code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
from typing import cast from pytest import raises from graphql import graphql_sync from graphql.type import ( GraphQLArgument, GraphQLBoolean, GraphQLEnumType, GraphQLEnumValue, GraphQLField, GraphQLFloat, GraphQLID, GraphQLInt, GraphQLObjectType, GraphQLSchema, GraphQLString, assert_enum_type, ) from graphql.utilities import ( build_schema, build_client_schema, introspection_from_schema, print_schema, ) from graphql.utilities.get_introspection_query import ( IntrospectionEnumType, IntrospectionInputObjectType, IntrospectionInterfaceType, IntrospectionObjectType, IntrospectionType, IntrospectionUnionType, ) from ..utils import dedent def cycle_introspection(sdl_string: str): """Test that the client side introspection gives the same result. This function does a full cycle of going from a string with the contents of the SDL, build in-memory GraphQLSchema from it, produce a client-side representation of the schema by using "build_client_schema" and then return that schema printed as SDL. """ server_schema = build_schema(sdl_string) initial_introspection = introspection_from_schema(server_schema) client_schema = build_client_schema(initial_introspection) # If the client then runs the introspection query against the client-side schema, # it should get a result identical to what was returned by the server second_introspection = introspection_from_schema(client_schema) # If the client then runs the introspection query against the client-side # schema, it should get a result identical to what was returned by the server. assert initial_introspection == second_introspection return print_schema(client_schema) def describe_type_system_build_schema_from_introspection(): def builds_a_simple_schema(): sdl = dedent( ''' """Simple schema""" schema { query: Simple } """This is a simple type""" type Simple { """This is a string field""" string: String } ''' ) assert cycle_introspection(sdl) == sdl def builds_a_schema_without_the_query_type(): sdl = dedent( """ type Query { foo: String } """ ) schema = build_schema(sdl) introspection = introspection_from_schema(schema) del introspection["__schema"]["queryType"] # type: ignore client_schema = build_client_schema(introspection) assert client_schema.query_type is None assert print_schema(client_schema) == sdl def builds_a_simple_schema_with_all_operation_types(): sdl = dedent( ''' schema { query: QueryType mutation: MutationType subscription: SubscriptionType } """This is a simple mutation type""" type MutationType { """Set the string field""" string: String } """This is a simple query type""" type QueryType { """This is a string field""" string: String } """This is a simple subscription type""" type SubscriptionType { """This is a string field""" string: String } ''' ) assert cycle_introspection(sdl) == sdl def uses_built_in_scalars_when_possible(): sdl = dedent( """ scalar CustomScalar type Query { int: Int float: Float string: String boolean: Boolean id: ID custom: CustomScalar } """ ) assert cycle_introspection(sdl) == sdl schema = build_schema(sdl) introspection = introspection_from_schema(schema) client_schema = build_client_schema(introspection) # Built-ins are used assert client_schema.get_type("Int") is GraphQLInt assert client_schema.get_type("Float") is GraphQLFloat assert client_schema.get_type("String") is GraphQLString assert client_schema.get_type("Boolean") is GraphQLBoolean assert client_schema.get_type("ID") is GraphQLID # Custom are built custom_scalar = schema.get_type("CustomScalar") assert client_schema.get_type("CustomScalar") is not custom_scalar def includes_standard_types_only_if_they_are_used(): schema = build_schema( """ type Query { foo: String } """ ) introspection = introspection_from_schema(schema) client_schema = build_client_schema(introspection) assert client_schema.get_type("Int") is None assert client_schema.get_type("Float") is None assert client_schema.get_type("ID") is None def builds_a_schema_with_a_recursive_type_reference(): sdl = dedent( """ schema { query: Recur } type Recur { recur: Recur } """ ) assert cycle_introspection(sdl) == sdl def builds_a_schema_with_a_circular_type_reference(): sdl = dedent( """ type Dog { bestFriend: Human } type Human { bestFriend: Dog } type Query { dog: Dog human: Human } """ ) assert cycle_introspection(sdl) == sdl def builds_a_schema_with_an_interface(): sdl = dedent( ''' type Dog implements Friendly { bestFriend: Friendly } interface Friendly { """The best friend of this friendly thing""" bestFriend: Friendly } type Human implements Friendly { bestFriend: Friendly } type Query { friendly: Friendly } ''' ) assert cycle_introspection(sdl) == sdl def builds_a_schema_with_an_interface_hierarchy(): sdl = dedent( ''' type Dog implements Friendly & Named { bestFriend: Friendly name: String } interface Friendly implements Named { """The best friend of this friendly thing""" bestFriend: Friendly name: String } type Human implements Friendly & Named { bestFriend: Friendly name: String } interface Named { name: String } type Query { friendly: Friendly } ''' ) assert cycle_introspection(sdl) == sdl def builds_a_schema_with_an_implicit_interface(): sdl = dedent( ''' type Dog implements Friendly { bestFriend: Friendly } interface Friendly { """The best friend of this friendly thing""" bestFriend: Friendly } type Query { dog: Dog } ''' ) assert cycle_introspection(sdl) == sdl def builds_a_schema_with_a_union(): sdl = dedent( """ type Dog { bestFriend: Friendly } union Friendly = Dog | Human type Human { bestFriend: Friendly } type Query { friendly: Friendly } """ ) assert cycle_introspection(sdl) == sdl def builds_a_schema_with_complex_field_values(): sdl = dedent( """ type Query { string: String listOfString: [String] nonNullString: String! nonNullListOfString: [String]! nonNullListOfNonNullString: [String!]! } """ ) assert cycle_introspection(sdl) == sdl def builds_a_schema_with_field_arguments(): sdl = dedent( ''' type Query { """A field with a single arg""" one( """This is an int arg""" intArg: Int ): String """A field with a two args""" two( """This is an list of int arg""" listArg: [Int] """This is a required arg""" requiredArg: Boolean! ): String } ''' ) assert cycle_introspection(sdl) == sdl def builds_a_schema_with_default_value_on_custom_scalar_field(): sdl = dedent( """ scalar CustomScalar type Query { testField(testArg: CustomScalar = "default"): String } """ ) assert cycle_introspection(sdl) == sdl def builds_a_schema_with_an_enum(): food_enum = GraphQLEnumType( "Food", { "VEGETABLES": GraphQLEnumValue( 1, description="Foods that are vegetables." ), "FRUITS": GraphQLEnumValue(2), "OILS": GraphQLEnumValue(3, deprecation_reason="Too fatty."), }, description="Varieties of food stuffs", ) schema = GraphQLSchema( GraphQLObjectType( "EnumFields", { "food": GraphQLField( food_enum, args={ "kind": GraphQLArgument( food_enum, description="what kind of food?" ) }, description="Repeats the arg you give it", ) }, ) ) introspection = introspection_from_schema(schema) client_schema = build_client_schema(introspection) second_introspection = introspection_from_schema(client_schema) assert second_introspection == introspection # It's also an Enum type on the client. client_food_enum = assert_enum_type(client_schema.get_type("Food")) # Client types do not get server-only values, so the values mirror the names, # rather than using the integers defined in the "server" schema. values = { name: value.to_kwargs() for name, value in client_food_enum.values.items() } assert values == { "VEGETABLES": { "value": "VEGETABLES", "description": "Foods that are vegetables.", "deprecation_reason": None, "extensions": {}, "ast_node": None, }, "FRUITS": { "value": "FRUITS", "description": None, "deprecation_reason": None, "extensions": {}, "ast_node": None, }, "OILS": { "value": "OILS", "description": None, "deprecation_reason": "Too fatty.", "extensions": {}, "ast_node": None, }, } def builds_a_schema_with_an_input_object(): sdl = dedent( ''' """An input address""" input Address { """What street is this address?""" street: String! """The city the address is within?""" city: String! """The country (blank will assume USA).""" country: String = "USA" } type Query { """Get a geocode from an address""" geocode( """The address to lookup""" address: Address ): String } ''' ) assert cycle_introspection(sdl) == sdl def builds_a_schema_with_field_arguments_with_default_values(): sdl = dedent( """ input Geo { lat: Float lon: Float } type Query { defaultInt(intArg: Int = 30): String defaultList(listArg: [Int] = [1, 2, 3]): String defaultObject(objArg: Geo = {lat: 37.485, lon: -122.148}): String defaultNull(intArg: Int = null): String noDefault(intArg: Int): String } """ ) assert cycle_introspection(sdl) == sdl def builds_a_schema_with_custom_directives(): sdl = dedent( ''' """This is a custom directive""" directive @customDirective repeatable on FIELD type Query { string: String } ''' ) assert cycle_introspection(sdl) == sdl def builds_a_schema_without_directives(): sdl = dedent( """ type Query { foo: String } """ ) schema = build_schema(sdl) introspection = introspection_from_schema(schema) del introspection["__schema"]["directives"] # type: ignore client_schema = build_client_schema(introspection) assert schema.directives assert client_schema.directives == () assert print_schema(client_schema) == sdl def builds_a_schema_aware_of_deprecation(): sdl = dedent( ''' directive @someDirective( """This is a shiny new argument""" shinyArg: SomeInputObject """This was our design mistake :(""" oldArg: String @deprecated(reason: "Use shinyArg") ) on QUERY enum Color { """So rosy""" RED """So grassy""" GREEN """So calming""" BLUE """So sickening""" MAUVE @deprecated(reason: "No longer in fashion") } input SomeInputObject { """Nothing special about it, just deprecated for some unknown reason""" oldField: String @deprecated(reason: "Don't use it, use newField instead!") """Same field but with a new name""" newField: String } type Query { """This is a shiny string field""" shinyString: String """This is a deprecated string field""" deprecatedString: String @deprecated(reason: "Use shinyString") """Color of a week""" color: Color """Some random field""" someField( """This is a shiny new argument""" shinyArg: SomeInputObject """This was our design mistake :(""" oldArg: String @deprecated(reason: "Use shinyArg") ): String } ''' # noqa: E501 ) assert cycle_introspection(sdl) == sdl def builds_a_schema_with_empty_deprecation_reasons(): sdl = dedent( """ directive @someDirective(someArg: SomeInputObject @deprecated(reason: "")) on QUERY type Query { someField(someArg: SomeInputObject @deprecated(reason: "")): SomeEnum @deprecated(reason: "") } input SomeInputObject { someInputField: String @deprecated(reason: "") } enum SomeEnum { SOME_VALUE @deprecated(reason: "") } """ # noqa: E501 ) assert cycle_introspection(sdl) == sdl def builds_a_schema_with_specified_by_url(): sdl = dedent( """ scalar Foo @specifiedBy(url: "https://example.com/foo_spec") type Query { foo: Foo } """ ) assert cycle_introspection(sdl) == sdl def can_use_client_schema_for_limited_execution(): schema = build_schema( """ scalar CustomScalar type Query { foo(custom1: CustomScalar, custom2: CustomScalar): String } """ ) introspection = introspection_from_schema(schema) client_schema = build_client_schema(introspection) class Data: foo = "bar" unused = "value" result = graphql_sync( client_schema, "query Limited($v: CustomScalar) { foo(custom1: 123, custom2: $v) }", root_value=Data(), variable_values={"v": "baz"}, ) assert result.data == {"foo": "bar"} def can_build_invalid_schema(): schema = build_schema("type Query", assume_valid=True) introspection = introspection_from_schema(schema) client_schema = build_client_schema(introspection, assume_valid=True) assert client_schema.to_kwargs()["assume_valid"] is True def describe_throws_when_given_invalid_introspection(): dummy_schema = build_schema( """ type Query { foo(bar: String): String } interface SomeInterface { foo: String } union SomeUnion = Query enum SomeEnum { FOO } input SomeInputObject { foo: String } directive @SomeDirective on QUERY """ ) def throws_when_introspection_is_missing_schema_property(): with raises(TypeError) as exc_info: # noinspection PyTypeChecker build_client_schema(None) # type: ignore assert str(exc_info.value) == ( "Invalid or incomplete introspection result. Ensure that you" " are passing the 'data' attribute of an introspection response" " and no 'errors' were returned alongside: None." ) with raises(TypeError) as exc_info: # noinspection PyTypeChecker build_client_schema({}) # type: ignore assert str(exc_info.value) == ( "Invalid or incomplete introspection result. Ensure that you" " are passing the 'data' attribute of an introspection response" " and no 'errors' were returned alongside: {}." ) def throws_when_referenced_unknown_type(): introspection = introspection_from_schema(dummy_schema) introspection["__schema"]["types"] = [ type_ for type_ in introspection["__schema"]["types"] if type_["name"] != "Query" ] with raises(TypeError) as exc_info: build_client_schema(introspection) assert str(exc_info.value) == ( "Invalid or incomplete schema, unknown type: Query." " Ensure that a full introspection query is used" " in order to build a client schema." ) def throws_when_missing_definition_for_one_of_the_standard_scalars(): schema = build_schema( """ type Query { foo: Float } """ ) introspection = introspection_from_schema(schema) introspection["__schema"]["types"] = [ type_ for type_ in introspection["__schema"]["types"] if type_["name"] != "Float" ] with raises(TypeError) as exc_info: build_client_schema(introspection) assert str(exc_info.value).endswith( "Invalid or incomplete schema, unknown type: Float." " Ensure that a full introspection query is used" " in order to build a client schema." ) def throws_when_type_reference_is_missing_name(): introspection = introspection_from_schema(dummy_schema) query_type = cast(IntrospectionType, introspection["__schema"]["queryType"]) assert query_type["name"] == "Query" del query_type["name"] # type: ignore with raises(TypeError) as exc_info: build_client_schema(introspection) assert str(exc_info.value) == "Unknown type reference: {}." def throws_when_missing_kind(): introspection = introspection_from_schema(dummy_schema) query_type_introspection = next( type_ for type_ in introspection["__schema"]["types"] if type_["name"] == "Query" ) assert query_type_introspection["kind"] == "OBJECT" del query_type_introspection["kind"] with raises( TypeError, match=r"^Invalid or incomplete introspection result\." " Ensure that a full introspection query is used" r" in order to build a client schema: {'name': 'Query', .*}\.$", ): build_client_schema(introspection) def throws_when_missing_interfaces(): introspection = introspection_from_schema(dummy_schema) query_type_introspection = cast( IntrospectionObjectType, next( type_ for type_ in introspection["__schema"]["types"] if type_["name"] == "Query" ), ) assert query_type_introspection["interfaces"] == [] del query_type_introspection["interfaces"] # type: ignore with raises( TypeError, match="^Query interfaces cannot be resolved." " Introspection result missing interfaces:" r" {'kind': 'OBJECT', 'name': 'Query', .*}\.$", ): build_client_schema(introspection) def legacy_support_for_interfaces_with_null_as_interfaces_field(): introspection = introspection_from_schema(dummy_schema) some_interface_introspection = cast( IntrospectionInterfaceType, next( type_ for type_ in introspection["__schema"]["types"] if type_["name"] == "SomeInterface" ), ) assert some_interface_introspection["interfaces"] == [] some_interface_introspection["interfaces"] = None # type: ignore client_schema = build_client_schema(introspection) assert print_schema(client_schema) == print_schema(dummy_schema) def throws_when_missing_fields(): introspection = introspection_from_schema(dummy_schema) query_type_introspection = cast( IntrospectionObjectType, next( type_ for type_ in introspection["__schema"]["types"] if type_["name"] == "Query" ), ) assert query_type_introspection["fields"] del query_type_introspection["fields"] # type: ignore with raises( TypeError, match="^Query fields cannot be resolved." " Introspection result missing fields:" r" {'kind': 'OBJECT', 'name': 'Query', .*}\.$", ): build_client_schema(introspection) def throws_when_missing_field_args(): introspection = introspection_from_schema(dummy_schema) query_type_introspection = cast( IntrospectionObjectType, next( type_ for type_ in introspection["__schema"]["types"] if type_["name"] == "Query" ), ) field = query_type_introspection["fields"][0] assert field["args"] del field["args"] # type: ignore with raises( TypeError, match="^Query fields cannot be resolved." r" Introspection result missing field args: {'name': 'foo', .*}\.$", ): build_client_schema(introspection) def throws_when_output_type_is_used_as_an_arg_type(): introspection = introspection_from_schema(dummy_schema) query_type_introspection = cast( IntrospectionObjectType, next( type_ for type_ in introspection["__schema"]["types"] if type_["name"] == "Query" ), ) arg = query_type_introspection["fields"][0]["args"][0] assert arg["type"]["name"] == "String" arg["type"]["name"] = "SomeUnion" with raises(TypeError) as exc_info: build_client_schema(introspection) assert str(exc_info.value).startswith( "Query fields cannot be resolved." " Introspection must provide input type for arguments," " but received: SomeUnion." ) def throws_when_output_type_is_used_as_an_input_value_type(): introspection = introspection_from_schema(dummy_schema) input_object_type_introspection = cast( IntrospectionInputObjectType, next( type_ for type_ in introspection["__schema"]["types"] if type_["name"] == "SomeInputObject" ), ) input_field = input_object_type_introspection["inputFields"][0] assert input_field["type"]["name"] == "String" input_field["type"]["name"] = "SomeUnion" with raises(TypeError) as exc_info: build_client_schema(introspection) assert str(exc_info.value).startswith( "SomeInputObject fields cannot be resolved." " Introspection must provide input type for input fields," " but received: SomeUnion." ) def throws_when_input_type_is_used_as_a_field_type(): introspection = introspection_from_schema(dummy_schema) query_type_introspection = cast( IntrospectionObjectType, next( type_ for type_ in introspection["__schema"]["types"] if type_["name"] == "Query" ), ) field = query_type_introspection["fields"][0] assert field["type"]["name"] == "String" field["type"]["name"] = "SomeInputObject" with raises(TypeError) as exc_info: build_client_schema(introspection) assert str(exc_info.value).startswith( "Query fields cannot be resolved." " Introspection must provide output type for fields," " but received: SomeInputObject." ) def throws_when_missing_possible_types(): introspection = introspection_from_schema(dummy_schema) some_union_introspection = cast( IntrospectionUnionType, next( type_ for type_ in introspection["__schema"]["types"] if type_["name"] == "SomeUnion" ), ) assert some_union_introspection["possibleTypes"] del some_union_introspection["possibleTypes"] # type: ignore with raises( TypeError, match="^Introspection result missing possibleTypes:" r" {'kind': 'UNION', 'name': 'SomeUnion', .*}\.$", ): build_client_schema(introspection) def throws_when_missing_enum_values(): introspection = introspection_from_schema(dummy_schema) some_enum_introspection = cast( IntrospectionEnumType, next( type_ for type_ in introspection["__schema"]["types"] if type_["name"] == "SomeEnum" ), ) assert some_enum_introspection["enumValues"] del some_enum_introspection["enumValues"] # type: ignore with raises( TypeError, match="^Introspection result missing enumValues:" r" {'kind': 'ENUM', 'name': 'SomeEnum', .*}\.$", ): build_client_schema(introspection) def throws_when_missing_input_fields(): introspection = introspection_from_schema(dummy_schema) some_input_object_introspection = cast( IntrospectionInputObjectType, next( type_ for type_ in introspection["__schema"]["types"] if type_["name"] == "SomeInputObject" ), ) assert some_input_object_introspection["inputFields"] del some_input_object_introspection["inputFields"] # type: ignore with raises( TypeError, match="^Introspection result missing inputFields:" r" {'kind': 'INPUT_OBJECT', 'name': 'SomeInputObject', .*}\.$", ): build_client_schema(introspection) def throws_when_missing_directive_locations(): introspection = introspection_from_schema(dummy_schema) some_directive_introspection = introspection["__schema"]["directives"][0] assert some_directive_introspection["name"] == "SomeDirective" assert some_directive_introspection["locations"] == ["QUERY"] del some_directive_introspection["locations"] # type: ignore with raises( TypeError, match="^Introspection result missing directive locations:" r" {'name': 'SomeDirective', .*}\.$", ): build_client_schema(introspection) def throws_when_missing_directive_args(): introspection = introspection_from_schema(dummy_schema) some_directive_introspection = introspection["__schema"]["directives"][0] assert some_directive_introspection["name"] == "SomeDirective" assert some_directive_introspection["args"] == [] del some_directive_introspection["args"] # type: ignore with raises( TypeError, match="^Introspection result missing directive args:" r" {'name': 'SomeDirective', .*}\.$", ): build_client_schema(introspection) def describe_very_deep_decorators_are_not_supported(): def fails_on_very_deep_lists_more_than_7_levels(): schema = build_schema( """ type Query { foo: [[[[[[[[String]]]]]]]] } """ ) introspection = introspection_from_schema(schema) with raises(TypeError) as exc_info: build_client_schema(introspection) assert str(exc_info.value) == ( "Query fields cannot be resolved." " Decorated type deeper than introspection query." ) def fails_on_a_very_deep_non_null_more_than_7_levels(): schema = build_schema( """ type Query { foo: [[[[String!]!]!]!] } """ ) introspection = introspection_from_schema(schema) with raises(TypeError) as exc_info: build_client_schema(introspection) assert str(exc_info.value) == ( "Query fields cannot be resolved." " Decorated type deeper than introspection query." ) def succeeds_on_deep_types_less_or_equal_7_levels(): # e.g., fully non-null 3D matrix sdl = dedent( """ type Query { foo: [[[String!]!]!]! } """ ) assert cycle_introspection(sdl) == sdl def describe_prevents_infinite_recursion_on_invalid_introspection(): def recursive_interfaces(): sdl = """ type Query { foo: Foo } type Foo { foo: String } """ schema = build_schema(sdl, assume_valid=True) introspection = introspection_from_schema(schema) foo_introspection = cast( IntrospectionObjectType, next( type_ for type_ in introspection["__schema"]["types"] if type_["name"] == "Foo" ), ) assert foo_introspection["interfaces"] == [] # we need to patch here since invalid interfaces cannot be built with Python foo_introspection["interfaces"] = [ {"kind": "OBJECT", "name": "Foo", "ofType": None} ] with raises(TypeError) as exc_info: build_client_schema(introspection) assert str(exc_info.value) == ( "Foo interfaces cannot be resolved." " Expected Foo to be a GraphQL Interface type." ) def recursive_union(): sdl = """ type Query { foo: Foo } union Foo """ schema = build_schema(sdl, assume_valid=True) introspection = introspection_from_schema(schema) foo_introspection = next( type_ for type_ in introspection["__schema"]["types"] if type_["name"] == "Foo" ) assert foo_introspection["kind"] == "UNION" assert foo_introspection["possibleTypes"] == [] # we need to patch here since invalid unions cannot be built with Python foo_introspection["possibleTypes"] = [ {"kind": "UNION", "name": "Foo", "ofType": None} ] with raises(TypeError) as exc_info: build_client_schema(introspection) assert str(exc_info.value) == ( "Foo types cannot be resolved." " Expected Foo to be a GraphQL Object type." )
graphql-python/graphql-core
tests/utilities/test_build_client_schema.py
Python
mit
35,277
import { withStyles } from '@material-ui/core/styles'; import cx from 'clsx'; export const SideSection = withStyles(theme => ({ aside: { [theme.breakpoints.up('md')]: { minWidth: 0, flex: 1, padding: '0 20px', background: theme.palette.background.paper, borderRadius: theme.shape.borderRadius, }, }, }))(({ classes, children, className, ...props }) => { return ( <aside className={cx(classes.aside, className)} {...props}> {children} </aside> ); }); export const SideSectionHeader = withStyles(theme => ({ asideHeader: { lineHeight: '20px', padding: '12px 0', fontWeight: 700, [theme.breakpoints.up('md')]: { padding: '20px 0 12px', borderBottom: `1px solid ${theme.palette.secondary[500]}`, }, }, }))(({ classes, children, className, ...props }) => { return ( <header className={cx(classes.asideHeader, className)} {...props}> {children} </header> ); }); export const SideSectionLinks = withStyles(theme => ({ asideItems: { display: 'flex', flexFlow: 'row', overflowX: 'auto', '--gutter': `${theme.spacing(2)}px`, margin: `0 calc(-1 * var(--gutter))`, padding: `0 var(--gutter)`, '&::after': { // Right-most gutter after the last item content: '""', flex: '0 0 var(--gutter)', }, [theme.breakpoints.up('sm')]: { '--gutter': `${theme.spacing(3)}px`, }, [theme.breakpoints.up('md')]: { '--gutter': 0, flexFlow: 'column', overflowX: 'visible', '&::after': { display: 'none', }, }, }, }))(({ classes, children, className, ...props }) => { return ( <div className={cx(classes.asideItems, className)} {...props}> {children} </div> ); }); export const SideSectionLink = withStyles(theme => ({ asideItem: { // override <a> defaults textDecoration: 'none', color: 'inherit', cursor: 'pointer', [theme.breakpoints.down('sm')]: { padding: 16, background: theme.palette.background.paper, borderRadius: theme.shape.borderRadius, flex: '0 0 320px', maxWidth: '66vw', '& + &': { marginLeft: 12, }, }, [theme.breakpoints.up('md')]: { padding: '16px 0', '& + &': { borderTop: `1px solid ${theme.palette.secondary[100]}`, }, }, }, }))(({ classes, children, className, ...props }) => { return ( <a className={cx(classes.asideItem, className)} {...props}> {children} </a> ); }); export const SideSectionText = withStyles(() => ({ asideText: { display: '-webkit-box', overflow: 'hidden', boxOrient: 'vertical', textOverflow: 'ellipsis', lineClamp: 5, }, }))(({ classes, children, className, ...props }) => { return ( <article className={cx(classes.asideText, className)} {...props}> {children} </article> ); });
cofacts/rumors-site
components/SideSection.js
JavaScript
mit
2,921
var $topnav = $('#topnav-row .col'); var $sidebar = $('#main-row .sidebar'); var $main = $('#main-row .main'); $(document).on('click', '.on-sidebar-toggler', function (e) { $sidebar.toggleClass('col-md-3 col-lg-2 d-md-block col-12'); $topnav.toggleClass('d-md-none'); $main.toggleClass('col-md-9 col-lg-10 col-12'); });
osalabs/osafw-asp.net
www/App_Data/template/layout/common.js
JavaScript
mit
334
/** * @jsx React.DOM */ /* not used but thats how you can use touch events * */ //React.initializeTouchEvents(true); /* not used but thats how you can use animation and other transition goodies * */ var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup; /** * we will use yes for true * we will use no for false * * React has some built ins that rely on state being true/false like classSet() * and these will not work with yes/no but can easily be modified / reproduced * * this single app uses the yes/no var so if you want you can switch back to true/false * * */ var yes = 'yes', no = 'no'; //var yes = true, no = false; /* bootstrap components * */ var Flash = ReactBootstrap.Alert; var Btn = ReactBootstrap.Button; var Modal = ReactBootstrap.Modal; /* create the container object * */ var snowUI = { passthrough: {}, //special for passing functions between components }; /* create flash message * */ snowUI.SnowpiFlash = React.createClass({displayName: 'SnowpiFlash', getInitialState: function() { return { isVisible: true }; }, getDefaultProps: function() { return ({showclass:'info'}); }, render: function() { snowlog.log(this.props); if(!this.state.isVisible) return null; var message = this.props.message ? this.props.message : this.props.children; return ( Flash({bsStyle: this.props.showclass, onDismiss: this.dismissFlash}, React.DOM.p(null, message) ) ); }, dismissFlash: function() { this.setState({isVisible: false}); } }); /* my little man component * simple example * */ snowUI.SnowpiMan = React.createClass({displayName: 'SnowpiMan', getDefaultProps: function() { return ({divstyle:{float:'right',}}); }, render: function() { return this.transferPropsTo( React.DOM.div({style: this.props.divstyle, dangerouslySetInnerHTML: {__html: snowtext.logoman}}) ); } }); /** * menu components * */ //main snowUI.leftMenu = React.createClass({displayName: 'leftMenu', getInitialState: function() { return ({ config:this.props.config || {section:snowPath.wallet,wallet:'all',moon:'overview'} }) }, componentWillReceiveProps: function(nextProps) { if(nextProps.config)this.setState({config:nextProps.config}) }, render: function() { var showmenu if(this.state.config.section === snowPath.wallet) { if(this.state.config.wallet && this.state.config.wallet !== 'new') showmenu = snowUI.walletMenu else showmenu = snowUI.defaultMenu } else if(this.state.config.section === snowPath.receive || this.state.config.section === snowPath.settings) { showmenu = snowUI.receiveMenu } else { showmenu = snowUI.defaultMenu } snowlog.log('main menu component',this.state.config) return ( React.DOM.div(null, showmenu({config: this.state.config}), " ") ); } }); //wallet menu snowUI.walletMenu = React.createClass({displayName: 'walletMenu', getInitialState: function() { return ({ config:this.props.config || {section:snowPath.wallet,wallet:false,moon:false} }) }, componentWillReceiveProps: function(nextProps) { if(nextProps.config)this.setState({config:nextProps.config}) }, componentDidUpdate: function() { $('.dogemenulink').removeClass('active'); var moon = this.state.config.moon if(!moon && this.state.config.wallet !== 'new')moon = 'dashboard' $('.dogemenulink[data-snowmoon="'+moon+'"]').addClass('active'); }, componentDidMount: function() { this.componentDidUpdate() }, menuClick: function(e) { e.preventDefault(); var moon = $(e.target).parent()[0].dataset.snowmoon; snowUI.methods.valueRoute(snowPath.wallet + '/' + this.state.config.wallet + '/' + moon); return false }, render: function() { snowlog.log('wallet menu component') return ( React.DOM.div(null, React.DOM.div({id: "menuwallet"}, React.DOM.a({onClick: this.menuClick, 'data-snowmoon': "dashboard", id: "dogedash", 'data-container': "#menuspy", title: "", className: "dogemenulink ", 'data-original-title': "Dashboard"}, " ", React.DOM.span({className: "glyphicon glyphicon-th"}), " Dashboard"), React.DOM.a({onClick: this.menuClick, 'data-snowmoon': "accounts", id: "dogeacc", 'data-container': "#menuspy", title: "", className: "dogemenulink", 'data-original-title': "manage wallet accounts"}, " ", React.DOM.span({className: "glyphicon glyphicon-list"}), " Accounts"), React.DOM.a({onClick: this.menuClick, 'data-snowmoon': "send", id: "dogesend", 'data-container': "#menuspy", title: "", className: "dogemenulink", 'data-original-title': "send coins"}, " ", React.DOM.span({className: "glyphicon glyphicon-share"}), " Send"), React.DOM.a({onClick: this.menuClick, 'data-snowmoon': "transactions", id: "dogetx", 'data-container': "#menuspy", title: "", className: "dogemenulink", 'data-original-title': "sortable transaction list"}, " ", React.DOM.span({className: "glyphicon glyphicon-list-alt"}), " Transactions"), React.DOM.a({onClick: this.menuClick, 'data-snowmoon': "update", id: "dogeupdate", 'data-container': "#menuspy", title: "", className: "dogemenulink", 'data-original-title': "update wallet"}, React.DOM.span({className: "glyphicon glyphicon-pencil"}), " Update ", React.DOM.span({id: "updatecoinspan", style: {display:"none"}})) ), "- ") ); } }); //main menu snowUI.receiveMenu = React.createClass({displayName: 'receiveMenu', getInitialState: function() { return ({ config:this.props.config || {section:snowPath.wallet,wallet:'all',moon:'overview'} }) }, componentWillReceiveProps: function(nextProps) { if(nextProps.config)this.setState({config:nextProps.config}) }, componentDidUpdate: function() { $('.dogedccmenulink').removeClass('active'); $('.dogedccmenulink[data-snowmoon="'+this.state.config.section+'"]').addClass('active'); }, menuClick: function(e) { e.preventDefault(); var moon = $(e.target).parent()[0].dataset.snowmoon; snowUI.methods.valueRoute(moon); return false }, render: function() { snowlog.log('receive menu component') return ( React.DOM.div(null, React.DOM.div({id: "menudcc"}, React.DOM.a({onClick: this.menuClick, 'data-snowmoon': snowPath.receive, id: "dogedccsetup", 'data-container': "#menuspy", title: "", className: "dogedccmenulink", 'data-original-title': "Receive coins from strangers. (friends too)"}, " ", React.DOM.span({className: "glyphicon glyphicon-tasks"}), " Receivers"), React.DOM.a({onClick: this.menuClick, 'data-snowmoon': snowPath.wallet, id: "dogewallets", 'data-container': "#menuspy", title: "", className: "dogedccmenulink", 'data-original-title': "Digital Coin Wallets"}, " ", React.DOM.span({className: "glyphicon glyphicon-briefcase"}), " Wallets"), React.DOM.a({onClick: this.menuClick, 'data-snowmoon': snowPath.settings, id: "dogedccsettings", 'data-container': "#menuspy", title: "", className: "dogedccmenulink", 'data-original-title': "Digital Coin Coordinator settings"}, " ", React.DOM.span({className: "glyphicon glyphicon-cog"}), " Settings") ) ) ); } }); //default snowUI.defaultMenu = snowUI.receiveMenu //wallet select snowUI.walletSelect = React.createClass({displayName: 'walletSelect', componentDidMount: function() { this.updateSelect(); }, componentDidUpdate: function() { this.updateSelect(); }, componentWillUpdate: function() { $("#walletselect").selectbox("detach"); }, updateSelect: function() { var _this = this $("#walletselect").selectbox({ onChange: function (val, inst) { _this.props.route(val) }, effect: "fade" }); //snowlog.log('wallet select updated') }, render: function() { var wallets; if(this.props.wally instanceof Array) { var wallets = this.props.wally.map(function (w) { return ( React.DOM.option({key: w.key, value: snowPath.wallet + '/' + w.key}, w.name) ); }); } if(this.props.section === snowPath.wallet) { var _df = (this.props.wallet) ? snowPath.wallet + '/' + this.props.wallet : snowPath.wallet; } else { var _df = this.props.section; } //snowlog.log(_df) return this.transferPropsTo( React.DOM.div({className: "list"}, React.DOM.div({className: "walletmsg", style: {display:'none'}}), React.DOM.select({onChange: this.props.route, id: "walletselect", value: _df}, wallets, React.DOM.optgroup(null), React.DOM.option({value: snowPath.wallet + '/new'}, snowtext.menu.plus.name), React.DOM.option({value: snowPath.wallet}, snowtext.menu.list.name), React.DOM.option({value: snowPath.receive}, snowtext.menu.receive.name), React.DOM.option({value: snowPath.settings}, snowtext.menu.settings.name), React.DOM.option({value: snowPath.inq}, snowtext.menu.inqueue.name) ) ) ); } }); var UI = React.createClass({displayName: 'UI', getInitialState: function() { /** * initialize the app * the plan is to keep only active references in root state. * we should use props for the fill outs * */ var _this = this snowUI.methods = { hrefRoute: _this.hrefRoute, valueRoute: _this.valueRoute, updateState: _this.updateState, loaderStart: _this.loaderStart, loaderStop: _this.loaderStop, config: _this.config(), fadeOut: function () { $('#maindiv').removeClass('reactfade-enter reactfade-enter-active'); $('#maindiv').addClass('reactfade-leave reactfade-leave-active'); }, fadeIn: function () { $('#maindiv').removeClass('reactfade-leave reactfade-leave-active'); $('#maindiv').addClass('reactfade-enter-active'); }, } return { section: this.props.section || 'wallet', moon: this.props.moon || false, wallet: this.props.wallet || false, mywallets: [], locatewallet: [], mounted:false }; }, //set up the config object config: function() { var _this = this if(this.state) { return { section:_this.state.section, wallet:_this.state.wallet, moon:_this.state.moon, mywallets: _this.state.mywallets, locatewallet: _this.state.locatewallet } } }, componentDidMount: function() { if(!this.state.mounted) { this.getWallets() } }, getWallets: function () { //grab our initial data snowlog.log('run on mount') $.ajax({url: "/api/snowcoins/local/change-wallet"}) .done(function( resp,status,xhr ) { _csrf = xhr.getResponseHeader("x-snow-token"); snowlog.log('wally',resp.wally) //wallets this.setState({mywallets:resp.wally}); //locater var a = []; var ix = resp.wally.length; for(i=0;i<ix;i++) { a[i]=resp.wally[i].key } this.setState({locatewallet:a}); this.setState({mounted:true}); }.bind(this)); }, componentWillReceiveProps: function(nextProps) { if(nextProps.section !== undefined)this.setState({section:nextProps.section}); if(nextProps.moon !== undefined)this.setState({moon:nextProps.moon}); if(nextProps.wallet !== undefined)this.setState({wallet:nextProps.wallet}); //wallet list if(nextProps.mywallets)this.setState({mywallets:nextProps.mywallets}); //if(nextProps.section)this.loaderStart() return false; }, componentWillUpdate: function() { this.loaderStart() return false }, updateState: function(prop,value) { this.setState({prop:value}); return false }, loaderStart: function() { $('.loader').fadeIn(); return false }, loaderStop: function() { $('.loader').delay(500).fadeOut("slow"); return false }, changeTheme: function() { var mbody = $('body'); if(mbody.hasClass('themeable-snowcoinslight')==true) { mbody.removeClass('themeable-snowcoinslight'); } else { mbody.addClass('themeable-snowcoinslight'); } return false }, valueRoute: function(route) { bone.router.navigate(snowPath.root + route, {trigger:true}); snowlog.log(snowPath.root + route) return false }, hrefRoute: function(route) { route.preventDefault(); bone.router.navigate(snowPath.root + $(route.target)[0].pathname, {trigger:true}); snowlog.log(snowPath.root + $(route.target)[0].pathname) return false }, eggy: function() { eggy(); }, render: function() { //set up our psuedo routes var comp = {} comp[snowPath.wallet]=snowUI.wallet; comp[snowPath.receive]=snowUI.receive; comp[snowPath.settings]=snowUI.settings; comp[snowPath.inq]=snowUI.inq; var mycomp = comp[this.state.section] snowlog.log('check state UI',this.state.mounted); if(this.state.mounted) { var mountwallet = function() { return (snowUI.walletSelect({route: this.valueRoute, section: this.state.section, wallet: this.state.wallet, wally: this.state.mywallets})) }.bind(this) var mountpages = function() { return (mycomp({methods: snowUI.methods, config: this.config()})) }.bind(this) } else { var mountwallet = function(){}; var mountpages = function(){}; } //mount return ( React.DOM.div({id: "snowpi-body"}, React.DOM.div({id: "walletbarspyhelper", style: {display:'block'}}), React.DOM.div({id: "walletbar", className: "affix"}, React.DOM.div({className: "wallet"}, React.DOM.div({className: "button-group"}, Btn({bsStyle: "link", 'data-toggle': "dropdown", className: "dropdown-toggle"}, snowtext.menu.menu.name), React.DOM.ul({className: "dropdown-menu", role: "menu"}, React.DOM.li({className: "nav-item-add"}, " ", React.DOM.a({onClick: this.hrefRoute, href: snowPath.wallet + '/new'}, snowtext.menu.plus.name)), React.DOM.li({className: "nav-item-home"}, " ", React.DOM.a({onClick: this.hrefRoute, href: snowPath.wallet}, snowtext.menu.list.name)), React.DOM.li({className: "nav-item-receive"}, React.DOM.a({onClick: this.hrefRoute, href: snowPath.receive}, snowtext.menu.receive.name)), React.DOM.li({className: "nav-item-settings"}, React.DOM.a({onClick: this.hrefRoute, href: snowPath.settings}, snowtext.menu.settings.name)), React.DOM.li({className: "divider"}), React.DOM.li({className: "nav-item-snowcat"}), React.DOM.li({className: "divider"}), React.DOM.li(null, React.DOM.div(null, React.DOM.div({onClick: this.changeTheme, className: "walletmenuspan changetheme bstooltip", title: "Switch between the light and dark theme", 'data-toggle': "tooltip", 'data-placement': "bottom", 'data-container': "body"}, React.DOM.span({className: "glyphicon glyphicon-adjust"})), React.DOM.div({className: "walletmenuspan bstooltip", title: "inquisive queue", 'data-toggle': "tooltip", 'data-placement': "bottom", 'data-container': "body"}, " ", React.DOM.a({onClick: this.hrefRoute, href: snowPath.inq, className: "nav-item-inq"})), React.DOM.div({className: "walletmenuspan bstooltip", title: "Logout", 'data-toggle': "tooltip", 'data-placement': "right", 'data-container': "body"}, " ", React.DOM.a({href: "/signout"}, " ", React.DOM.span({className: "glyphicon glyphicon-log-out"}))), React.DOM.div({className: "clearfix"}) ) ) ) ) ), mountwallet(), React.DOM.div({className: "logo", onClick: this.eggy}, React.DOM.a({title: "inquisive.io snowcoins build info", 'data-container': "body", 'data-placement': "bottom", 'data-toggle': "tooltip", className: "walletbar-logo"})) ), React.DOM.div({className: "container-fluid"}, React.DOM.div({id: "menuspy", className: "dogemenu col-xs-1 col-md-2", 'data-spy': "affix", 'data-offset-top': "0"}, snowUI.leftMenu({config: this.config()}) ), React.DOM.div({id: "menuspyhelper", className: "dogemenu col-xs-1 col-md-2"}), React.DOM.div({className: "dogeboard col-xs-11 col-md-10"}, snowUI.AppInfo(null), React.DOM.div({className: "dogeboard-left col-xs-12 col-md-12"}, mountpages() ) ) ) /* end snowpi-body */ ) ) } }); //app info snowUI.AppInfo = React.createClass({displayName: 'AppInfo', render: function() { return ( React.DOM.div({id: "easter-egg", style: {display:'none'}}, React.DOM.div(null, React.DOM.div({className: "blocks col-xs-offset-1 col-xs-10 col-md-offset-1 col-md-5 col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.h4(null, "Get Snowcoins"), React.DOM.div({className: "row"}, React.DOM.div({className: "col-sm-offset-1 col-sm-11"}, React.DOM.a({href: "https://github.com/inquisive/snowcoins", target: "_blank"}, "GitHub / Installation")), React.DOM.div({className: "col-sm-offset-1 col-sm-11"}, " ", React.DOM.a({href: "https://github.com/inquisive/snowcoins/latest.zip", target: "_blank"}, "Download zip"), " | ", React.DOM.a({href: "https://github.com/inquisive/snowcoins/latest.tar.gz", target: "_blank"}, "Download gz")) ), React.DOM.div({style: {borderBottom:'transparent 15px solid'}}), React.DOM.h4(null, "Built With"), React.DOM.div({className: "row"}, React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://nodejs.org", target: "_blank"}, "nodejs")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://keystonejs.com", target: "_blank"}, "KeystoneJS")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://getbootstrap.com/", target: "_blank"}, "Bootstrap")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://github.com/countable/node-dogecoin", target: "_blank"}, "node-dogecoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://mongoosejs.com/", target: "_blank"}, "mongoose")) ) ), React.DOM.div({className: "blocks col-xs-offset-1 col-xs-10 col-md-offset-1 col-md-5 col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.h4(null, "Donate"), React.DOM.div({className: "row"}, React.DOM.div({title: "iq", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, "iq: ", React.DOM.a({href: "https://inquisive.com/iq/snowkeeper", target: "_blank"}, "snowkeeper")), React.DOM.div({title: "Dogecoin", className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://snow.snowpi.org/share/dogecoin", target: "_blank"}, "Ðogecoin")), React.DOM.div({title: "Bitcoin", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "https://snow.snowpi.org/share/bitcoin", target: "_blank"}, "Bitcoin")), React.DOM.div({title: "Litecoin", className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://snow.snowpi.org/share/litecoin", target: "_blank"}, "Litecoin")), React.DOM.div({title: "Darkcoin", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "https://snow.snowpi.org/share/darkcoin", target: "_blank"}, "Darkcoin")) ), React.DOM.div({style: {borderBottom:'transparent 15px solid'}}), React.DOM.h4(null, "Digital Coin Wallets"), React.DOM.div({className: "row"}, React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://dogecoin.com", target: "_blank"}, "dogecoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://bitcoin.org", target: "_blank"}, "bitcoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://litecoin.org", target: "_blank"}, "litecoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://vertcoin.org", target: "_blank"}, "vertcoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://octocoin.org", target: "_blank"}, "888")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://auroracoin.org", target: "_blank"}, "auroracoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://blackcoin.co", target: "_blank"}, "blackcoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://digibyte.co", target: "_blank"}, "digibyte")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://digitalcoin.co", target: "_blank"}, "digitalcoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://darkcoin.io", target: "_blank"}, "darkcoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://maxcoin.co.uk", target: "_blank"}, "maxcoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://mintcoin.co", target: "_blank"}, "mintcoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://einsteinium.org", target: "_blank"}, "einsteinium")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://peercoin.net", target: "_blank"}, "peercoin ")) ), React.DOM.div({className: "row"} ) ), React.DOM.div({className: "clearfix"}) ) ) ); } });
inquisive/wallet-manager
public/js/.module-cache/ab49b1cc9df6578c57e04eb43cab7040e5bdb3ee.js
JavaScript
mit
21,475
package jp.gr.java_conf.kgd.library.cool.jsfml.actor.parts.scroll.bar; public interface IConstScrollbarController { boolean isVertical(); float getSliderPositionRate(); float getSliderLengthRate(); }
t-kgd/library-cool
cool-jsfml/src/main/java/jp/gr/java_conf/kgd/library/cool/jsfml/actor/parts/scroll/bar/IConstScrollbarController.java
Java
mit
206
response.title = "Enter H4H" response.subtitle = "Smart House4H Access Control" response.meta.keywords = "arduino hacker space" response.menu = [ (T('Gate'), False, URL('default','gate')), (T('Door'), False, URL('default','door')), (T('About'), False, URL('default','about')), ]
house4hack/openSHAC
web2py_shac/applications/enter/models/menu.py
Python
mit
282
<?xml version="1.0" ?><!DOCTYPE TS><TS language="es_MX" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Aleacoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;Aleacoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The Aleacoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Haga doble clic para editar el domicilio o la etiqueta</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Crear una dirección nueva</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copiar el domicilio seleccionado al portapapeles del sistema</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-46"/> <source>These are your Aleacoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Aleacoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified Aleacoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Borrar</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Archivo separado por comas (*.CSV)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Domicilio</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Ingrese la contraseña</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nueva contraseña</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Repita la nueva contraseña</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Ingrese la nueva contraseña a la cartera&lt;br/&gt;Por favor use una contraseña de&lt;b&gt;10 o más caracteres aleatorios&lt;/b&gt; o &lt;b&gt;ocho o más palabras&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Cartera encriptada.</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Esta operación necesita la contraseña de su cartera para desbloquear su cartera.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Desbloquear cartera.</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Esta operación necesita la contraseña de su cartera para desencriptar su cartera.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Desencriptar la cartera</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Cambiar contraseña</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Ingrese la antugüa y nueva contraseña de la cartera</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Confirmar la encriptación de cartera</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>Cartera encriptada</translation> </message> <message> <location line="-58"/> <source>Aleacoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>La encriptación de la cartera falló</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>La encriptación de la cartera falló debido a un error interno. Su cartera no fue encriptada.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>Las contraseñas dadas no coinciden</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>El desbloqueo de la cartera Fallo</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La contraseña ingresada para la des encriptación de la cartera es incorrecto</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>La desencriptación de la cartera fallo</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+282"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>Synchronizing with network...</source> <translation>Sincronizando con la red...</translation> </message> <message> <location line="-319"/> <source>&amp;Overview</source> <translation>&amp;Vista previa</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Mostrar la vista previa general de la cartera</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Transacciones</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Explorar el historial de transacciones</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation>S&amp;alir</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Salir de la aplicación</translation> </message> <message> <location line="+6"/> <source>Show information about Aleacoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opciones</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+259"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location line="-256"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Send coins to a Aleacoin address</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Modify configuration options for Aleacoin</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Cambiar la contraseña usada para la encriptación de la cartera</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-202"/> <source>Aleacoin</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+180"/> <source>&amp;About Aleacoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>&amp;File</source> <translation>&amp;Archivo</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;Configuraciones</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;Ayuda</translation> </message> <message> <location line="+12"/> <source>Tabs toolbar</source> <translation>Pestañas</translation> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+60"/> <source>Aleacoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+75"/> <source>%n active connection(s) to Aleacoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="-312"/> <source>About Aleacoin card</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Aleacoin card</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+297"/> <source>%n minute(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation>Actualizado al dia </translation> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation>Resiviendo...</translation> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>Enviar Transacción</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>Transacción entrante</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid Aleacoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>La cartera esta &lt;b&gt;encriptada&lt;/b&gt; y &lt;b&gt;desbloqueada&lt;/b&gt; actualmente </translation> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>La cartera esta &lt;b&gt;encriptada&lt;/b&gt; y &lt;b&gt;bloqueada&lt;/b&gt; actualmente </translation> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+109"/> <source>A fatal error occurred. Aleacoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Monto:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation>Prioridad:</translation> </message> <message> <location line="+48"/> <source>Fee:</source> <translation>Cuota:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount</source> <translation>Monto</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>Domicilio</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Fecha</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Confirmado </translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation>Copiar dirección </translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copiar capa </translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>copiar monto</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation>copiar cantidad</translation> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation>copiar cuota</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>copiar despues de cuota</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>copiar bytes</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>copiar prioridad</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>copiar cambio</translation> </message> <message> <location line="+317"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Editar dirección</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etiqueta</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Dirección</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation>Nueva dirección de entregas</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nueva dirección de entregas</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Editar dirección de entregas</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Editar dirección de envios</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>El domicilio ingresado &quot;%1&quot; ya existe en la libreta de direcciones</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Aleacoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>No se puede desbloquear la cartera</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>La generación de la nueva clave fallo</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>Aleacoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opciones</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start Aleacoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Aleacoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the Aleacoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the Aleacoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Aleacoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show Aleacoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Aleacoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Formulario</translation> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Aleacoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-160"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-107"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Transacciones recientes&lt;/b&gt;</translation> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+348"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the Aleacoin-Qt help message to get a list with possible Aleacoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>Aleacoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Aleacoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Aleacoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the Aleacoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Mandar monedas</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>Monto:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 ALEA</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation>Prioridad:</translation> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation>Cuota:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>Enviar a múltiples receptores a la vez</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+16"/> <source>123.456 ALEA</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Confirme la acción de enviar</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a Aleacoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation>copiar cantidad</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>copiar monto</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation>copiar cuota</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>copiar despues de cuota</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>copiar bytes</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>copiar prioridad</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>copiar cambio</translation> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Confirme para mandar monedas</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>El monto a pagar debe ser mayor a 0</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>WARNING: Invalid Aleacoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>M&amp;onto</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Pagar &amp;a:</translation> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation>Ingrese una etiqueta para esta dirección para agregarlo en su libreta de direcciones.</translation> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation>&amp;Etiqueta</translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Pegar dirección del portapapeles</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Aleacoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Pegar dirección del portapapeles</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Aleacoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Aleacoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Aleacoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter Aleacoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation>Abrir hasta %1</translation> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/No confirmado</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 confirmaciones</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Fecha</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 110 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Monto</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation>, no ha sido transmitido aun</translation> </message> <message> <location line="+35"/> <source>unknown</source> <translation>desconocido</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Detalles de la transacción</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Este panel muestras una descripción detallada de la transacción</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation>Fecha</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Domicilio</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Monto</translation> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation>Abrir hasta %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>Confimado (%1 confirmaciones)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Este bloque no fue recibido por ningun nodo y probablemente no fue aceptado !</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generado pero no aprovado</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>Recivido con</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Enviar a</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pagar a si mismo</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Minado</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Fecha y hora en que la transacción fue recibida </translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Escriba una transacción</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Direccion del destinatario de la transacción</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Cantidad removida del saldo o agregada </translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation>Todo</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Hoy</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Esta semana </translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Este mes </translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>El mes pasado </translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Este año</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Recivido con</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Enviar a</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Para ti mismo</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Minado </translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Otro</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Ingrese dirección o capa a buscar </translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Monto minimo </translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copiar dirección </translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copiar capa </translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>copiar monto</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Editar capa </translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Arhchivo separado por comas (*.CSV)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confirmado </translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Fecha</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Domicilio</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Monto</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation>Para</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+33"/> <source>Aleacoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>Uso:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or aleacoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation>Lista de comandos</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify configuration file (default: aleacoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: aleacoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Aleacoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=aleacoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Aleacoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-158"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. Aleacoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>Aleacoin</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation>Cargando direcciones...</translation> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of Aleacoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart Aleacoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation>Cargando indice de bloques... </translation> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. Aleacoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation>Cargando billetera...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Done loading</source> <translation>Carga completa</translation> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
aleacoin/aleacoin-release
src/qt/locale/bitcoin_es_MX.ts
TypeScript
mit
110,454
<?php declare(strict_types=1); namespace Overblog\GraphQLBundle\Command; use GraphQL\Type\Introspection; use GraphQL\Utils\SchemaPrinter; use InvalidArgumentException; use Overblog\GraphQLBundle\Request\Executor as RequestExecutor; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use function file_put_contents; use function json_encode; use function realpath; use function sprintf; use function strtolower; use const JSON_PRETTY_PRINT; final class GraphQLDumpSchemaCommand extends Command { private RequestExecutor $requestExecutor; private string $baseExportPath; public function __construct(string $baseExportPath, RequestExecutor $requestExecutor) { parent::__construct(); $this->baseExportPath = $baseExportPath; $this->requestExecutor = $requestExecutor; } public function getRequestExecutor(): RequestExecutor { return $this->requestExecutor; } protected function configure(): void { $this ->setName('graphql:dump-schema') ->setAliases(['graph:dump-schema']) ->setDescription('Dumps GraphQL schema') ->addOption( 'file', null, InputOption::VALUE_OPTIONAL, 'Path to generate schema file.' ) ->addOption( 'schema', null, InputOption::VALUE_OPTIONAL, 'The schema name to generate.' ) ->addOption( 'format', null, InputOption::VALUE_OPTIONAL, 'The schema format to generate ("graphql" or "json").', 'json' ) ->addOption( 'modern', null, InputOption::VALUE_NONE, 'Enabled modern json format: { "data": { "__schema": {...} } }.' ) ->addOption( 'classic', null, InputOption::VALUE_NONE, 'Enabled classic json format: { "__schema": {...} }.' ) ->addOption( 'with-descriptions', null, InputOption::VALUE_NONE, 'Dump schema including descriptions.' ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $file = $this->createFile($input); $io->success(sprintf('GraphQL schema "%s" was successfully dumped.', realpath($file))); return 0; } private function createFile(InputInterface $input): string { $format = strtolower($input->getOption('format')); /** @var string|null $schemaName */ $schemaName = $input->getOption('schema'); /** @var bool $includeDescription */ $includeDescription = $input->getOption('with-descriptions'); /** @var string $file */ $file = $input->getOption('file') ?: $this->baseExportPath.sprintf('/schema%s.%s', $schemaName ? '.'.$schemaName : '', $format); switch ($format) { case 'json': $request = [ 'query' => Introspection::getIntrospectionQuery(['descriptions' => $includeDescription]), 'variables' => [], 'operationName' => null, ]; $modern = $this->useModernJsonFormat($input); $result = $this->getRequestExecutor() ->execute($schemaName, $request) ->toArray(); $content = json_encode($modern ? $result : ($result['data'] ?? null), JSON_PRETTY_PRINT); break; case 'graphql': $content = SchemaPrinter::doPrint($this->getRequestExecutor()->getSchema($schemaName)); break; default: throw new InvalidArgumentException(sprintf('Unknown format %s.', json_encode($format))); } file_put_contents($file, $content); // @phpstan-ignore-next-line return $file; } private function useModernJsonFormat(InputInterface $input): bool { $modern = $input->getOption('modern'); $classic = $input->getOption('classic'); if ($modern && $classic) { throw new InvalidArgumentException('"modern" and "classic" options should not be used together.'); } return true === $modern; } }
overblog/GraphQLBundle
src/Command/GraphQLDumpSchemaCommand.php
PHP
mit
4,754
/** * Wrapper for the component that compatible with amd, commonjs and as global object */ (function (root, factory) { if(typeof define === "function" && define.amd) { define(function () { return factory(); }); } else if(typeof module === "object" && module.exports) { module.exports = factory(); } else { root.Treeview = factory(); } }(this, function() { 'use strict';
yjcxy12/react-treeview-component
src/Tree/intro.js
JavaScript
mit
417
package org.robolectric.shadows; import android.widget.AbsSpinner; import android.widget.SpinnerAdapter; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; import org.robolectric.util.ReflectionHelpers.ClassParameter; import static org.robolectric.shadow.api.Shadow.directlyOn; /** * Shadow for {@link android.widget.AbsSpinner}. */ @SuppressWarnings({"UnusedDeclaration"}) @Implements(AbsSpinner.class) public class ShadowAbsSpinner extends ShadowAdapterView { @RealObject AbsSpinner realAbsSpinner; private boolean animatedTransition; @Implementation public void setSelection(int position, boolean animate) { directlyOn(realAbsSpinner, AbsSpinner.class, "setSelection", ClassParameter.from(int.class, position), ClassParameter.from(boolean.class, animate)); animatedTransition = animate; } @Implementation public void setSelection(int position) { directlyOn(realAbsSpinner, AbsSpinner.class, "setSelection", ClassParameter.from(int.class, position)); SpinnerAdapter adapter = realAbsSpinner.getAdapter(); if (getItemSelectedListener() != null && adapter != null) { getItemSelectedListener().onItemSelected(realAbsSpinner, null, position, adapter.getItemId(position)); } } // Non-implementation helper method public boolean isAnimatedTransition() { return animatedTransition; } }
cesar1000/robolectric
robolectric-shadows/shadows-core/src/main/java/org/robolectric/shadows/ShadowAbsSpinner.java
Java
mit
1,436
module.exports = require('./src/LensedStateMixin');
Laiff/react-lensed-state
index.js
JavaScript
mit
51
require 'active_support/basic_object' module CleverElements class Proxy attr_reader :client, :wsdl, :proxy_methods, :response_methods def initialize client @client = client @wsdl = client.savon.wsdl @proxy_methods = Module.new @response_methods = Module.new build_proxy end protected def build_proxy wsdl.operations.each_pair do |name, vals| build_operation_proxy_for name end extend proxy_methods extend response_methods end # Builds a response processor for a SOAP action: # The response processor uses message and type information of the # wsdl to "un-nest" the soap response as far as possible, # e.g. if the soap response is # :a => { # :b => { # :c => { # :d => 1, # :e => 2 # } # } # } # the processor will return # { :d => 1, :e => 2} # (first non-trivial nesting level) def build_response_processor_for name method_name = "process_response_for_#{name}" message_name, message = wsdl.parser.port_type[name][:output].first key, type = message.first types = wsdl.parser.types keys = [message_name.snakecase.to_sym, key.snakecase.to_sym] while type type = type.split(':').last typedef = types[type] if typedef _keys = (typedef.keys - [:namespace, :type]) break unless _keys.length == 1 key = _keys.first type = typedef[key][:type] keys << key.snakecase.to_sym else break end end response_methods.send :define_method, method_name do |body| keys.inject body do |b, key| b[key] if b end end method_name end def build_operation_proxy_for name method_name = name.to_s.sub /^api_/, '' input_message = wsdl.parser.port_type[name][:input].first response_processor_name = build_response_processor_for name proxy_methods.send :define_method, method_name do |*args| arguments = args.first if input_message arguments = { input_message.to_sym => arguments } end response = client.request name, arguments send response_processor_name, response.body end end end end
kayoom/clever_elements
lib/clever_elements/proxy.rb
Ruby
mit
2,432
package com.ziyuan.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.lang.annotation.Annotation; import java.net.URL; import java.net.URLDecoder; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * 特此声明,感谢排骨支持 */ public final class ClassUtil { private static Logger logger = LoggerFactory.getLogger(ClassUtil.class); /** * Class文件扩展名 */ private static final String CLASS_EXT = ".class"; /** * Jar文件扩展名 */ private static final String JAR_FILE_EXT = ".jar"; /** * 在Jar中的路径jar的扩展名形式 */ private static final String JAR_PATH_EXT = ".jar!"; /** * 当Path为文件形式时, path会加入一个表示文件的前缀 */ private static final String PATH_FILE_PRE = "file:"; /** * 文件过滤器,过滤掉不需要的文件 * 只保留Class文件、目录和Jar */ private static FileFilter fileFilter = new FileFilter() { @Override public boolean accept(File pathname) { return isClass(pathname.getName()) || pathname.isDirectory() || isJarFile(pathname); } }; // 静态类不可实例化 private ClassUtil() { } /** * 扫描指定包路径下所有包含指定注解的类 * * @param packageName 包路径 * @param inJar 在jar包中查找 * @param annotationClass 注解类 * @return 类集合 */ public static Set<Class<?>> scanPackageByAnnotation(String packageName, boolean inJar, final Class<? extends Annotation> annotationClass) { return scanPackage(packageName, inJar, new ClassFilter() { @Override public boolean accept(Class<?> clazz) { return clazz.isAnnotationPresent(annotationClass); } }); } /** * 扫面包路径下满足class过滤器条件的所有class文件 * 如果包路径为 com.abs + A.class 但是输入 abs会产生classNotFoundException * 因为className 应该为 com.abs.A 现在却成为abs.A,此工具类对该异常进行忽略处理,有可能是一个不完善的地方,以后需要进行修改 * * @param packageName 包路径 com | com. | com.abs | com.abs. * @param inJar 在jar包中查找 * @param classFilter class过滤器,过滤掉不需要的class * @return 类集合 */ public static Set<Class<?>> scanPackage(String packageName, boolean inJar, ClassFilter classFilter) { if (packageName == null || "".equals(packageName.trim())) { packageName = ""; } packageName = getWellFormedPackageName(packageName); final Set<Class<?>> classes = new HashSet<>(); for (String classPath : getClassPaths(packageName)) { // 填充 classes, 并对classpath解码 classPath = decodeUrl(classPath); fillClasses(classPath, packageName, classFilter, classes); } //如果在项目的ClassPath中未找到,去系统定义的ClassPath里找 if (inJar) { for (String classPath : getJavaClassPaths()) { // 填充 classes, 并对classpath解码 classPath = decodeUrl(classPath); fillClasses(classPath, new File(classPath), packageName, classFilter, classes); } } return classes; } /** * 获得ClassPath * * @param packageName 包名称 * @return ClassPath路径字符串集合 */ public static Set<String> getClassPaths(String packageName) { String packagePath = packageName.replace(".", "/"); Enumeration<URL> resources; try { resources = getClassLoader().getResources(packagePath); } catch (IOException e) { throw new RuntimeException(String.format("Loading classPath [%s] error!", packageName), e); } Set<String> paths = new HashSet<>(); while (resources.hasMoreElements()) { paths.add(resources.nextElement().getPath()); } return paths; } /** * @return 获得Java ClassPath路径,不包括 jre */ public static String[] getJavaClassPaths() { return System.getProperty("java.class.path").split(System.getProperty("path.separator")); } /** * 获取当前线程的ClassLoader * * @return 当前线程的class loader */ public static ClassLoader getContextClassLoader() { return Thread.currentThread().getContextClassLoader(); } /** * 获得class loader * 若当前线程class loader不存在,取当前类的class loader * * @return 类加载器 */ public static ClassLoader getClassLoader() { ClassLoader classLoader = getContextClassLoader(); if (classLoader == null) { classLoader = ClassUtil.class.getClassLoader(); } return classLoader; } /** * 根据指定的类名称加载类 * * @param className 完整类名 * @return {Class} * @throws ClassNotFoundException 找不到异常 */ public static Class<?> loadClass(String className) throws ClassNotFoundException { try { return ClassUtil.getContextClassLoader().loadClass(className); } catch (ClassNotFoundException e) { try { return Class.forName(className, false, ClassUtil.getClassLoader()); } catch (ClassNotFoundException ex) { try { return ClassLoader.class.getClassLoader().loadClass(className); } catch (ClassNotFoundException exc) { throw exc; } } } } /** * 改变 com -> com. 避免在比较的时候把比如 completeTestSuite.class类扫描进去,如果没有"." * 那class里面com开头的class类也会被扫描进去,其实名称后面或前面需要一个 ".",来添加包的特征 * * @param packageName 包名 * @return 格式化后的包名 */ private static String getWellFormedPackageName(String packageName) { return packageName.lastIndexOf('.') != packageName.length() - 1 ? packageName + '.' : packageName; } /** * 去掉指定前缀 * * @param str 字符串 * @param prefix 前缀 * @return 切掉后的字符串,若前缀不是 preffix, 返回原字符串 */ private static String removePrefix(String str, String prefix) { if (str != null && str.startsWith(prefix)) { return str.substring(prefix.length()); } return str; } /** * 填充满足条件的class 填充到 classes * 同时会判断给定的路径是否为Jar包内的路径,如果是,则扫描此Jar包 * * @param path Class文件路径或者所在目录Jar包路径 * @param packageName 需要扫面的包名 * @param classFilter class过滤器 * @param classes List 集合 */ private static void fillClasses(String path, String packageName, ClassFilter classFilter, Set<Class<?>> classes) { //判定给定的路径是否为Jar int index = path.lastIndexOf(JAR_PATH_EXT); if (index != -1) { //Jar文件 path = path.substring(0, index + JAR_FILE_EXT.length()); //截取jar路径 path = removePrefix(path, PATH_FILE_PRE); //去掉文件前缀 processJarFile(new File(path), packageName, classFilter, classes); } else { fillClasses(path, new File(path), packageName, classFilter, classes); } } /** * 填充满足条件的class 填充到 classes * * @param classPath 类文件所在目录,当包名为空时使用此参数,用于截掉类名前面的文件路径 * @param file Class文件或者所在目录Jar包文件 * @param packageName 需要扫面的包名 * @param classFilter class过滤器 * @param classes List 集合 */ private static void fillClasses(String classPath, File file, String packageName, ClassFilter classFilter, Set<Class<?>> classes) { if (file.isDirectory()) { processDirectory(classPath, file, packageName, classFilter, classes); } else if (isClassFile(file)) { processClassFile(classPath, file, packageName, classFilter, classes); } else if (isJarFile(file)) { processJarFile(file, packageName, classFilter, classes); } } /** * 处理如果为目录的情况,需要递归调用 fillClasses方法 * * @param directory 目录 * @param packageName 包名 * @param classFilter 类过滤器 * @param classes 类集合 */ private static void processDirectory(String classPath, File directory, String packageName, ClassFilter classFilter, Set<Class<?>> classes) { for (File file : directory.listFiles(fileFilter)) { fillClasses(classPath, file, packageName, classFilter, classes); } } /** * 处理为class文件的情况,填充满足条件的class 到 classes * * @param classPath 类文件所在目录,当包名为空时使用此参数,用于截掉类名前面的文件路径 * @param file class文件 * @param packageName 包名 * @param classFilter 类过滤器 * @param classes 类集合 */ private static void processClassFile(String classPath, File file, String packageName, ClassFilter classFilter, Set<Class<?>> classes) { if (!classPath.endsWith(File.separator)) { classPath += File.separator; } String path = file.getAbsolutePath(); if (packageName == null || "".equals(packageName.trim())) { path = removePrefix(path, classPath); } final String filePathWithDot = path.replace(File.separator, "."); int subIndex; if ((subIndex = filePathWithDot.indexOf(packageName)) != -1) { final int endIndex = filePathWithDot.lastIndexOf(CLASS_EXT); final String className = filePathWithDot.substring(subIndex, endIndex); fillClass(className, packageName, classes, classFilter); } } /** * 处理为jar文件的情况,填充满足条件的class 到 classes * * @param file jar文件 * @param packageName 包名 * @param classFilter 类过滤器 * @param classes 类集合 */ private static void processJarFile(File file, String packageName, ClassFilter classFilter, Set<Class<?>> classes) { try (JarFile jarFile = new JarFile(file)) { for (JarEntry entry : Collections.list(jarFile.entries())) { if (isClass(entry.getName())) { final String className = entry.getName().replace("/", ".").replace(CLASS_EXT, ""); fillClass(className, packageName, classes, classFilter); } } } catch (Exception ex) { logger.error(ex.getMessage(), ex); } } /** * 填充class 到 classes * * @param className 类名 * @param packageName 包名 * @param classes 类集合 * @param classFilter 类过滤器 */ private static void fillClass(String className, String packageName, Set<Class<?>> classes, ClassFilter classFilter) { if (className.startsWith(packageName)) { try { final Class<?> clazz = ClassUtil.loadClass(className); if (classFilter == null || classFilter.accept(clazz)) { classes.add(clazz); } } catch (Exception ex) { logger.error(ex.getMessage(), ex); } } } /** * @param file 文件 * @return 是否为类文件 */ private static boolean isClassFile(File file) { return isClass(file.getName()); } /** * @param fileName 文件名 * @return 是否为类文件 */ private static boolean isClass(String fileName) { return fileName.endsWith(CLASS_EXT); } /** * @param file 文件 * @return是否为Jar文件 */ private static boolean isJarFile(File file) { return file.getName().endsWith(JAR_FILE_EXT); } //--------------------------------------------------------------------------------------------------- Private method end /** * 类过滤器,用于过滤不需要加载的类 */ public interface ClassFilter { /** * 过滤不需要加载的类 * * @param clazz * @return */ boolean accept(Class<?> clazz); } /** * 对路径解码 * * @param url 路径 * @return String 解码后的路径 */ private static String decodeUrl(String url) { try { return URLDecoder.decode(url, "UTF-8"); } catch (java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } } }
carryxyh/Electrons
electrons/src/main/java/com/ziyuan/util/ClassUtil.java
Java
mit
13,408
<?php /** * Post archive for tags and categories * * @package mb */ namespace MauroBringolf; ?> <?php get_header(); ?> <main class="content"> <?php if ( have_posts() ) : ?> <section> <h2>#<?php single_tag_title(); ?></h2> <?php post_list(); ?> </section> <?php endif; ?> </main> <?php get_footer(); ?>
maurobringolf/mb
archive.php
PHP
mit
323
package auth import ( "errors" "fmt" "golang.org/x/net/context" "google.golang.org/appengine/datastore" ) var ( sessionKey = contextKey("session-key") ) // Errors var ( ErrMissingToken = errors.New("no auth token found") ErrNoSuchAccount = errors.New("failed to find account") ) // Session provides helper methods to get and set the account key within the request context type Session struct{} // SignedIn returns boolean value indicating if the user is signed in or not func (s *Session) SignedIn(c context.Context) bool { key, err := s.AccountKey(c) if err != nil { return false } return key != nil } // AccountKey return the *datastore.Key value for the account func (s *Session) AccountKey(c context.Context) (*datastore.Key, error) { var err error val := c.Value(sessionKey) if val == nil { return nil, ErrMissingToken } key, err := datastore.DecodeKey(val.(string)) if err != nil { return nil, fmt.Errorf("decoding the context account key: %v", err) } return key, nil } // SetAccountKey sets the key in the request context to allow for later access func (s *Session) SetAccountKey(c context.Context, key *datastore.Key) context.Context { return context.WithValue(c, sessionKey, key.Encode()) }
chrisolsen/ae
auth/session.go
GO
mit
1,237
/* * Open Payments Cloud Application API * Open Payments Cloud API * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.ixaris.ope.applications.client.model; import java.util.Objects; import com.google.gson.annotations.SerializedName; import com.ixaris.ope.applications.client.model.DepositProfile; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; /** * DepositProfiles */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-30T15:46:40.836+02:00") public class DepositProfiles { @SerializedName("depositProfiles") private List<DepositProfile> depositProfiles = new ArrayList<DepositProfile>(); @SerializedName("count") private Integer count = null; /** * Gets or Sets actions */ public enum ActionsEnum { @SerializedName("CREATE") CREATE("CREATE"); private String value; ActionsEnum(String value) { this.value = value; } @Override public String toString() { return String.valueOf(value); } } @SerializedName("actions") private List<ActionsEnum> actions = new ArrayList<ActionsEnum>(); public DepositProfiles depositProfiles(List<DepositProfile> depositProfiles) { this.depositProfiles = depositProfiles; return this; } public DepositProfiles addDepositProfilesItem(DepositProfile depositProfilesItem) { this.depositProfiles.add(depositProfilesItem); return this; } /** * Get depositProfiles * @return depositProfiles **/ @ApiModelProperty(example = "null", value = "") public List<DepositProfile> getDepositProfiles() { return depositProfiles; } public void setDepositProfiles(List<DepositProfile> depositProfiles) { this.depositProfiles = depositProfiles; } public DepositProfiles count(Integer count) { this.count = count; return this; } /** * The total number of entries that match the given filter, including any entries which were not returned due to paging constraints. * @return count **/ @ApiModelProperty(example = "null", value = "The total number of entries that match the given filter, including any entries which were not returned due to paging constraints.") public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public DepositProfiles actions(List<ActionsEnum> actions) { this.actions = actions; return this; } public DepositProfiles addActionsItem(ActionsEnum actionsItem) { this.actions.add(actionsItem); return this; } /** * The actions that can be performed on this particular resource instance. * @return actions **/ @ApiModelProperty(example = "null", value = "The actions that can be performed on this particular resource instance.") public List<ActionsEnum> getActions() { return actions; } public void setActions(List<ActionsEnum> actions) { this.actions = actions; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DepositProfiles depositProfiles = (DepositProfiles) o; return Objects.equals(this.depositProfiles, depositProfiles.depositProfiles) && Objects.equals(this.count, depositProfiles.count) && Objects.equals(this.actions, depositProfiles.actions); } @Override public int hashCode() { return Objects.hash(depositProfiles, count, actions); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DepositProfiles {\n"); sb.append(" depositProfiles: ").append(toIndentedString(depositProfiles)).append("\n"); sb.append(" count: ").append(toIndentedString(count)).append("\n"); sb.append(" actions: ").append(toIndentedString(actions)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
ixaris/ope-applicationclients
java-client/src/main/java/com/ixaris/ope/applications/client/model/DepositProfiles.java
Java
mit
4,465
# Enter your code here. Read input from STDIN. Print output to STDOUT import re t = int(raw_input()) for i in range(t): try: x = re.compile(raw_input()) if x: print True except: print False
ugaliguy/HackerRank
Python/Errors-and-Exceptions/incorrect-regex.py
Python
mit
246
using System.Collections.Generic; using UltimateTeam.Toolkit.Parameters; namespace UltimateTeam.Toolkit.Models { public class ItemData { public long AssetId { get; set; } public ushort Assists { get; set; } public List<Attribute> AttributeList { get; set; } public ushort CardSubTypeId { get; set; } public byte Contract { get; set; } public ushort? DiscardValue { get; set; } public byte Fitness { get; set; } public string Formation { get; set; } public long Id { get; set; } public byte InjuryGames { get; set; } public string InjuryType { get; set; } public string ItemState { get; set; } public string ItemType { get; set; } public uint LastSalePrice { get; set; } public uint LeagueId { get; set; } public ushort LifeTimeAssists { get; set; } public ushort Loans { get; set; } public List<Attribute> LifeTimeStats { get; set; } public byte LoyaltyBonus { get; set; } public byte Morale { get; set; } public byte Owners { get; set; } public ChemistryStyle PlayStyle { get; set; } public string PreferredPosition { get; set; } public byte RareFlag { get; set; } public byte Rating { get; set; } public long ResourceId { get; set; } public List<Attribute> StatsList { get; set; } public byte Suspension { get; set; } public uint TeamId { get; set; } public string Timestamp { get; set; } public int Training { get; set; } public bool Untradeable { get; set; } public int Pile { get; set; } public int Nation { get; set; } } }
lorenzh/FIFA-Ultimate-Team-Toolkit
UltimateTeam.Toolkit/Models/ItemData.cs
C#
mit
1,750
#include "PathSearchNode.h" bool PathSearchNode::IsSameState( PathSearchNode &rhs , void* context) { return coord == rhs.coord && timestamp == rhs.timestamp; } float PathSearchNode::GoalDistanceEstimate( PathSearchNode &nodeGoal , void* _context) { int cost_hX = abs(coord.x - nodeGoal.coord.x); int cost_hY = abs(coord.y - nodeGoal.coord.y); int cost_hZ = abs(coord.z - nodeGoal.coord.z); float cost_h = cost_hX + cost_hY + cost_hZ; return cost_h; } bool PathSearchNode::IsGoal( PathSearchNode &nodeGoal , void* _context) { CAstar* context = (CAstar*)_context; if(coord == nodeGoal.coord) { vector< vector<WS_Coord> > avoidTrajs = context->GetAvoidTrajs(); for(int i=0; i < avoidTrajs.size(); i++) { for(int t=timestamp; t < avoidTrajs[i].size(); t++) { if(avoidTrajs[i][t] == nodeGoal.coord) { return false; } } } return true; } return false; } bool isBlocked(WS_Coord pos, int timestep, int ***obsmap, vector< vector<WS_Coord> > avoidTrajs) { if(obsmap[pos.x][pos.y][pos.z] == 1) { return true; } for(int i=0; i < avoidTrajs.size(); i++) { for(int t = timestep - Delta; t <= timestep + Delta; t++) { if(t >= 0) { if(t < avoidTrajs[i].size()) { if(pos == avoidTrajs[i][t]) { return true; } } else { if(pos == avoidTrajs[i][avoidTrajs[i].size() - 1]) { return true; } } } } } return false; } bool PathSearchNode::GetSuccessors( AStarSearch<PathSearchNode> *astarsearch, PathSearchNode *parent_node, void* _context) { CAstar* context = (CAstar*)_context; #define add_if_not_blocked(side, step) { \ WS_Coord neighbor = coord; \ neighbor.side += (step); \ if(neighbor.side >= 0 && neighbor.side < context->GetDimension().side##_dim && \ !isBlocked(neighbor, timestamp + 1, context->GetObstacleMap(), context->GetAvoidTrajs())) { \ PathSearchNode newNode(neighbor, timestamp + 1); \ astarsearch->AddSuccessor(newNode); \ } \ } add_if_not_blocked(x, -1); add_if_not_blocked(x, +1); add_if_not_blocked(y, -1); add_if_not_blocked(y, +1); add_if_not_blocked(z, -1); add_if_not_blocked(z, +1); add_if_not_blocked(x, 0); // hovering action return true; } float PathSearchNode::GetCost( PathSearchNode &successor , void* context) { if(coord == successor.coord) { return HOVERING_COST; } else { return STEP_COST; } } void PathSearchNode::PrintNodeInfo() { printf("(%d, %d %d)@t=%d\n", coord.x, coord.y, coord.z, timestamp); }
Drona-Org/DronaForPX4
Src/Lib/ExternalMotionPlanners/AStarPlanner/Src/PathSearchNode.cpp
C++
mit
3,025
/** * Module dependencies */ var utils = require('../utils'); var safeRequire = utils.safeRequire; var cassandra = safeRequire('cassandra-driver'); var Types = cassandra.types; var timeUUID = Types.timeuuid; var util = require('util'); var BaseSQL = require('../sql'); exports.initialize = function initializeSchema(schema, callback) { if (!cassandra) { return; } var s = schema.settings; if (s.url) { var uri = url.parse(s.url); s.host = uri.hostname; s.port = uri.port || '9042'; s.database = uri.pathname.replace(/^\//, ''); s.username = uri.auth && uri.auth.split(':')[0]; s.password = uri.auth && uri.auth.split(':')[1]; } s.host = s.host || 'localhost'; s.port = parseInt(s.port || '9042', 10); s.database = s.database || s.keyspace || 'test'; if (!(s.host instanceof Array)) { s.host = [s.host]; } schema.client = new cassandra.Client({ contactPoints: s.host, protocolOptions: { maxVersion: 3 }, autoPage: true }); // , keyspace: s.database schema.adapter = new Cassandra(schema, schema.client); schema.client.connect(function (err, result) { schema.client.execute("CREATE KEYSPACE IF NOT EXISTS " + s.database.toString() + " WITH replication " + "= {'class' : 'SimpleStrategy', 'replication_factor' : 2};", function (err, data) { console.log('Cassandra connected.'); schema.client.keyspace = s.database; process.nextTick(callback); } ); }); }; function Cassandra(schema, client) { this.name = 'cassandra'; this._models = {}; this.client = client; this.schema = schema; } util.inherits(Cassandra, BaseSQL); Cassandra.prototype.execute = function (sql, callback) { var self = this; var client = self.client; client.execute(sql, callback); }; Cassandra.prototype.query = function (sql, callback) { 'use strict'; var self = this; if (typeof callback !== 'function') { throw new Error('callback should be a function'); } self.execute(sql, function (err, data) { if (err && err.message.match(/does\s+not\s+exist/i)) { self.query('CREATE KEYSPACE IF NOT EXISTS ' + self.schema.settings.database, function (error) { if (!error) { self.execute(sql, callback); } else { callback(err); } }); } else if (err && (err.message.match(/no\s+keyspace\s+has\s+been\s+specified/gi) || parseInt(err.errno) === 1046)) { self.execute('USE ' + self.schema.settings.database + '', function (error) { if (!error) { self.execute(sql, callback); } else { callback(error); } }); } else { var rows = []; data = data || {}; if (data.rows && data.rows.length) { rows = data.rows; } return callback(err, rows); } }); }; /** * Must invoke callback(err, id) * @param {Object} model * @param {Object} data * @param {Function} callback */ Cassandra.prototype.create = function (model, data, callback) { 'use strict'; var self = this; var props = self._models[model].properties; data = data || {}; if (data.id === null) { data.id = timeUUID(); } var keys = []; var questions = []; Object.keys(data).map(function (key) { var val = self.toDatabase(props[key], data[key]); if (val !== 'NULL') { keys.push(key); questions.push(val); } }); var sql = 'INSERT INTO ' + self.tableEscaped(model) + ' (' + keys.join(',') + ') VALUES ('; sql += questions.join(','); sql += ')'; this.query(sql, function (err, info) { callback(err, !err && data.id); }); }; Cassandra.prototype.all = function all(model, filter, callback) { 'use strict'; var self = this, sFields = '*'; if ('function' === typeof filter) { callback = filter; filter = {}; } if (!filter) { filter = {}; } var sql = 'SELECT ' + sFields + ' FROM ' + self.tableEscaped(model); if (filter) { if (filter.fields) { if (typeof filter.fields === 'string') { sFields = self.tableEscaped(filter.fields); } else if (Object.prototype.toString.call(filter.fields) === '[object Array]') { sFields = filter.fields.map(function (field) { return '`' + field + '`'; }).join(', '); } sql = sql.replace('*', sFields); } if (filter.where) { sql += ' ' + self.buildWhere(filter.where, self, model); } if (filter.order) { sql += ' ' + self.buildOrderBy(filter.order); } if (filter.group) { sql += ' ' + self.buildGroupBy(filter.group); } if (filter.limit) { sql += ' ' + self.buildLimit(filter.limit, filter.offset || filter.skip || 0); } } this.query(sql, function (err, data) { if (err) { return callback(err, []); } callback(null, data.map(function (obj) { return self.fromDatabase(model, obj); })); }.bind(this)); return sql; }; Cassandra.prototype.update = function (model, filter, data, callback) { 'use strict'; if ('function' === typeof filter) { return filter(new Error("Get parametrs undefined"), null); } if ('function' === typeof data) { return data(new Error("Set parametrs undefined"), null); } filter = filter.where ? filter.where : filter; var self = this; var combined = []; var props = self._models[model].properties; Object.keys(data).forEach(function (key) { if (props[key] || key === 'id') { var k = '' + key + ''; var v; if (key !== 'id') { v = self.toDatabase(props[key], data[key]); } else { v = data[key]; } combined.push(k + ' = ' + v); } }); var sql = 'UPDATE ' + this.tableEscaped(model); sql += ' SET ' + combined.join(', '); sql += ' ' + self.buildWhere(filter, self, model); this.query(sql, function (err, affected) { callback(err, !err); }); }; Cassandra.prototype.destroyAll = function destroyAll(model, callback) { this.query('TRUNCATE ' + this.tableEscaped(model), function (err) { if (err) { return callback(err, []); } callback(err); }.bind(this)); }; /** * Update existing database tables. * @param {Function} cb */ Cassandra.prototype.autoupdate = function (cb) { 'use strict'; var self = this; var wait = 0; Object.keys(this._models).forEach(function (model) { wait += 1; self.query('SELECT column_name as field, type, validator, index_type, index_name FROM system.schema_columns ' + 'WHERE keyspace_name = \'' + self.schema.settings.database + '\' ' + 'AND columnfamily_name = \'' + self.escapeName(model) + '\'', function (err, data) { var indexes = data.filter(function (m) { return m.index_type !== null || m.type === 'partition_key'; }) || []; if (!err && data.length) { self.alterTable(model, data, indexes || [], done); } else { self.createTable(model, indexes || [], done); } }); }); function done(err) { if (err) { console.log(err); } if (--wait === 0 && cb) { cb(); } } }; Cassandra.prototype.alterTable = function (model, actualFields, actualIndexes, done, checkOnly) { 'use strict'; var self = this; var m = this._models[model]; var propNames = Object.keys(m.properties).filter(function (name) { return !!m.properties[name]; }); var indexNames = m.settings.indexes ? Object.keys(m.settings.indexes).filter(function (name) { return !!m.settings.indexes[name]; }) : []; var sql = []; var ai = {}; if (actualIndexes) { actualIndexes.forEach(function (i) { var name = i.index_name || i.field; if (!ai[name]) { ai[name] = { info: i, columns: [] }; } ai[name].columns.push(i.field); }); } var aiNames = Object.keys(ai); // change/add new fields propNames.forEach(function (propName) { if (propName === 'id') { return; } var found; actualFields.forEach(function (f) { if (f.field === propName) { found = f; } }); if (found) { actualize(propName, found); } else { // ALTER TABLE users ADD top_places list<text>; sql.push('ALTER TABLE ' + self.escapeName(model) + ' ADD ' + self.propertySettingsSQL(model, propName)); } }); // drop columns actualFields.forEach(function (f) { var notFound = !~propNames.indexOf(f.field); if (f.field === 'id') { return; } if (notFound || !m.properties[f.field]) { // ALTER TABLE addamsFamily DROP gender; sql.push('ALTER TABLE ' + self.escapeName(model) + ' DROP ' + f.field + ''); } }); // remove indexes aiNames.forEach(function (indexName) { if (indexName === 'id' || indexName === 'PRIMARY') { return; } if ((indexNames.indexOf(indexName) === -1 && !m.properties[indexName]) || (m.properties[indexName] && !m.properties[indexName].index && !ai[indexName])) { sql.push('DROP INDEX IF EXISTS ' + indexName + ''); } else { // first: check single (only type and kind) if (m.properties[indexName] && !m.properties[indexName].index) { // TODO return; } // second: check multiple indexes var orderMatched = true; if (indexNames.indexOf(indexName) !== -1) { m.settings.indexes[indexName].columns.split(/,\s*/).forEach(function (columnName, i) { if (ai[indexName].columns[i] !== columnName) orderMatched = false; }); } if (!orderMatched) { sql.push('DROP INDEX IF EXISTS ' + indexName + ''); delete ai[indexName]; } } }); // add single-column indexes propNames.forEach(function (propName) { var i = m.properties[propName].index; if (!i) { return; } var found = ai[propName] && ai[propName].info; if (!found) { var type = ''; var kind = ''; if (i.type) { type = 'USING ' + i.type; } if (i.kind) { // kind = i.kind; } // CREATE INDEX IF NOT EXISTS user_state ON myschema.users (state); if (kind && type) { sql.push('CREATE INDEX IF NOT EXISTS ' + propName + ' ON ' + self.escapeName(model) + ' (' + propName + ')'); } else { sql.push('CREATE INDEX IF NOT EXISTS ' + propName + ' ON ' + self.escapeName(model) + ' (' + propName + ')'); } } }); /* // add multi-column indexes indexNames.forEach(function (indexName) { var i = m.settings.indexes[indexName]; var found = ai[indexName] && ai[indexName].info; if (!found) { sql.push('CREATE INDEX IF NOT EXISTS '+indexName+' ON '+self.escapeName(model)+' ('+i.columns+')'); } }); */ if (sql.length) { var query = sql; if (checkOnly) { done(null, true, { statements: sql, query: query }); } else { var slen = query.length; for (var qi in query) { this.query(query[qi] + '', function (err, data) { if (err) console.log(err); if (--slen === 0) { done(); } }); } } } else { done(); } function actualize(propName, oldSettings) { 'use strict'; var newSettings = m.properties[propName]; if (newSettings && changed(newSettings, oldSettings)) { // ALTER TABLE users ALTER bio TYPE text; sql.push('ALTER TABLE ' + self.escapeName(model) + ' ALTER ' + propName + ' TYPE ' + self.propertySettingsSQL(model, propName)); } } function changed(newSettings, oldSettings) { 'use strict'; var type = oldSettings.validator.replace(/ORG\.APACHE\.CASSANDRA\.DB\.MARSHAL\./gi, ''); type = type.replace(/type/gi, '').toLowerCase(); if (/^map/gi.test(type)) { type = 'map<text,text>'; } switch (type) { case 'utf8': type = 'text'; break; case 'int32': type = 'int'; break; case 'long': type = 'bigint'; break; } if (type !== datatype(newSettings) && type !== 'reversed(' + datatype(newSettings) + ')') { return true; } return false; } }; Cassandra.prototype.ensureIndex = function (model, fields, params, callback) { 'use strict'; var self = this, sql = "", keyName = params.name || null, afld = [], kind = ""; Object.keys(fields).forEach(function (field) { if (!keyName) { keyName = "idx_" + field; } afld.push('' + field + ''); }); if (params.unique) { kind = "UNIQUE"; } // CREATE INDEX IF NOT EXISTS xi ON xx5 (x); sql += 'CREATE INDEX IF NOT EXISTS ' + kind + ' INDEX `' + keyName + '` ON `' + model + '` (' + afld.join(', ') + ');'; self.query(sql, callback); }; Cassandra.prototype.buildLimit = function buildLimit(limit, offset) { 'use strict'; return 'LIMIT ' + (offset ? (offset + ', ' + limit) : limit); }; Cassandra.prototype.buildWhere = function buildWhere(conds, adapter, model) { 'use strict'; var cs = [], or = [], self = adapter, props = self._models[model].properties; Object.keys(conds).forEach(function (key) { if (key !== 'or') { cs = parseCond(cs, key, props, conds, self); } else { conds[key].forEach(function (oconds) { Object.keys(oconds).forEach(function (okey) { or = parseCond(or, okey, props, oconds, self); }); }); } }); if (cs.length === 0 && or.length === 0) { return ''; } var orop = ""; if (or.length) { orop = ' (' + or.join(' OR ') + ') '; } orop += (orop !== "" && cs.length > 0) ? ' AND ' : ''; return 'WHERE ' + orop + cs.join(' AND '); }; Cassandra.prototype.buildGroupBy = function buildGroupBy(group) { 'use strict'; if (typeof group === 'string') { group = [group]; } return 'GROUP BY ' + group.join(', '); }; Cassandra.prototype.fromDatabase = function (model, data) { 'use strict'; if (!data) { return null; } var props = this._models[model].properties; Object.keys(data).forEach(function (key) { var val = data[key]; if (props[key]) { if (props[key].type.name === 'Date' && val !== null) { val = new Date(val.toString().replace(/GMT.*$/, 'GMT')); } } data[key] = val; }); return data; }; Cassandra.prototype.propertiesSQL = function (model) { 'use strict'; var self = this; var sql = []; Object.keys(this._models[model].properties).forEach(function (prop) { if (prop === 'id') { return; } return sql.push('' + prop + ' ' + self.propertySettingsSQL(model, prop)); }); var primaryKeys = this._models[model].settings.primaryKeys || []; primaryKeys = primaryKeys.slice(0); if (primaryKeys.length) { for (var i = 0, length = primaryKeys.length; i < length; i++) { primaryKeys[i] = "" + primaryKeys[i] + ""; } sql.push("PRIMARY KEY (" + primaryKeys.join(', ') + ")"); } else { sql.push('id timeuuid PRIMARY KEY'); } return sql.join(',\n '); }; Cassandra.prototype.propertySettingsSQL = function (model, prop) { 'use strict'; var p = this._models[model].properties[prop], field = []; field.push(datatype(p)); return field.join(" "); }; Cassandra.prototype.escapeName = function (name) { 'use strict'; return name.toLowerCase(); }; Cassandra.prototype.toFields = function (model, data) { 'use strict'; var fields = []; var props = this._models[model].properties; Object.keys(data).forEach(function (key) { if (props[key] && key !== 'id') { fields.push(key + ' = ' + this.toDatabase(props[key], data[key])); } }.bind(this)); return fields.join(','); }; Cassandra.prototype.toDatabase = function (prop, val) { 'use strict'; if (val === null) { return 'NULL'; } if (val.constructor.name === 'Object') { var operator = Object.keys(val)[0]; val = val[operator]; if (operator === 'between') { if (prop.type.name === 'Date') { return 'STR_TO_DATE(' + this.toDatabase(prop, val[0]) + ', "%Y-%m-%d %H:%i:%s")' + ' AND STR_TO_DATE(' + this.toDatabase(prop, val[1]) + ', "%Y-%m-%d %H:%i:%s")'; } else { return this.toDatabase(prop, val[0]) + ' AND ' + this.toDatabase(prop, val[1]); } } else if (operator === 'in' || operator === 'inq' || operator === 'nin') { if (!(val.propertyIsEnumerable('length')) && typeof val === 'object' && typeof val.length === 'number') { //if value is array for (var i = 0; i < val.length; i++) { val[i] = this.escapeName(val[i]); } return val.join(','); } else { return val; } } } if (!prop) { return val; } var type = (prop.type.name || '').toLowerCase(); if (type === 'json') { return val; } if (type === 'uuid' || type === 'timeuuid' || type === 'number' || type === 'float' || type === 'integer' || type === 'real') { return val; } if (type === 'date') { if (!val) { return 'NULL'; } if (typeof val === 'string') { val = val.split('.')[0].replace('T', ' '); val = Date.parse(val); } if (typeof val === 'number') { val = new Date(val); } if (val instanceof Date) { val = val.getTime(); } return val; } if (type === "boolean" || type === "tinyint") { return val ? 1 : 0; } return '\'' + val.toString() + '\''; }; function dateToCassandra(val) { 'use strict'; return val.getUTCFullYear() + '-' + fillZeros(val.getUTCMonth() + 1) + '-' + fillZeros(val.getUTCDate()) + ' ' + fillZeros(val.getUTCHours()) + ':' + fillZeros(val.getUTCMinutes()) + ':' + fillZeros(val.getUTCSeconds()); function fillZeros(v) { 'use strict'; return v < 10 ? '0' + v : v; } } function parseCond(cs, key, props, conds, self) { 'use strict'; var keyEscaped = '' + key + ''; var val = self.toDatabase(props[key], conds[key]); if (conds[key] === null) { cs.push(keyEscaped + ' IS NULL'); } else if (conds[key].constructor.name === 'Object') { Object.keys(conds[key]).forEach(function (condType) { val = self.toDatabase(props[key], conds[key][condType]); var sqlCond = keyEscaped; if ((condType === 'inq' || condType === 'nin') && val.length === 0) { cs.push(condType === 'inq' ? 0 : 1); return true; } switch (condType) { case 'gt': sqlCond += ' > '; break; case 'gte': sqlCond += ' >= '; break; case 'lt': sqlCond += ' < '; break; case 'lte': sqlCond += ' <= '; break; case 'between': sqlCond += ' BETWEEN '; break; case 'inq': case 'in': sqlCond += ' IN '; break; case 'nin': sqlCond += ' NOT IN '; break; case 'neq': case 'ne': sqlCond += ' != '; break; case 'regex': sqlCond += ' REGEXP '; break; case 'like': sqlCond += ' LIKE '; break; case 'nlike': sqlCond += ' NOT LIKE '; break; default: sqlCond += ' ' + condType + ' '; break; } sqlCond += (condType === 'in' || condType === 'inq' || condType === 'nin') ? '(' + val + ')' : val; cs.push(sqlCond); }); } else if (/^\//gi.test(conds[key])) { var reg = val.toString().split('/'); cs.push(keyEscaped + ' REGEXP "' + reg[1] + '"'); } else { cs.push(keyEscaped + ' = ' + val); } return cs; } function datatype(p) { 'use strict'; var dt = ''; switch ((p.type.name || 'string').toLowerCase()) { case 'json': dt = 'map<text,text>'; break; case 'text': dt = 'text'; break; case 'int': case 'integer': case 'number': dt = (parseFloat(p.limit) > 11) ? "bigint" : "int"; break; case 'float': case 'double': dt = 'float'; case 'real': dt = 'decimal'; break; case 'timestamp': case 'date': dt = 'timestamp'; break; case 'boolean': case 'bool': dt = 'boolean'; break; case 'uuid': case 'timeuuid': dt = 'uuid'; break; case 'blob': case 'bytes': dt = 'bytes'; break; case 'countercolumn': dt = 'countercolumn'; break; default: dt = 'text'; } return dt; }
philipz/caminte
lib/adapters/cassandra.js
JavaScript
mit
23,406
$(document).ready(function(){ $("#lang").change(function(){ var lang = $("#lang").val(); $.ajax({ "type":"POST", // "url":baseUrl+"home/checklang", "data":"lang="+lang, "async":true, "success":function(result){ window.location=baseUrl+lang; } }) }) })
vungocgiao1510/giao
public/default/js/jquery_code.js
JavaScript
mit
339
import Pyro4 import Pyro4.errors from diffiehellman import DiffieHellman dh = DiffieHellman(group=14) with Pyro4.locateNS() as ns: uri = ns.lookup("example.dh.secretstuff") print(uri) p = Pyro4.Proxy(uri) try: p.process("hey") raise RuntimeError("this should not be reached") except Pyro4.errors.PyroError as x: print("Error occured (expected!):", x) with Pyro4.Proxy("PYRONAME:example.dh.keyexchange") as keyex: print("exchange public keys...") other_key = keyex.exchange_key(dh.public_key) print("got server public key, creating shared secret key...") dh.make_shared_secret_and_key(other_key) print("setting key on proxy.") p._pyroHmacKey = dh.key print("Calling proxy again...") result = p.process("hey") print("Got reply:", result)
irmen/Pyro4
examples/diffie-hellman/client.py
Python
mit
786
#region License Information (GPL v3) /* ShareX - A program that allows you to take screenshots and share any file type Copyright (c) 2007-2016 ShareX Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Optionally you can also view the license at <http://www.gnu.org/licenses/>. */ #endregion License Information (GPL v3) using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Cache; using System.Text; using Newtonsoft.Json; namespace puush_installer.ShareX.HelpersLib { public class GitHubUpdateChecker : UpdateChecker { public string Owner { get; private set; } public string Repo { get; private set; } public bool IncludePreRelease { get; set; } private const string APIURL = "https://api.github.com"; private string ReleasesURL => $"{APIURL}/repos/{Owner}/{Repo}/releases"; public GitHubUpdateChecker(string owner, string repo) { Owner = owner; Repo = repo; } public override void CheckUpdate() { } public string GetLatestDownloadURL(bool includePreRelease, bool isPortable, bool isBrowserDownloadURL) { try { GitHubRelease latestRelease = GetLatestRelease(includePreRelease); if (UpdateReleaseInfo(latestRelease, isPortable, isBrowserDownloadURL)) { return DownloadURL; } } catch (Exception) { //DebugHelper.WriteException(e); } return null; } public string GetDownloadCounts() { StringBuilder sb = new StringBuilder(); foreach (GitHubRelease release in GetReleases().Where(x => x.assets != null && x.assets.Count > 0)) { sb.AppendFormat("{0} ({1}): {2}{3}", release.name, DateTime.Parse(release.published_at), release.assets.Sum(x => x.download_count), Environment.NewLine); } return sb.ToString().Trim(); } private List<GitHubRelease> GetReleases() { using (WebClient wc = new WebClient()) { wc.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); wc.Headers.Add("user-agent", "ShareX"); wc.Proxy = Proxy; string response = wc.DownloadString(ReleasesURL); if (!string.IsNullOrEmpty(response)) { return JsonConvert.DeserializeObject<List<GitHubRelease>>(response); } } return null; } private GitHubRelease GetLatestRelease(bool includePreRelease) { GitHubRelease latestRelease = null; List<GitHubRelease> releases = GetReleases(); if (releases != null && releases.Count > 0) { if (includePreRelease) { latestRelease = releases[0]; } else { latestRelease = releases.FirstOrDefault(x => !x.prerelease); } } return latestRelease; } public bool UpdateReleaseInfo(GitHubRelease release, bool isPortable, bool isBrowserDownloadURL) { if (release != null && !string.IsNullOrEmpty(release.tag_name) && release.tag_name.Length > 1 && release.tag_name[0] == 'v') { LatestVersion = new Version(release.tag_name.Substring(1)); if (release.assets != null && release.assets.Count > 0) { string endsWith; if (isPortable) { endsWith = "portable.zip"; } else { endsWith = ".exe"; } foreach (GitHubAsset asset in release.assets) { if (asset != null && !string.IsNullOrEmpty(asset.name) && asset.name.EndsWith(endsWith, StringComparison.InvariantCultureIgnoreCase)) { Filename = asset.name; if (isBrowserDownloadURL) { DownloadURL = asset.browser_download_url; } else { DownloadURL = asset.url; } return true; } } } } return false; } } [System.Reflection.ObfuscationAttribute(Feature = "renaming", ApplyToMembers = true)] [Serializable] public class GitHubRelease { public string url { get; set; } public string assets_url { get; set; } public string upload_url { get; set; } public string html_url { get; set; } public int id { get; set; } public string tag_name { get; set; } public string target_commitish { get; set; } public string name { get; set; } public string body { get; set; } public bool draft { get; set; } public bool prerelease { get; set; } public string created_at { get; set; } public string published_at { get; set; } public List<GitHubAsset> assets { get; set; } public string tarball_url { get; set; } public string zipball_url { get; set; } } [System.Reflection.ObfuscationAttribute(Feature = "renaming", ApplyToMembers = true)] [Serializable] public class GitHubAsset { public string url { get; set; } public int id { get; set; } public string name { get; set; } public string label { get; set; } public string content_type { get; set; } public string state { get; set; } public int size { get; set; } public int download_count { get; set; } public string created_at { get; set; } public string updated_at { get; set; } public string browser_download_url { get; set; } } }
Jaex/puush-installer
puush-installer/ShareX.HelpersLib/GitHubUpdateChecker.cs
C#
mit
7,044
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace FancyAsyncMagic { public class AsyncWriter { private readonly Stream _Stream; public AsyncWriter(Stream stream) { _Stream = stream; } private Task WriteBytes(byte[] data, CancellationToken token) { return _Stream.WriteAsync(data, 0, data.Length, token); } private async Task WriteBytesAndType(byte[] data, ElementType type, CancellationToken token, byte[] dataPrefix = null) { await WriteBytes(new byte[] { (byte)type }, token); if (dataPrefix != null) await WriteBytes(dataPrefix, token); await WriteBytes(data, token); } public Task Write(byte b, CancellationToken token) { return WriteBytesAndType(new byte[] { b }, ElementType.Byte, token); } public Task Write(Int32 i, CancellationToken token) { return WriteBytesAndType(BitConverter.GetBytes(i), ElementType.Int32, token); } public Task Write(Int64 i, CancellationToken token) { return WriteBytesAndType(BitConverter.GetBytes(i), ElementType.Int64, token); } public Task Write(UInt32 i, CancellationToken token) { return WriteBytesAndType(BitConverter.GetBytes(i), ElementType.UInt32, token); } public Task Write(UInt64 i, CancellationToken token) { return WriteBytesAndType(BitConverter.GetBytes(i), ElementType.UInt64, token); } public Task Write(byte[] data, CancellationToken token) { return WriteBytesAndType(data, ElementType.ByteArray, token, BitConverter.GetBytes(data.Length)); } public Task Write(string s, CancellationToken token) { return WriteBytesAndType(Encoding.UTF8.GetBytes(s), ElementType.String, token, BitConverter.GetBytes(Encoding.UTF8.GetByteCount(s))); } } }
main--/FancyAsyncMagic
FancyAsyncMagic/AsyncWriter.cs
C#
mit
2,141
<?php /* * This file is part of KoolKode BPMN. * * (c) Martin Schröder <m.schroeder2007@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types = 1); namespace KoolKode\BPMN\Task\Command; use KoolKode\BPMN\Engine\AbstractBusinessCommand; use KoolKode\BPMN\Engine\ProcessEngine; use KoolKode\BPMN\Task\Event\UserTaskUnclaimedEvent; use KoolKode\Util\UUID; /** * Removes the current assignee from a user task. * * @author Martin Schröder */ class UnclaimUserTaskCommand extends AbstractBusinessCommand { protected $taskId; public function __construct(UUID $taskId) { $this->taskId = $taskId; } /** * {@inheritdoc} * * @codeCoverageIgnore */ public function isSerializable(): bool { return true; } /** * {@inheritdoc} */ public function executeCommand(ProcessEngine $engine): void { $task = $engine->getTaskService()->createTaskQuery()->taskId($this->taskId)->findOne(); if (!$task->isClaimed()) { throw new \RuntimeException(\sprintf('User task %s is not claimed', $task->getId())); } $sql = " UPDATE `#__bpmn_user_task` SET `claimed_at` = :time, `claimed_by` = :assignee WHERE `id` = :id "; $stmt = $engine->prepareQuery($sql); $stmt->bindValue('time', null); $stmt->bindValue('assignee', null); $stmt->bindValue('id', $task->getId()); $stmt->execute(); $task = $engine->getTaskService()->createTaskQuery()->taskId($this->taskId)->findOne(); $engine->notify(new UserTaskUnclaimedEvent($task, $engine)); $engine->debug('User task "{task}" unclaimed', [ 'task' => $task->getName() ]); } }
koolkode/bpmn
src/Task/Command/UnclaimUserTaskCommand.php
PHP
mit
1,946
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies and Contributors # See license.txt import frappe import unittest # test_records = frappe.get_test_records('OAuth Authorization Code') class TestOAuthAuthorizationCode(unittest.TestCase): pass
mhbu50/frappe
frappe/integrations/doctype/oauth_authorization_code/test_oauth_authorization_code.py
Python
mit
261
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) from folium.plugins.marker_cluster import MarkerCluster from folium.utilities import _validate_coordinates from jinja2 import Template class FastMarkerCluster(MarkerCluster): """ Add marker clusters to a map using in-browser rendering. Using FastMarkerCluster it is possible to render 000's of points far quicker than the MarkerCluster class. Be aware that the FastMarkerCluster class passes an empty list to the parent class' __init__ method during initialisation. This means that the add_child method is never called, and no reference to any marker data are retained. Methods such as get_bounds() are therefore not available when using it. Parameters ---------- data: list List of list of shape [[], []]. Data points should be of the form [[lat, lng]]. callback: string, default None A string representation of a valid Javascript function that will be passed a lat, lon coordinate pair. See the FasterMarkerCluster for an example of a custom callback. name : string, default None The name of the Layer, as it will appear in LayerControls. overlay : bool, default True Adds the layer as an optional overlay (True) or the base layer (False). control : bool, default True Whether the Layer will be included in LayerControls. show: bool, default True Whether the layer will be shown on opening (only for overlays). options : dict, default None A dictionary with options for Leaflet.markercluster. See https://github.com/Leaflet/Leaflet.markercluster for options. """ _template = Template(u""" {% macro script(this, kwargs) %} var {{ this.get_name() }} = (function(){ {{this._callback}} var data = {{ this._data }}; var cluster = L.markerClusterGroup({{ this.options }}); for (var i = 0; i < data.length; i++) { var row = data[i]; var marker = callback(row); marker.addTo(cluster); } cluster.addTo({{ this._parent.get_name() }}); return cluster; })(); {% endmacro %}""") def __init__(self, data, callback=None, options=None, name=None, overlay=True, control=True, show=True): super(FastMarkerCluster, self).__init__(name=name, overlay=overlay, control=control, show=show, options=options) self._name = 'FastMarkerCluster' self._data = _validate_coordinates(data) if callback is None: self._callback = """ var callback = function (row) { var icon = L.AwesomeMarkers.icon(); var marker = L.marker(new L.LatLng(row[0], row[1])); marker.setIcon(icon); return marker; };""" else: self._callback = 'var callback = {};'.format(callback)
QuLogic/folium
folium/plugins/fast_marker_cluster.py
Python
mit
3,213
namespace OggVorbisEncoder.Setup.Templates.FloorBooks { public class Line256X7_0Sub3 : IStaticCodeBook { public int Dimensions { get; } = 1; public byte[] LengthList { get; } = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3, 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9, 10, 9, 11, 13, 11, 13, 10, 10, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12 }; public CodeBookMapType MapType { get; } = CodeBookMapType.None; public int QuantMin { get; } = 0; public int QuantDelta { get; } = 0; public int Quant { get; } = 0; public int QuantSequenceP { get; } = 0; public int[] QuantList { get; } = null; } }
vr-the-feedback/vr-the-feedback-unity
Assets/VRTheFeedback/Scripts/OggVorbisEncoder/Setup/Templates/FloorBooks/Line256X7_0Sub3.cs
C#
mit
775
#include "SumUnique.cc" #include <algorithm> #include <cmath> #include <cstdlib> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <sys/time.h> #include <vector> const static double __EPSILON = 1e-9; static double __time = 0.0; static void __timer_start() { struct timeval tv; if (gettimeofday(&tv, NULL) == 0) { __time = double(tv.tv_sec) * 1000.0 + double(tv.tv_usec) * 0.001; } } static double __timer_stop() { double start = __time; __timer_start(); return __time - start; } static void __eat_whitespace(std::istream& in) { while (in.good() && std::isspace(in.peek())) in.get(); } std::ostream& operator << (std::ostream& out, const std::string& str) { out << '"' << str.c_str() << '"'; return out; } template <class T> std::ostream& operator << (std::ostream& out, const std::vector<T>& vec) { out << '{'; if (0 < vec.size()) { out << vec[0]; for (size_t i = 1; i < vec.size(); ++i) out << ", " << vec[i]; } out << '}'; return out; } std::istream& operator >> (std::istream& in, std::string& str) { __eat_whitespace(in); int c; if (in.good() && (c = in.get()) == '"') { std::ostringstream s; while (in.good() && (c = in.get()) != '"') { s.put(char(c)); } str = s.str(); } return in; } template <class T> std::istream& operator >> (std::istream& in, std::vector<T>& vec) { __eat_whitespace(in); int c; if (in.good() && (c = in.get()) == '{') { __eat_whitespace(in); vec.clear(); while (in.good() && (c = in.get()) != '}') { if (c != ',') in.putback(c); T t; in >> t; __eat_whitespace(in); vec.push_back(t); } } return in; } template <class T> bool __equals(const T& actual, const T& expected) { return actual == expected; } bool __equals(double actual, double expected) { if (std::abs(actual - expected) < __EPSILON) { return true; } else { double minimum = std::min(expected * (1.0 - __EPSILON), expected * (1.0 + __EPSILON)); double maximum = std::max(expected * (1.0 - __EPSILON), expected * (1.0 + __EPSILON)); return actual > minimum && actual < maximum; } } bool __equals(const std::vector<double>& actual, const std::vector<double>& expected) { if (actual.size() != expected.size()) { return false; } for (size_t i = 0; i < actual.size(); ++i) { if (!__equals(actual[i], expected[i])) { return false; } } return true; } int main(int argc, char* argv[]) { bool __abort_on_fail = false; int __pass = 0; int __fail = 0; if (1 < argc) __abort_on_fail = true; std::cout << "TAP version 13" << std::endl; std::cout.flush(); std::ifstream __in("testcases.txt"); for(;;) { int __testnum = __pass + __fail + 1; int __expected; vector <int> values; __in >> __expected >> values; if (!__in.good()) break; std::cout << "# input for test " << __testnum << ": " << values << std::endl; std::cout.flush(); __timer_start(); SumUnique __object; int __actual = __object.getSum(values); double __t = __timer_stop(); std::cout << "# test completed in " << __t << "ms" << std::endl; std::cout.flush(); if (__equals(__actual, __expected)) { std::cout << "ok"; ++__pass; } else { std::cout << "not ok"; ++__fail; } std::cout << " " << __testnum << " - " << __actual << " must equal " << __expected << std::endl; std::cout.flush(); if (__abort_on_fail && 0 < __fail) std::abort(); } std::cout << "1.." << (__pass + __fail) << std::endl << "# passed: " << __pass << std::endl << "# failed: " << __fail << std::endl; if (__fail == 0) { std::cout << std::endl << "# Nice! Don't forget to compile remotely before submitting." << std::endl; } return __fail; } // vim:ft=cpp:noet:ts=8
mathemage/CompetitiveProgramming
topcoder/SRM/Rookie-SRM-7-DIV-1/500/driver.cc
C++
mit
3,736
/* jshint node: true */ module.exports = function(grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: [ '*.js', 'spec/*.js' ], options: { jshintrc: '.jshintrc' } }, jasmine: { src: 'method-proxy.js', options: { specs: 'spec/**/*.js' } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.registerTask('test', ['jshint', 'jasmine']); grunt.registerTask('default', ['test']); };
causes/method-proxy-js
Gruntfile.js
JavaScript
mit
584
var gulp = require('gulp'), sass = require('gulp-sass'), scsslint = require('gulp-scss-lint'); gulp.task('sass', function () { gulp.src('./_sass/**/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('./css')); }); gulp.task('scsslint', function () { gulp.src('./_sass/**/*.scss') .pipe(scsslint()) }); gulp.task('sass:watch', function () { gulp.watch('./_sass/**/*.scss', ['sass']); }); gulp.task('sass:watch:lint', function () { gulp.watch(['./_sass/**/*.scss', './_sass/**/_*.scss'], ['sass','scsslint']); });
rogeralbinoi/html5-boilerplate-sass-lint
Gulpfile.js
JavaScript
mit
557
<?php require_once __DIR__ . '/vendor/autoload.php'; use Chadicus\Marvel\Api\Client; use Chadicus\Marvel\Api\Entities\ImageVariant; use DominionEnterprises\Util\Arrays; $nameStartsWith = Arrays::get($_POST, 'nameStartsWith'); ?> <html> <head> <style> label { display: inline-block; width: 140px; text-align: right; } img { max-width:800px; } </style> </head> <body> <form method="POST" action="/"> <fieldset> <legend>Search Characters</legend> <br /> <label for="nameStartsWith">Name</label> <input type="text" name="nameStartsWith" size="32" value="<?=$nameStartsWith?>" /> <br /> <input type="Submit" value="Search" /> </fieldset> </form> <?php if ($_SERVER['REQUEST_METHOD'] === 'POST'): ?> <?php $client = new Client(getenv('PRIVATE_KEY'), getenv('PUBLIC_KEY')); $dataWrapper = $client->search('characters', ['nameStartsWith' => $nameStartsWith]); $count = 0; ?> <h3><?=$dataWrapper->getData()->getTotal()?> characters found</h3> <table border="1"> <tbody> <tr> <?php foreach ($dataWrapper->getData()->getResults() as $character): ?> <?php if ($count++ % 5 === 0): ?> </tr><tr> <?php endif; ?> <td> <p><?=$character->getName()?></p> <a href="<?=$character->getUrls()[0]->getUrl()?>"> <img src="<?=$character->getThumbnail()->getUrl(ImageVariant::PORTRAIT_XLARGE())?>" /> </a> </td> <?php endforeach; ?> </tr> </tbody> </table> <center><?=$dataWrapper->getAttributionHTML()?></center> <?php endif; ?> </body> </html>
chadicus/marvel-api-client
examples/gallery/index.php
PHP
mit
2,104
<?php /******************************************************************* * Glype is copyright and trademark 2007-2015 UpsideOut, Inc. d/b/a Glype * and/or its licensors, successors and assigners. All rights reserved. * * Use of Glype is subject to the terms of the Software License Agreement. * http://www.glype.com/license.php ******************************************************************* * This is the parser for the proxy - changes the original 'raw' * document so that everything (images, links, etc.) is rerouted to * be downloaded via the proxy script instead of directly. ******************************************************************/ class parser { # State of javascript parser - null for parse everything, false # for parse all non-standard overrides, or (array) with specifics private $jsFlagState; # Browsing options (Remove Scripts, etc.) private $htmlOptions; # Constructor accepts options and saves them in the object function __construct($htmlOptions, $jsFlags) { $this->jsFlagState = $jsFlags; $this->htmlOptions = $htmlOptions; } /***************************************************************** * HTML parsers - main parsing function splits up document into * component parts ('normal' HTML, scripts and styles) ******************************************************************/ function HTMLDocument($input, $insert='', $inject=false, $footer='') { if (strlen($input)>65536) { if (version_compare(PHP_VERSION, '5.3.7')<=0) { ini_set('pcre.backtrack_limit', 1000000); } } # # Apply parsing that only needs to be done once.. # # Record the charset global $charset; if (!isset($charset)) { $meta_equiv = preg_match('#(<meta[^>]*http\-equiv\s*=[^>]*>)#is', $input, $tmp, PREG_OFFSET_CAPTURE) ? $tmp[0][0] : null; if (isset($meta_equiv)) { $charset = preg_match('#charset\s*=\s*["\']+([^"\'\s>]*)#is', $meta_equiv, $tmp, PREG_OFFSET_CAPTURE) ? $tmp[1][0] : null; } } if (!isset($charset)) { $meta_charset = preg_match('#<meta[^>]*charset\s*=\s*["\']+([^"\'\s>]*)#is', $input, $tmp, PREG_OFFSET_CAPTURE) ? $tmp[1][0] : null; if (isset($meta_charset)) { $charset = $meta_charset; } } # Remove empty script comments $input = preg_replace('#/\*\s*\*/#s', '', $input); # Remove conditional comments $input = preg_replace('#<\!\-\-\[if \!IE\]>\s*\-\->(.*?)<\!\[endif\]\-\->#s','$1',$input); $input = preg_replace('#<\!\-\-\[if.*?<\!\[endif\]\-\->#s','',$input); # Prevent websites from calling disableOverride() $input = preg_replace('#disableOverride#s', 'disabled___disableOverride', $input); # Remove titles if option is enabled if ( $this->htmlOptions['stripTitle'] || $this->htmlOptions['encodePage'] ) { $input = preg_replace('#<title.*?</title>#is', '', $input, 1); $input = preg_replace('#<meta[^>]*name=["\'](title|description|keywords)["\'][^>]*>#is', '', $input, 3); $input = preg_replace('#<link[^>]*rel=["\'](icon|shortcut icon)["\'][^>]*>#is', '', $input, 2); } # Remove and record a <base> href $input = preg_replace_callback('#<base href\s*=\s*([\\\'"])?((?(1)(?(?<=")[^"]{1,2048}|[^\\\']{1,2048})|[^\s"\\\'>]{1,2048}))(?(1)\\1|)[^>]*>#i', 'html_stripBase', $input, 1); # Proxy url= values in meta redirects $input = preg_replace_callback('#content\s*=\s*(["\\\'])?[0-9]+\s*;\s*url=([\\\'"]|&\#39;)?((?(?<=")[^"]+|(?(?<=\\\')[^\\\']+|[^\\\'" >]+)))(?(2)\\2|)(?(1)\\1|)#i', 'html_metaRefresh', $input, 1); # Process forms $input = preg_replace_callback('#<form([^>]*)>(.*?)</form>#is', 'html_form', $input); # Remove scripts blocks (avoids individual processing below) if ( $this->htmlOptions['stripJS'] ) { $input = preg_replace('#<script[^>]*>.*?</script>#is', '', $input); } # # Split up the document into its different types and parse them # # Build up new document into this var $new = ''; $offset = 0; # Find instances of script or style blocks while ( preg_match('#<(s(?:cript|tyle))[^>]*>#i', $input, $match, PREG_OFFSET_CAPTURE, $offset) ) { # What type of block is this? $block = strtolower($match[1][0]); # Start position of content $outerStart = $match[0][1]; $innerStart = $outerStart + strlen($match[0][0]); # Determine type of end tag and find it's position $endTag = "</$block>"; $innerEnd = stripos($input, $endTag, $innerStart); if ($innerEnd===false) { $endTag = "</"; $innerEnd = stripos($input, $endTag, $innerStart); if ($innerEnd===false) { $input = preg_replace('#<script[^>]*>.*?$#is', '', $input); break; } } $outerEnd = $innerEnd + strlen($endTag); # Parse everything up till here and add to the new document $new .= $this->HTML(substr($input, $offset, $innerStart - $offset)); # Find parsing function $parseFunction = $block == 'style' ? 'CSS' : 'JS' ; # Add the parsed block $new .= $this->$parseFunction(substr($input, $innerStart, $innerEnd - $innerStart)); # Move offset to new position $offset = $innerEnd; } # And add the final chunk (between last script/style block and end of doc) $new .= $this->HTML(substr($input, $offset)); # Replace input with the updated document $input = $new; global $foundPlugin; if ( $foundPlugin && function_exists('postParse') ) { $input = postParse($input, 'html'); $foundPlugin=false; } # Make URLs relative $input = preg_replace('#=\s*(["\'])?\s*https?://[^"\'>/]*/#i', '=$1/', $input); # Encode the page if ( $this->htmlOptions['encodePage'] ) { $input = encodePage($input); } # # Now add our own code bits # # Insert our mini form after the <body> if ( $insert !== false ) { # Check for a frameset if ( ( $useFrames = stripos($input, '<frameset') ) !== false ) { # Flag the frames so only first displays mini-form $input = preg_replace_callback('#<frame[^>]+src\s*=\s*([\\\'"])?((?(1)(?(?<=")[^"]{1,2048}|[^\\\']{1,2048})|[^\s"\\\'>]{1,2048}))(?(1)\\1|)#i', 'html_flagFrames', $input); } # Attempt to add after body $input = preg_replace('#(<body[^>]*>)#i', '$1' . $insert, $input, 1, $tmp); # Check it inserted and append (if not a frameset) if ( ! $tmp && ! $useFrames ) { $input = $insert . $input; } } # Insert our javascript library if ( $inject ) { # Generate javascript to insert $inject = injectionJS(); # Add our proxy javascript after <head> $input = preg_replace('#(<head[^>]*>)#i', '$1' . $inject, $input, 1, $tmp); # If no <head>, just prepend if ( ! $tmp ) { $input = $inject . $input; } } # Add anything to the footer? if ( $footer ) { $input = preg_replace('#(</body[^>]*>)#i', $footer . '$1', $input, 1, $tmp); # If no </body>, just append the footer if ( ! $tmp ){ $input .= $footer; } } # Return new document return $input; } # Parse HTML sections function HTML($input) { # Removing objects? Follow spec and display inner content of object tags instead. if ( $this->htmlOptions['stripObjects'] ) { # Remove all object tags (including those deprecated but still common) $input = preg_replace('#<(?>object|applet|param|embed)[^>]*>#i', '', $input, -1, $tmp); # Found any? Remove the corresponding end tags if ( $tmp ) { $input = preg_replace('#</(?>object|applet|param|embed)>#i', '', $input, $tmp); } } else { # Parse <param name="movie" value="URL"> tags $input = preg_replace_callback('#<param[^>]+value\s*=\s*([\\\'"])?((?(1)(?(?<=")[^"]{1,2048}|[^\\\']{1,2048})|[^\s"\\\'>]{1,2048}))(?(1)\\1|)[^>]*>#i', 'html_paramValue', $input); # To do: proxy object related URLs } # Show content within <noscript> tags # (preg_ seems to be faster than 2 str_ireplace() calls) if ( $this->htmlOptions['stripJS'] ) { $input = preg_replace('#</?noscript>#i', '', $input); } # remove srcset attribute for now $input = preg_replace('#srcset\s*=\s*[\\\'"][^"]*[\\\'"]#i', '', $input); # Parse onX events $input = preg_replace_callback('#\b(on(?<!\.on)[a-z]{2,20})\s*=\s*([\\\'"])?((?(2)(?(?<=")[^"]{1,2048}|[^\\\']{1,2048})|[^\s"\\\'>]{1,2048}))(?(2)\\2|)#i', array(&$this, 'html_eventJS'), $input); # Parse style attributes $input = preg_replace_callback('#style\s*=\s*([\\\'"])?((?(1)(?(?<=")[^"]{1,2048}|[^\\\']{1,2048})|[^\s"\\\'>]{1,2048}))(?(1)\\1|)#i', array(&$this, 'html_elementCSS'), $input); # Proxy URL attributes - this is the bottleneck but optimized as much as possible $input = preg_replace_callback('#(?><[A-Z0-9]{1,15})(?>\s+[^>\s]+)*?\s*(?>(href|src|background|poster)\s*=(?!\\\\)\s*)(?>([\\\'"])?)((?(2)(?(?<=")[^"]{1,2048}|[^\\\']{1,2048})|[^ >]{1,2048}))(?(2)\\2|)#i', 'html_attribute', $input); # Return changed input return $input; } # Proxy an onX javascript event function html_eventJS($input) { return $this->htmlOptions['stripJS'] ? '' : $input[1] . '=' . $input[2] . $this->JS($input[3]) . $input[2]; } # Proxy a style="CSS" attribute function html_elementCSS($input) { return 'style=' . $input[1] . $this->CSS($input[2]) . $input[1]; } /***************************************************************** * CSS parser - main parsing function * CSS parsing is a complicated by the caching of CSS files. We need * to consider (A) cross-domain caching and (B) the unique URLs option. * A) If possible, use a relative URL so the saved URLs do not explictly * point to a single domain. * B) There is a second set of callback functions with "_unique" suffixed * and these return the original URL to be reparesed. ******************************************************************/ # The URLs depend on the unique and path info settings. The type parameter allows # us to specify the unique callbacks. function CSS($input, $storeUnique=false) { # What type of parsing is this? Normally we parse any URLs to redirect # back through the proxy but not when storing a cache with unique URLs. $type = $storeUnique ? '_unique' : ''; # CSS needs proxying the calls to url(), @import and src='' $input = preg_replace_callback('#\burl\s*\(\s*[\\\'"]?([^\\\'"\)]+)[\\\'"]?\s*\)#i', 'css_URL' . $type, $input); $input = preg_replace_callback('#@import\s*[\\\'"]([^\\\'"\(\)]+)[\\\'"]#i', 'css_import' . $type, $input); $input = preg_replace_callback('#\bsrc\s*=\s*([\\\'"])?([^)\\\'"]+)(?(1)\\1|)#i', 'css_src' . $type, $input); # Make URLs relative $input = preg_replace('#https?://[^"\'>/]*/#i', '/', $input); # Return changed return $input; } /***************************************************************** * Javascript parser - main parsing function * * The specific parts that need proxying depends on which javascript * functions we've been able to override. On first page load, the browser * capabilities are tested to see what we can do client-side and the results * sent back to us. This allows us to parse only what we have to. * If $CONFIG['override_javascript'] is disabled, all commands are parsed * server-side. This will use much more CPU! * * Commands to proxy only if no override at all: * document.write() * document.writeln() * window.open() * eval() * * Commands to proxy, regardless of browser capabilities: * location.replace() * .innerHTML= * * Commands to proxy if the extra "watch" flag is set * (the browser doesn't support the .watch() method): * location= * x.location= * location.href= * * Commands to proxy if the extra "setters" flag is set * (the browser doesn't support the __defineSetter__() method): * .src= * .href= * .background= * .action= * * Commands to proxy if the extra "ajax" flag is set * (the browser failed to override the .open() method): * XMLHttpRequest.open() ******************************************************************/ function JS($input) { # Stripping? if ( $this->htmlOptions['stripJS'] ) { return ''; } # Get our flags $flags = $this->jsFlagState; # Unless we know we don't need to, apply all the browser-specific flags if ( ! is_array($this->jsFlagState) ) { $flags = array('ajax', 'watch', 'setters'); } # If override is disabled, add a "base" flag if ( $this->jsFlagState === null ) { $flags[] = 'base'; } # Start parsing! $search = array(); # Create shortcuts to various search patterns: # "before" - matches preceeding character (string of single char) [ignoring whitespace] # "after" - matches next character (string of single char) [ignoring whitespace] # "id" - key for identifying the original match (e.g. if we have >1 of the same key) $assignmentPattern = array('before' => '.', 'after' => '='); $methodPattern = array('before' => '.', 'after' => '('); $functionPattern = array('after' => '('); # Configure strings to search for, starting with always replaced commands $search['innerHTML'][] = $assignmentPattern; $search['location'][] = array('after' => '.', 'id' => 'replace()'); # ^ This is only for location.replace() - other forms are handled later # Look for attribute assignments if ( in_array('setters', $flags) ) { $search['src'][] = $assignmentPattern; $search['href'][] = $assignmentPattern; $search['action'][] = $assignmentPattern; $search['background'][] = $assignmentPattern; $search['poster'][] = $assignmentPattern; } # Look for location changes # location.href will be handled above, location= is handled here if ( in_array('watch', $flags) ) { $search['location'][] = array('after' => '=', 'id' => 'assignment'); } # Look for .open() if either AJAX (XMLHttpRequest.open) or # base (window.open) flags are present if ( in_array('ajax', $flags) || in_array('base', $flags) ) { $search['open'][] = $methodPattern; } # Add the basic code if no override if ( in_array('base', $flags) ) { $search['eval'][] = $functionPattern; $search['writeln'][] = $methodPattern; $search['write'][] = $methodPattern; } # Set up starting parameters $offset = 0; $length = strlen($input); $searchStrings = array_keys($search); while ( $offset < $length ) { # Start off by assuming no more items (i.e. the next position # of interest is the end of the document) $commandPos = $length; # Loop through the search subjects foreach ( $searchStrings as $item ) { # Any more instances of this? if ( ( $tmp = strpos($input, $item, $offset) ) === false ) { # Nope, skip to next item continue; } # If $item is whole word? if ( ( $input[$tmp-1] == '_' ) || ctype_alpha($input[$tmp-1]) ) { # No continue; } # Closer to the currently held 'next' position? if ( $tmp < $commandPos ) { $commandPos = $tmp; $command = $item; } } # No matches found? Finish parsing. if ( $commandPos == $length ) { break; } # We've found the main point of interest; now use the # search parameters to check the surrounding chars to validate # the match. $valid = false; foreach ( $search[$command] as $pattern ) { # Check the preceeding chars if ( isset($pattern['before']) && str_checkprev($input, $pattern['before'], $commandPos-1) === false ) { continue; } # Check next chars if ( isset($pattern['after']) && ( $charPos = str_checknext($input, $pattern['after'], $commandPos + strlen($command), false, false) ) === false ) { continue; } $postCharPos = ($charPos + 1) + strspn($input, " \t\r\n", $charPos + 1); # Still here? Match must be OK so generate a match ID if ( isset($pattern['id']) ) { $valid = $command . $pattern['id']; } else { $valid = $command; } break; } # What we do next depends on which match (if any) we've found... switch ( $valid ) { # Assigment case 'src': case 'href': case 'background': case 'poster': case 'action': case 'locationassignment': case 'innerHTML': # Check our post-char position for = as well (could be equality # test rather than assignment, i.e. == ) if ( ! isset($input[$postCharPos]) || $input[$postCharPos] == '=' ) { break; } # Find the end of this statement $endPos = analyzeAssign_js($input, $charPos); $valueLength = $endPos - $postCharPos; # Produce replacement command $replacement = sprintf('parse%s(%s)', $command=='innerHTML' ? 'HTML' : 'URL', substr($input, $postCharPos, $valueLength)); # Adjust total document length as appropriate $length += strlen($replacement); # Make the replacement $input = substr_replace($input, $replacement, $postCharPos, $valueLength); # Move offset up to new position $offset = $endPos + 10; # Go get next match continue 2; # Function calls - we don't know for certain if these are in fact members of the # appropriate objects (window/XMLHttpRequest for .open(), document for .write() and # .writeln) so we won't change anything. Main.js still overrides these functions but # does nothing with them by default. We add an extra parameter to tell our override # to kick in. case 'open': case 'write': case 'writeln': # Find the end position (the closing ")" for the function call) $endPos = analyze_js($input, $charPos); # Insert our additional argument just before that $glStr=',"gl"'; if (strspn($input, ";\n\r\+{}()[]", $charPos) >= ($endPos - $charPos)) { $glStr='"gl"'; } $input = substr_replace($input, $glStr, $endPos - 1, 0); # Adjust the document length $length += strlen($glStr); # And move the offset $offset = $endPos + strlen($glStr); # Get next match continue 2; # Eval() is a just as easy since we can just wrap the entire thing in parseJS(). case 'eval': # Ensure this is a call to eval(), not anotherfunctionendingineval() if ( isset($input[$commandPos-1]) && strpos('abcdefghijklmnopqrstuvwxyz123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_', $input[$commandPos-1]) !== false ) { break; } # Find the end position (the closing ")" for the function call) $endPos = analyze_js($input, $charPos); $valueLength = $endPos - $postCharPos; # Generate our replacement $replacement = sprintf('parseJS(%s)', substr($input, $postCharPos, $valueLength)); # Make the replacement $input = substr_replace($input, $replacement, $postCharPos, $valueLength); # Adjust the document length $length += 9; # And move the offset $offset = $endPos + 9; continue 2; # location.replace() is a tricky one. We have the position of the char # after . as $postCharPos and need to ensure we're calling replace(), # then parse the entire URL case 'locationreplace()': # Validate the match if ( ! preg_match('#\Greplace\s*\(#', $input, $tmp, 0, $postCharPos) ) { break; } # Move $postCharPos to inside the brackets of .replace() $postCharPos += strlen($tmp[0]); # Find the end position (the closing ")" for the function call) $endPos = analyze_js($input, $postCharPos); $valueLength = $endPos - $postCharPos; # Generate our replacement $replacement = sprintf('parseURL(%s)', substr($input, $postCharPos, $valueLength)); # Make the replacement $input = substr_replace($input, $replacement, $postCharPos, $valueLength); # Adjust the document length $length += 9; # And move the offset $offset = $endPos + 9; continue 2; } # Still here? A match didn't validate so adjust offset to just after # current position $offset = $commandPos + 1; } # Ignore document.domain $input = str_replace('document.domain', 'ignore', $input); # Return changed return $input; } } /***************************************************************** * HTML callbacks ******************************************************************/ # Remove and record the <base> href function html_stripBase($input) { global $base; $base = $input[2]; return ''; } # Proxy the location of a meta refresh function html_metaRefresh($input) { return str_replace($input[3], proxyURL($input[3]), $input[0]); } # Proxy URL in <param name="movie" value="URL"> function html_paramValue($input) { # Check for a name="movie" tag if ( stripos($input[0], 'movie') === false ) { return $input[0]; } return str_replace($input[2], proxyURL($input[2]), $input[0]); } # Process forms - the query string is used by the proxy script # and GET data needs to be encoded anyway. We convert all GET # forms to POST and then the proxy script will forward it properly. function html_form($input) { # Check for a given method if ( preg_match('#\bmethod\s*=\s*["\\\']?(get|post)["\\\']?#i', $input[1], $tmp) ) { # Not POST? if ( strtolower($tmp[1]) != 'post' ) { # Convert to post and flag as a conversion $input[1] = str_replace($tmp[0], 'method="post"', $input[1]); $converted = true; } } else { # Append a POST method (no method given and GET is default) $input[1] .= ' method="post"'; $converted = true; } # Prepare the extra input to insert $add = empty($converted) ? '' : '<input type="hidden" name="convertGET" value="1">'; # To do: javascript onsubmit event to immediately redirect to the appropriate # location using GET data, without an intermediate POST to the proxy script. # Proxy the form action $input[1] = preg_replace_callback('#\baction\s*=\s*([\\\'"])?((?(1)(?(?<=")[^"]{1,2048}|[^\\\']{1,2048})|[^\s"\\\'>]{1,2048}))(?(1)\\1|)#i', 'html_formAction', $input[1]); # What type of form is this? Due to register_globals support, PHP converts # a number of characters to _ in incoming variable names. To get around this, # we can use the raw post data from php://input but this is not available # for multipart forms. Instead we must encode the input names in these forms. if ( stripos($input[1], 'multipart/form-data') ) { $input[2] = preg_replace_callback('#name\s*=\s*([\\\'"])?((?(1)(?(?<=")[^"]{1,2048}|[^\\\']{1,2048})|[^\s"\\\'>]{1,2048}))(?(1)\\1|)#i', 'html_inputName', $input[2]); } # Return updated form return '<form' . $input[1] . '>' . $add . $input[2] . '</form>'; } # Proxy the action="URL" value in forms function html_formAction($input) { return 'action=' . $input[1] . proxyURL($input[2]) . $input[1]; } # Encode input names function html_inputName($input) { return 'name=' . $input[1] . inputEncode($input[2]) . $input[1]; } # Proxy URL values in attributes function html_attribute($input) { # Is this an iframe? $flag = stripos($input[0], 'iframe') === 1 ? 'frame' : ''; # URL occurred as value of an attribute and should have been htmlspecialchar()ed # We need to do the job of the browser and decode before proxying. return str_replace($input[3], htmlspecialchars(proxyURL(htmlspecialchars_decode($input[3]), $flag)), $input[0]); } # Flag frames in a frameset so only the first one shows the mini-form. # This could be done in the above callback but adds extra processing # when 99% of the time, it won't be needed. function html_flagFrames($input) { static $addFlag; # If it's the first frame, leave it but set the flag var if ( ! isset($addFlag) ) { $addFlag = true; return $input[0]; } # Add the frame flag $newURL = $input[2] . ( strpos($input[2], '?') ? '&amp;f=frame' : 'fframe/'); return str_replace($input[2], $newURL, $input[0]); } /***************************************************************** * CSS callbacks ******************************************************************/ # Proxy CSS url(LOCATION) function css_URL($input) { return 'url(' . proxyURL(trim($input[1])) . ')'; } # Proxy CSS @import "URL" function css_import($input) { return '@import "' . proxyURL($input[1]) . '"'; } # Proxy CSS src= function css_src($input) { return 'src=' . $input[1] . proxyURL($input[2]) . $input[1]; } # Callbacks for use with unique URLs and cached CSS # The <UNIQUE[]URL> acts as a marker for quick and easy processing later # Unique CSS url(LOCATION) function css_URL_unique($input) { return 'url(<UNIQUE[' . absoluteURL($input[1],'') . ']URL>)'; } # Unique CSS @import "URL" function css_import_unique($input) { return '@import "<UNIQUE[' . absoluteURL($input[1]) . ']URL>"'; } # Unique CSS src= function css_src_unique($input) { return 'src=' . $input[1] . '<UNIQUE[' . absoluteURL($input[2]) . ']URL>' . $input[1]; } /***************************************************************** * Helper functions ******************************************************************/ # Take a string, and check that the next non-whitespace char is the # passed in char (X). Return false if non-whitespace and non-X char is # found. Otherwise, return the position of X. # If $inverse is true, the next non-whitespace char must NOT be in $char # If $pastChar is true, ignore whitespace after finding X and return # the position of the last post-X whitespace char. function str_checknext($input, $char, $offset, $inverse = false, $pastChar = false) { for ( $i = $offset, $length = strlen($input); $i < $length; ++$i ) { # Examine char switch ( $input[$i] ) { # Ignore whitespace case ' ': case "\t": case "\r": case "\n": break; # Found the passed char case $char: # $inverse means we do NOT want this char if ( $inverse ) { return false; } # Move past this to the next non-whitespace? if ( $pastChar ) { ++$i; return $i + strspn($input, " \t\r\n", $i); } # Found desired char, no $pastChar, just return X offset return $i; # Found non-$char non-whitespace default: # This is the desired result if $inverse if ( $inverse ) { return $i; } # No $inverse, found a non-$char, return false return false; } } return false; } # Same as above but go backwards function str_checkprev($input, $char, $offset, $inverse = false) { for ( $i = $offset; $i > 0; --$i ) { # Examine char switch ( $input[$i] ) { # Ignore whitespace case ' ': case "\t": case "\r": case "\n": break; # Found char case $char: return $inverse ? false : $i; # Found non-$char char default: return $inverse ? $i : false; } } return $inverse; } # Analyze javascript and return offset positions. # Default is to find the end of the statement, indicated by: # (1) ; while not in string # (2) newline which, if not there, would create invalid syntax # (3) a closing bracket (object, language construct or function call) for which # no corresponding opening bracket was detected AFTER the passed offset # If (int) $argPos is true, we return an array of the start and end position # for the nth argument, where n = $argPos. The $start position must be just inside # the parenthesis of the function call we're interested in. function analyze_js($input, $start, $argPos = false) { # Add , if looking for an argument position if ( $argPos ) { $currentArg = 1; } # Loop through the input, stopping only at special chars for ( $i = $start, $length = strlen($input), $end = false, $openObjects = $openBrackets = $openArrays = 0; $end === false && $i < $length; ++$i ) { $char = $input[$i]; switch ( $char ) { # Starting string delimiters case '"': case "'": if ( $input[$i-1] == '\\' ) { break; } # Skip straight to end of string # Find the corresponding end delimiter and ensure it's not escaped while ( ( $i = strpos($input, $char, $i+1) ) && $input[$i-1] == '\\' ); # Check for false, in which case we assume the end is the end of the doc if ( $i === false ) { break 2; } break; # End of operation? case ';': $end = $i; break; # New lines case "\n": case "\r": # Newlines are OK if occuring within an open brackets, arrays or objects. if ( $openObjects || $openBrackets || $openArrays || $argPos ) { break; } # Newlines are also OK if followed by an opening function OR concatenation # e.g. someFunc\n(params) or someVar \n + anotherVar # Find next non-whitespace char position $tmp = $i + strspn($input, " \t\r\n", $i+1); # And compare to allowed chars if ( isset($input[$tmp+1]) && ( $input[$tmp+1] == '(' || $input[$tmp+1] == '+' ) ) { $i = $tmp; break; } # Newline not indicated as OK, set the end to here $end = $i; break; # Concatenation case '+': # Our interest in the + operator is it's use in allowing an expression # to span multiple lines. If we come across a +, move past all whitespace, # including newlines (which would otherwise indicate end of expression). $i += strspn($input, " \t\r\n", $i+1); break; # Opening chars (objects, parenthesis and arrays) case '{': ++$openObjects; break; case '(': ++$openBrackets; break; case '[': ++$openArrays; break; # Closing chars - is there a corresponding open char? # Yes = reduce stored count. No = end of statement. case '}': $openObjects ? --$openObjects : $end = $i; break; case ')': $openBrackets ? --$openBrackets : $end = $i; break; case ']': $openArrays ? --$openArrays : $end = $i; break; # Commas - tell us which argument it is case ',': # Ignore commas inside other functions or whatnot if ( $openObjects || $openBrackets || $openArrays ) { break; } # End now if ( $currentArg == $argPos ) { $end = $i; } # Increase the current argument number ++$currentArg; # If we're not after the first arg, start now? if ( $currentArg == $argPos ) { $start = $i+1; } break; } } # End not found? Use end of document if ( $end === false ) { $end = $length; } # Return array of start/end if ( $argPos ) { return array($start, $end); } # Return end return $end; } function analyzeAssign_js($input, $start) { # Loop through the input, stopping only at special chars for ( $i = $start, $length = strlen($input), $end = false, $openObjects = $openBrackets = $openArrays = 0; $end === false && $i < $length; ++$i ) { $char = $input[$i]; switch ( $char ) { # Starting string delimiters case '"': case "'": if ( $input[$i-1] == '\\' ) { break; } # Skip straight to end of string # Find the corresponding end delimiter and ensure it's not escaped while ( ( $i = strpos($input, $char, $i+1) ) && $input[$i-1] == '\\' ); # Check for false, in which case we assume the end is the end of the doc if ( $i === false ) { break 2; } break; # End of operation? case ';': $end = $i; break; # New lines case "\n": case "\r": # Newlines are OK if occuring within an open brackets, arrays or objects. if ( $openObjects || $openBrackets || $openArrays ) { break; } break; # Concatenation case '+': # Our interest in the + operator is it's use in allowing an expression # to span multiple lines. If we come across a +, move past all whitespace, # including newlines (which would otherwise indicate end of expression). $i += strspn($input, " \t\r\n", $i+1); break; # Opening chars (objects, parenthesis and arrays) case '{': ++$openObjects; break; case '(': ++$openBrackets; break; case '[': ++$openArrays; break; # Closing chars - is there a corresponding open char? # Yes = reduce stored count. No = end of statement. case '}': $openObjects ? --$openObjects : $end = $i; break; case ')': $openBrackets ? --$openBrackets : $end = $i; break; case ']': $openArrays ? --$openArrays : $end = $i; break; # Commas - tell us which argument it is case ',': # Ignore commas inside other functions or whatnot if ( $openObjects || $openBrackets || $openArrays ) { break; } # End now $end = $i; break; } } # End not found? Use end of document if ( $end === false ) { $end = $length; } # Return end return $end; } /***************************************************************** * Page encoding functions ******************************************************************/ # Encode page - splits into HTML/script sections and encodes HTML function encodePage($input) { # Look for script blocks # if ( preg_match_all('#<(?:script|style).*?</(?:script|style)>#is', $input, $scripts, PREG_OFFSET_CAPTURE) ) { # not working if ( preg_match_all('#<script.*?</script>#is', $input, $scripts, PREG_OFFSET_CAPTURE) ) { # Create starting offset - only start encoding after the <head> # as this seems to help browsers cope! $offset = preg_match('#<body[^>]*>(.)#is', $input, $tmp, PREG_OFFSET_CAPTURE) ? $tmp[1][1] : 0; $new = $offset ? substr($input, 0, $offset) : ''; # Go through all the matches foreach ( $scripts[0] as $id => $match ) { # Determine position of the preceeding non-script block $end = $match[1] ? $match[1]-1 : 0; $start = $offset; $length = $end - $start; # Add encoded block to page if there is one if ($length && $length>0) { $new .= "\n\n\n<!--start encode block-->\n"; $new .= encodeBlock(substr($input, $start, $length)); $new .= "\n<!--end encode block-->\n\n\n"; } # Add unencoded script to page $new .= "\n\n\n<!--start unencoded block-->\n"; $new .= $match[0]; $new .= "\n<!--end unencoded block-->\n\n\n"; # Move offset up $offset = $match[1] + strlen($match[0]); } # Add final block if ( $remainder = substr($input, $offset) ) { $new .= encodeBlock($remainder); } # Update input with new $input = $new; } else { # No scripts is easy - just encode the lot $input = encodeBlock($input); } # Return the encoded page return $input; } # Encode block - applies the actual encoding # note - intended to obfustate URLs and HTML source code. Does not provide security. Use SSL for actual security. function encodeBlock($input) { global $charset; $new=''; if (isset($charset)) { $charset=strtolower($charset); if (function_exists('mb_convert_encoding')) { $input=mb_convert_encoding($input, 'HTML-ENTITIES', $charset); } } # Return javascript decoder return '<script type="text/javascript">document.write(arcfour(ginf.enc.u,base64_decode(\'' . arcfour('encrypt',$GLOBALS['unique_salt'],$input) . '\')));</script>'; }
selecterskyphp/glype_chs
includes/parser.php
PHP
mit
34,604
namespace NorthwindWindowsStore.DAL.Model.Interface { public interface ITerritory { } }
krzysztofkolek/NorthwindWindowsStore
NorthwindWindowsStoreService/NorthwindWindowsStore.DAL.Model/Interface/ITerritory.cs
C#
mit
99
/* Project : 4-9 Math Tutor Author : Mohammad Al-Husseini Description : Displays two random numbers to be added then waits for the user to solve it. The user can type their result in and the program tells them if they are correct. Knowns : 2x Random Numbers - Int Inputs : Answer - Int Display : 2x Radnom Numbers - Int Answer - Int */ /////////////////////////////////////////////////////////////////////////////////////////////////// #include <iostream> // cout and cin objects for command line output/input #include <cstdlib> // random numbers #include <ctime> // time to seed the random numbers using namespace std; int main() { // Create variables to hold the random numbers int num1, num2; // Variable for User Input int result; // Seed the random number unsigned seed = time(0); // 0 indicates current time at run-time srand(seed); // Generate the random numbers num1 = rand(); num2 = rand(); // Display the numbers cout << " " << num1 << endl; cout << "+ " << num2 << endl; cout << "__________" << endl; cout << " "; // Wait for user input cin >> result; // Determine if answer was correct if (result == num1 + num2) cout << "Congratulations! That is correct, good job!"; else cout << " " << num1 + num2; return 0; }
menarus/C-Course
Solutions/Ch4/4-09 Math Tutor.cpp
C++
mit
1,339
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- try: from ._models_py3 import AlertRuleResource from ._models_py3 import AlertRuleResourceCollection from ._models_py3 import AlertRuleResourcePatch from ._models_py3 import AutoscaleNotification from ._models_py3 import AutoscaleProfile from ._models_py3 import AutoscaleSettingResource from ._models_py3 import AutoscaleSettingResourceCollection from ._models_py3 import AutoscaleSettingResourcePatch from ._models_py3 import EmailNotification from ._models_py3 import ErrorResponse from ._models_py3 import EventCategoryCollection from ._models_py3 import EventData from ._models_py3 import EventDataCollection from ._models_py3 import HttpRequestInfo from ._models_py3 import LocalizableString from ._models_py3 import LocationThresholdRuleCondition from ._models_py3 import ManagementEventAggregationCondition from ._models_py3 import ManagementEventRuleCondition from ._models_py3 import MetricTrigger from ._models_py3 import Operation from ._models_py3 import OperationDisplay from ._models_py3 import OperationListResult from ._models_py3 import Recurrence from ._models_py3 import RecurrentSchedule from ._models_py3 import Resource from ._models_py3 import RuleAction from ._models_py3 import RuleCondition from ._models_py3 import RuleDataSource from ._models_py3 import RuleEmailAction from ._models_py3 import RuleManagementEventClaimsDataSource from ._models_py3 import RuleManagementEventDataSource from ._models_py3 import RuleMetricDataSource from ._models_py3 import RuleWebhookAction from ._models_py3 import ScaleAction from ._models_py3 import ScaleCapacity from ._models_py3 import ScaleRule from ._models_py3 import ScaleRuleMetricDimension from ._models_py3 import SenderAuthorization from ._models_py3 import ThresholdRuleCondition from ._models_py3 import TimeWindow from ._models_py3 import WebhookNotification except (SyntaxError, ImportError): from ._models import AlertRuleResource # type: ignore from ._models import AlertRuleResourceCollection # type: ignore from ._models import AlertRuleResourcePatch # type: ignore from ._models import AutoscaleNotification # type: ignore from ._models import AutoscaleProfile # type: ignore from ._models import AutoscaleSettingResource # type: ignore from ._models import AutoscaleSettingResourceCollection # type: ignore from ._models import AutoscaleSettingResourcePatch # type: ignore from ._models import EmailNotification # type: ignore from ._models import ErrorResponse # type: ignore from ._models import EventCategoryCollection # type: ignore from ._models import EventData # type: ignore from ._models import EventDataCollection # type: ignore from ._models import HttpRequestInfo # type: ignore from ._models import LocalizableString # type: ignore from ._models import LocationThresholdRuleCondition # type: ignore from ._models import ManagementEventAggregationCondition # type: ignore from ._models import ManagementEventRuleCondition # type: ignore from ._models import MetricTrigger # type: ignore from ._models import Operation # type: ignore from ._models import OperationDisplay # type: ignore from ._models import OperationListResult # type: ignore from ._models import Recurrence # type: ignore from ._models import RecurrentSchedule # type: ignore from ._models import Resource # type: ignore from ._models import RuleAction # type: ignore from ._models import RuleCondition # type: ignore from ._models import RuleDataSource # type: ignore from ._models import RuleEmailAction # type: ignore from ._models import RuleManagementEventClaimsDataSource # type: ignore from ._models import RuleManagementEventDataSource # type: ignore from ._models import RuleMetricDataSource # type: ignore from ._models import RuleWebhookAction # type: ignore from ._models import ScaleAction # type: ignore from ._models import ScaleCapacity # type: ignore from ._models import ScaleRule # type: ignore from ._models import ScaleRuleMetricDimension # type: ignore from ._models import SenderAuthorization # type: ignore from ._models import ThresholdRuleCondition # type: ignore from ._models import TimeWindow # type: ignore from ._models import WebhookNotification # type: ignore from ._monitor_management_client_enums import ( ComparisonOperationType, ConditionOperator, EventLevel, MetricStatisticType, RecurrenceFrequency, ScaleDirection, ScaleRuleMetricDimensionOperationType, ScaleType, TimeAggregationOperator, TimeAggregationType, ) __all__ = [ 'AlertRuleResource', 'AlertRuleResourceCollection', 'AlertRuleResourcePatch', 'AutoscaleNotification', 'AutoscaleProfile', 'AutoscaleSettingResource', 'AutoscaleSettingResourceCollection', 'AutoscaleSettingResourcePatch', 'EmailNotification', 'ErrorResponse', 'EventCategoryCollection', 'EventData', 'EventDataCollection', 'HttpRequestInfo', 'LocalizableString', 'LocationThresholdRuleCondition', 'ManagementEventAggregationCondition', 'ManagementEventRuleCondition', 'MetricTrigger', 'Operation', 'OperationDisplay', 'OperationListResult', 'Recurrence', 'RecurrentSchedule', 'Resource', 'RuleAction', 'RuleCondition', 'RuleDataSource', 'RuleEmailAction', 'RuleManagementEventClaimsDataSource', 'RuleManagementEventDataSource', 'RuleMetricDataSource', 'RuleWebhookAction', 'ScaleAction', 'ScaleCapacity', 'ScaleRule', 'ScaleRuleMetricDimension', 'SenderAuthorization', 'ThresholdRuleCondition', 'TimeWindow', 'WebhookNotification', 'ComparisonOperationType', 'ConditionOperator', 'EventLevel', 'MetricStatisticType', 'RecurrenceFrequency', 'ScaleDirection', 'ScaleRuleMetricDimensionOperationType', 'ScaleType', 'TimeAggregationOperator', 'TimeAggregationType', ]
Azure/azure-sdk-for-python
sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/models/__init__.py
Python
mit
6,678
<?php require_once __DIR__ . '/../../lib/DoublyLinkedListNode.php'; class SumListNoConvertReversed { public static function sum(Node $n1, Node $n2) { $head = $tail = null; $n1Length = self::getLinkedListSize($n1); $n2Length = self::getLinkedListSize($n2); $maxLength = max($n1Length, $n2Length); $n1Offset = $maxLength - $n1Length; $n2Offset = $maxLength - $n2Length; while ($n1 !== null || $n2 !== null) { $sum = 0; if ($n1Offset > 0) { $n1Offset--; } else { $sum += $n1->getData(); $n1 = $n1->getNext(); } if ($n2Offset > 0) { $n2Offset--; } else { $sum += $n2->getData(); $n2 = $n2->getNext(); } self::addDigitToLinkedList($head, $tail, $sum); } return $head; } public static function addDigitToLinkedList( DoublyLinkedListNode &$head = null, DoublyLinkedListNode &$tail = null, $number) { $digit = $number % 10; if ($number >= 10) { $carry = ($number - $digit) / 10; if ($tail !== null) { $previousDigit = $tail->getData(); $tail = $tail->getPrevious(); if ($tail !== null) { $tail->setNext(null); } else { $head = null; } } else { $previousDigit = 0; } self::addDigitToLinkedList($head, $tail, $previousDigit + $carry); } $node = new DoublyLinkedListNode($digit); if ($tail !== null) { $tail->setNext($node); $node->setPrevious($tail); $tail = $node; } else { $head = $tail = $node; } } public static function getLinkedListSize(Node $node) { $size = 0; while ($node !== null) { $size++; $node = $node->getNext(); } return $size; } }
Kiandr/CrackingCodingInterview
php/src/chapter02/question2.5/SumListNoConvertReversed.php
PHP
mit
2,104
#!/usr/bin/env node import {cd, exec, rm, set} from 'shelljs'; import * as fs from 'fs'; // Fail on first error set('-e'); // Install Angular packages that are built locally from HEAD. // This also gets around the bug whereby yarn caches local `file://` urls. // See https://github.com/yarnpkg/yarn/issues/2165 // The below packages are all required in a default CLI project. const ngPackages = [ 'animations', 'core', 'common', 'compiler', 'forms', 'platform-browser', 'platform-browser-dynamic', 'router', 'compiler-cli', 'language-service', ]; // Keep typescript, tslib, and @types/node versions in sync with the ones used in this repo const nodePackages = [ '@types/node', 'tslib', 'typescript', ]; // Under Bazel integration tests are sand-boxed and cannot reference // reference `../../dist/*` packages and should not do so as these are not // inputs to the test. The npm_integeration_test rule instead provides a manifest // file that contains all of the npm package mappings available to the test. const bazelMappings: { [key: string]: string } = fs.existsSync('NPM_PACKAGE_MANIFEST.json') ? require('./NPM_PACKAGE_MANIFEST.json') : {}; const packages: { [key: string]: string } = {}; for (let p of ngPackages) { const n = `@angular/${p}`; packages[n] = `file:${bazelMappings[n]}` || `file:${__dirname}/../../dist/packages-dist/${p}`; } for (let p of nodePackages) { packages[p] = `file:${bazelMappings[p]}` || `file:${__dirname}/../../node_modules/${p}`; } // Clean up previously run test cd(__dirname); rm('-rf', `demo`); // Set up demo project exec('ng version'); exec('ng new demo --skip-git --skip-install --style=css --no-interactive'); cd('demo'); // Use a local yarn cache folder so we don't access the global yarn cache exec('mkdir .yarn_local_cache'); // Install Angular packages that are built locally from HEAD and npm packages // from root node modules that are to be kept in sync const packageList = Object.keys(packages).map(p => `${p}@${packages[p]}`).join(' '); exec(`yarn add --ignore-scripts --silent ${packageList} --cache-folder ./.yarn_local_cache`); // Add @angular/elements const schematicPath = bazelMappings ? `${bazelMappings['@angular/elements']}` : `${__dirname}/../../dist/packages-dist/elements`; exec(`ng add "${schematicPath}" --skip-confirmation`); // Test that build is successful after adding elements exec('ng build --no-source-map --configuration=development');
mgechev/angular
integration/ng_elements_schematics/test.ts
TypeScript
mit
2,456
<?php class Pilotes extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('Pilote_model'); } public function index() { $data['title'] = 'Gestion des pilotes'; $this->load->view('header', $data); // Critères sur les pilotes à afficher $champs = $this->Pilote_model->getFields(); $data['champsLike'] = null; $data['champsEqual'] = null; foreach ($champs as $champ) { if (isset($_GET[$champ])) { if (($champ == 'id') OR ($_GET[$champ] == 'true' OR $_GET[$champ] == 'false') OR strtotime(str_replace('/', '-', $_GET[$champ]))) { $data['champsEqual'][$champ] = $_GET[$champ]; } else { $data['champsLike'][$champ] = $_GET[$champ]; } $data['old_data'][$champ] = $_GET[$champ]; } } $this->load->view('formRecherchePilote', $data); $this->display_pilotes($data); $this->load->view('footer', $data); } public function display_pilotes($data) { $data['title'] = 'Pilotes'; // Critère de tri if (isset($_GET['o'])) { $o = $_GET['o']; } else { $o = 'id'; } // Récupération des données $data['array_data'] = $this->Pilote_model->get($o, $data['champsEqual'], $data['champsLike'])->result_array(); $data['fields_metadata'] = $this->Pilote_model->getFieldsMetaData(); $data['array_headings'] = $this->perso->get_headings('pilote'); $data['miscInfos'] = $this->Pilote_model->getMisc(); $this->perso->set_data_for_display('pilote', $data['array_data']); // Traitement des lignes /*foreach($data['array_data'] as $num_row => $row) { }*/ $data['btnNouveau'] = true; $data['btnModif'] = true; $data['btnInfos'] = true; $data['object'] = 'pilote'; $data['miscInfos'] = $this->Pilote_model->getMisc(); $this->load->view('table', $data); } public function ajouter() { $data['title'] = 'Ajouter un pilote'; if (isset($_POST['nom'])) { if (!isset($_POST['qualification_biplace'])) { $_POST['qualification_biplace'] = false; } $_POST['nom'] = strtolower($_POST['nom']); $_POST['prenom'] = strtolower($_POST['prenom']); try { $this->Pilote_model->add($_POST); redirect('/pilotes', 'location', 301); } catch (Exception $e) { $data['error_message'] = $e.getMessage(); redirect('/pilotes', 'location', 400); } } else { $this->load->view('header', $data); $data['function'] = 'ajouter'; $this->load->view('formPilote', $data); $this->load->view('footer', $data); } } public function modifier($id) { $data['title'] = 'Modifier un pilote'; if (isset($_POST['nom'])) { if (!isset($_POST['qualification_biplace'])) { $_POST['qualification_biplace'] = false; } $_POST['nom'] = strtolower($_POST['nom']); $_POST['prenom'] = strtolower($_POST['prenom']); try { $this->Pilote_model->update($id, $_POST); redirect('/pilotes', 'location', 301); } catch (Exception $e) { $data['error_message'] = $e.getMessage(); redirect('/pilotes', 'location', 400); } } else { $this->load->view('header', $data); $data['function'] = 'modifier/'.$id; $data['old_data'] = $this->Pilote_model->get('id', array('id' => $id), null)->result_array()[0]; $this->load->view('formPilote', $data); $this->load->view('footer', $data); } } }
Sayomul/GestionParapente
application/controllers/Pilotes.php
PHP
mit
3,292
<?php namespace SEC\SolicitudesBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ProcesoType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('tipo', 'entity', array( 'class' => 'SECSolicitudesBundle:Tipo', 'property' => 'descripcion', 'empty_value' => 'Seleccione...' )) ->add('fechaRecSDA', 'date', array( 'label' => 'Fecha Recepción SDA : ', 'widget' => 'single_text', )) ->add('fechaRecSER', 'date', array( 'label' => 'Fecha Recepción SER : ', 'widget' => 'single_text', )) ->add('titulo') ->add('resumen', 'textarea', array( 'label' => 'Resumen' )) ->add('infoadicional') ->add('noradicado') ->add('entecontrol', 'entity', array( 'class' => 'SECSolicitudesBundle:EnteControl', 'property' => 'nombre', 'empty_value' => 'Seleccione...' )) ->add('diasrespuesta') ->add('fechamaxrespuesta', 'date', array( 'label' => 'Fecha Maxima : ', 'widget' => 'single_text', 'format' => 'dd/MM/yyyy', 'read_only' => true )) ->add('alerta1', 'date', array( 'label' => 'Alerta 1 : ', 'widget' => 'single_text', 'format' => 'dd/MM/yyyy', 'read_only' => true )) ->add('alerta2', 'date', array( 'label' => 'Alerta 2 : ', 'widget' => 'single_text', 'format' => 'dd/MM/yyyy', 'read_only' => true )) ->add('asignaciones', 'collection', array( 'type' => new AsignacionType(), 'label' => 'Responsables', 'by_reference' => false, //'prototype_data' => new Asignacion(), 'allow_delete' => true, 'allow_add' => true, )) ; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'SEC\SolicitudesBundle\Entity\Proceso' )); } public function getName() { return 'proceso_asignaciones'; } } ?>
miguelplazasr/sec
src/SEC/SolicitudesBundle/Form/ProcesoType.php
PHP
mit
2,796
require 'rails_helper' describe UserImportResult do #pending "add some examples to (or delete) #{__FILE__}" end # == Schema Information # # Table name: user_import_results # # id :bigint not null, primary key # user_import_file_id :bigint # user_id :bigint # body :text # created_at :datetime not null # updated_at :datetime not null # error_message :text #
next-l/enju_library
spec/models/user_import_result_spec.rb
Ruby
mit
464
package com.example.alexeyglushkov.uimodulesandclasses.activitymodule.presenter; import com.example.alexeyglushkov.uimodulesandclasses.activitymodule.view.ActivityModuleItemView; import com.example.alexeyglushkov.uimodulesandclasses.activitymodule.view.ActivityModuleView; /** * Created by alexeyglushkov on 02.04.17. */ public interface ActivityModuleItem { ActivityModuleItemView getActivityModuleItemView(); }
soniccat/android-taskmanager
ui/src/main/java/com/example/alexeyglushkov/uimodulesandclasses/activitymodule/presenter/ActivityModuleItem.java
Java
mit
422
'use strict'; // helper to start and stop the redis process. var config = require('./config'); var fs = require('fs'); var path = require('path'); var spawn = require('win-spawn'); var spawnFailed = false; var tcpPortUsed = require('tcp-port-used'); // wait for redis to be listening in // all three modes (ipv4, ipv6, socket). function waitForRedis (available, cb) { if (process.platform === 'win32') return cb(); var ipV4 = false; var id = setInterval(function () { tcpPortUsed.check(config.PORT, '127.0.0.1').then(function (_ipV4) { ipV4 = _ipV4; return tcpPortUsed.check(config.PORT, '::1'); }).then(function (ipV6) { if (ipV6 === available && ipV4 === available && fs.existsSync('/tmp/redis.sock') === available) { clearInterval(id); return cb(); } }); }, 100); } module.exports = { start: function (done, conf) { // spawn redis with our testing configuration. var confFile = conf || path.resolve(__dirname, '../conf/redis.conf'); var rp = spawn("redis-server", [confFile], {}); // capture a failure booting redis, and give // the user running the test some directions. rp.once("exit", function (code) { if (code !== 0) spawnFailed = true; }); // wait for redis to become available, by // checking the port we bind on. waitForRedis(true, function () { // return an object that can be used in // an after() block to shutdown redis. return done(null, { spawnFailed: function () { return spawnFailed; }, stop: function (done) { if (spawnFailed) return done(); rp.once("exit", function (code) { var error = null; if (code !== null && code !== 0) { error = Error('Redis shutdown failed with code ' + code); } waitForRedis(false, function () { return done(error); }); }); rp.kill("SIGTERM"); } }); }); } };
MailOnline/node_redis
test/lib/redis-process.js
JavaScript
mit
2,328
/*global piranha, tinymce */ // // Create a new inline editor // piranha.editor.addInline = function (id, toolbarId) { tinymce.init({ selector: "#" + id, browser_spellcheck: true, fixed_toolbar_container: "#" + toolbarId, menubar: false, branding: false, statusbar: false, inline: true, convert_urls: false, plugins: [ piranha.editorconfig.plugins ], width: "100%", autoresize_min_height: 0, toolbar: piranha.editorconfig.toolbar, extended_valid_elements: piranha.editorconfig.extended_valid_elements, block_formats: piranha.editorconfig.block_formats, style_formats: piranha.editorconfig.style_formats, file_picker_callback: function(callback, value, meta) { // Provide file and text for the link dialog if (meta.filetype == 'file') { piranha.mediapicker.openCurrentFolder(function (data) { callback(data.publicUrl, { text: data.filename }); }, null); } // Provide image and alt text for the image dialog if (meta.filetype == 'image') { piranha.mediapicker.openCurrentFolder(function (data) { callback(data.publicUrl, { alt: "" }); }, "image"); } } }); $("#" + id).parent().append("<a class='tiny-brand' href='https://www.tiny.cloud' target='tiny'>Powered by Tiny</a>"); }; // // Remove the TinyMCE instance with the given id. // piranha.editor.remove = function (id) { tinymce.remove(tinymce.get(id)); $("#" + id).parent().find('.tiny-brand').remove(); };
PiranhaCMS/piranha.core
core/Piranha.Manager.TinyMCE/assets/piranha.editor.js
JavaScript
mit
1,717
'use strict'; import path from 'path'; import autoprefixer from 'autoprefixer-core'; import gulpif from 'gulp-if'; export default function(gulp, plugins, args, config, taskTarget, browserSync) { let dirs = config.directories; let entries = config.entries; let dest = path.join(taskTarget, dirs.styles.replace(/^_/, '')); // Sass compilation gulp.task('sass', () => { gulp.src(path.join(dirs.source, dirs.styles, entries.css)) .pipe(plugins.plumber()) .pipe(plugins.sourcemaps.init()) .pipe(plugins.sass({ outputStyle: 'expanded', precision: 10, includePaths: [ path.join(dirs.source, dirs.styles), path.join(dirs.source, dirs.modules) ] }).on('error', plugins.sass.logError)) .pipe(plugins.postcss([autoprefixer({browsers: ['last 2 version', '> 5%', 'safari 5', 'ios 6', 'android 4']})])) .pipe(plugins.rename(function(path) { // Remove 'source' directory as well as prefixed folder underscores // Ex: 'src/_styles' --> '/styles' path.dirname = path.dirname.replace(dirs.source, '').replace('_', ''); })) .pipe(gulpif(args.production, plugins.minifyCss({rebase: false}))) .pipe(plugins.sourcemaps.write('./')) .pipe(gulp.dest(dest)) .pipe(browserSync.stream({match: '**/*.css'})); }); }
jacekpolak/generator-yeogurt
app/templates/gulp/es6/sass.js
JavaScript
mit
1,348
@extends('adminlte::page') @section('title', 'Redirects') @section('content_header') <h1>Redirects</h1> @stop @section('content') <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-body"> @include('admin.redirects._form', [ 'route' => ['admin.redirects.store'] ]) </div> </div> </div> </div> @stop
patrykwozinski/shared-flat
resources/views/admin/redirects/create.blade.php
PHP
mit
474
namespace EngineOverflow.Web.ViewModels.Manage { using System.ComponentModel.DataAnnotations; public class AddPhoneNumberViewModel { [Required] [Phone] [Display(Name = "Phone Number")] public string Number { get; set; } } }
delyan-nikolov-1992/EngineOverflow
Source/Web/EngineOverflow.Web/ViewModels/Manage/AddPhoneNumberViewModel.cs
C#
mit
276
var Articles = require("../articles"); var summarize = require("../summarize"); var translate = require("../translate"); var pipeline = require("../pipeline"); var veoozInterface = require("./veoozInterface.js"); module.exports = function (socketEnsureLoggedIn, socket) { function handleError(err) { return Promise.reject(err); } function throwError(err) { console.log(socket.id, "Throwing error:", err); socket.emit('new error', err); } function ensureArticleFactory(source) { if (!socket.articleFactory) { socket.articleFactory = new Articles(socket.id, source); } } socket.on('get article list', function (options, callback) { ensureArticleFactory(socket.handshake.query.articleSource); socket.articleFactory.fetchList(options).then(callback, throwError); }); socket.on('access article', function (articleId, langs, options, callback) { ensureArticleFactory(socket.handshake.query.articleSource); var authPromise; if (options.requireAuth) { authPromise = socketEnsureLoggedIn(socket); } else { authPromise = Promise.resolve(); } authPromise .then(function () { return socket.articleFactory.fetchOne(articleId); }, handleError) .then(function (article) { return pipeline.accessArticle(article, langs, options); }, handleError) .then(function (articles) { if (options.initializeLog) { var loggerPromises = []; articles.forEach(function (article) { loggerPromises.push( socket.articleFactory.initializeLogger(article) .then(function (loggerId) { if (!("_meta" in article)) { article._meta = {}; } article._meta.loggerId = loggerId; }, handleError) ); }); return Promise.all(loggerPromises).then(function () { return articles; }, handleError); } else { return articles; } }) .then(callback, handleError) .catch(throwError); }); socket.on('insert logs', function (loggerId, logs, callback) { ensureArticleFactory(socket.handshake.query.articleSource); // Client should ensure that no parallel request for the same loggerId are made. socketEnsureLoggedIn(socket) .then(function () { socket.articleFactory.insertLogs(loggerId, logs) .then(callback, function (err) { console.log(socket.id, "Ignoring error:", err); }); }, function (err) { console.log(socket.id, "Ignoring error:", err); }); }); socket.on('publish article', function (article, callback) { ensureArticleFactory(socket.handshake.query.articleSource); socketEnsureLoggedIn(socket) .then(function (user) { if (!article._meta) { article._meta = {}; } article._meta.username = user.username; return article; }, handleError) .then(function (article) { socket.articleFactory.storeEdited(article) .then(callback, throwError); if (article._meta.rawId) { console.log(socket.id, "Pushing accessible article to Veooz:", article.id); return veoozInterface.pushArticle(article).catch(function (err) { console.log(socket.id, "Error pushing article:", err); }); } }, throwError); }); socket.on('translate text', function (text, from, to, method, callback) { translate.translateText(text, from, to, method) .then(callback, throwError); }); };
nisargjhaveri/news-access
server/handleSocket.js
JavaScript
mit
4,291
module Fog module OpenStack class Compute class Real def list_os_interfaces(server_id) request( :expects => [200, 203], :method => 'GET', :path => "servers/#{server_id}/os-interface" ) end end class Mock def list_os_interfaces(server_id) Excon::Response.new( :body => {'interfaceAttachments' => data[:os_interfaces]}, :status => 200 ) end end end end end
fog/fog-openstack
lib/fog/openstack/compute/requests/list_os_interfaces.rb
Ruby
mit
530
'use strict'; var _ = require('lodash'); var moment = require('moment'); var util = require('util'); var articleService = require('../../services/article'); var listOrSingle = require('./lib/listOrSingle'); function parse (params) { var formats = ['YYYY', 'MM', 'DD']; var parts = _.values(params); var len = parts.length; var input = parts.join('-'); var inputFormat = formats.slice(0, len).join('-'); var unit; var textual; if (params.day) { textual = 'MMMM Do, YYYY'; unit = 'day'; } else if (params.month) { textual = 'MMMM, YYYY'; unit = 'month'; } else { textual = 'YYYY'; unit = 'year'; } var when = moment(input, inputFormat); var text = when.format(textual); return { start: when.startOf(unit).toDate(), end: when.clone().endOf(unit).toDate(), text: text }; } function slug (params) { var fmt = 'YYYY/MM/DD'; var keys = Object.keys(params).length; var parts = [params.year, params.month, params.day].splice(0, keys.length); return moment(parts.join('/'), fmt).format(fmt); } module.exports = function (req, res, next) { var parsed = parse(req.params); var handle = listOrSingle(res, { skip: false }, next); var titleFormat = 'Articles published on %s'; var title = util.format(titleFormat, parsed.text); res.viewModel = { model: { title: title, meta: { canonical: '/articles/' + slug(req.params), description: 'This search results page contains all of the ' + title.toLowerCase() } } }; var query = { status: 'published', publication: { $gte: parsed.start, $lt: parsed.end } }; articleService.find(query, handle); };
cshum/ponyfoo
controllers/articles/dated.js
JavaScript
mit
1,693
using Android.App; using Android.Content; using Android.Content.PM; using Android.OS; using Android.Support.V7.App; using System; using System.IO; namespace Teaching.Skills.Droid.Activities { [Activity(Label = "@string/app_title", Icon = "@drawable/icon", Theme = "@style/App.Default", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Portrait)] public class BaseActivity : AppCompatActivity { public BaseActivity() { } protected override void OnPause() { base.OnPause(); MainApplication.LastUseTime = DateTime.UtcNow; } protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); if (toolbar != null) { SetSupportActionBar(toolbar); SupportActionBar.Title = this.Title; SupportActionBar.SetDisplayHomeAsUpEnabled(true); SupportActionBar.SetHomeButtonEnabled(true); } } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults) { Permissions.Verify(grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } public static Intent CreateIntent<T>(object model = null) where T : Activity { var intent = new Intent(Application.Context, typeof(T)); if (model != null) { var serializer = new System.Xml.Serialization.XmlSerializer(model.GetType()); var modelStream = new MemoryStream(); serializer.Serialize(modelStream, model); intent.PutExtra("Model", modelStream.ToArray()); } return intent; } public override bool OnOptionsItemSelected(Android.Views.IMenuItem item) { if (item.ItemId == Android.Resource.Id.Home) Finish(); return base.OnOptionsItemSelected(item); } } }
ennerperez/teaching-skills
teaching.skills.droid/Activities/BaseActivity.cs
C#
mit
2,260
using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; namespace CodeTiger.CodeAnalysis.Analyzers.Readability { /// <summary> /// Analyzes general readability issues. /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] public class GeneralReadabilityAnalyzer : DiagnosticAnalyzer { internal static readonly DiagnosticDescriptor EmptyStatementsShouldNotBeUsedDescriptor = new DiagnosticDescriptor("CT3100", "Empty statements should not be used.", "Empty statements should not be used.", "CodeTiger.Readability", DiagnosticSeverity.Warning, true); /// <summary> /// Gets a set of descriptors for the diagnostics that this analyzer is capable of producing. /// </summary> public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(EmptyStatementsShouldNotBeUsedDescriptor); /// <summary> /// Registers actions in an analysis context. /// </summary> /// <param name="context">The context to register actions in.</param> /// <remarks>This method should only be called once, at the start of a session.</remarks> public override void Initialize(AnalysisContext context) { Guard.ArgumentIsNotNull(nameof(context), context); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.EnableConcurrentExecution(); context.RegisterSyntaxNodeAction(AnalyzeEmptyStatements, SyntaxKind.EmptyStatement); } private static void AnalyzeEmptyStatements(SyntaxNodeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(EmptyStatementsShouldNotBeUsedDescriptor, context.Node.GetLocation())); } } }
csdahlberg/CodeTiger.CodeAnalysis
CodeTiger.CodeAnalysis/Analyzers/Readability/GeneralReadabilityAnalyzer.cs
C#
mit
1,931
#include "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "walletmodel.h" #include <QMessageBox> #include <QPushButton> #include <QKeyEvent> AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::AskPassphraseDialog), mode(mode), model(0), fCapsLock(false) { ui->setupUi(this); ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE); // Setup Caps Lock detection. ui->passEdit1->installEventFilter(this); ui->passEdit2->installEventFilter(this); ui->passEdit3->installEventFilter(this); ui->capsLabel->clear(); //Setup Keyboard keyboard = new VirtualKeyboard(this); ui->keyboardLayout->addWidget(keyboard); switch(mode) { case Encrypt: // Ask passphrase x2 ui->passLabel1->hide(); ui->passEdit1->hide(); ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.")); setWindowTitle(tr("Encrypt wallet")); break; case Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; case Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; case ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->keyboardToggle, SIGNAL(clicked()), keyboard, SLOT(toggleKeyboard())); } AskPassphraseDialog::~AskPassphraseDialog() { // Attempt to overwrite text so that they do not linger around in memory ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size())); ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size())); ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size())); delete ui; } void AskPassphraseDialog::setModel(WalletModel *model) { this->model = model; } void AskPassphraseDialog::accept() { SecureString oldpass, newpass1, newpass2; if(!model) return; oldpass.reserve(MAX_PASSPHRASE_SIZE); newpass1.reserve(MAX_PASSPHRASE_SIZE); newpass2.reserve(MAX_PASSPHRASE_SIZE); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make this input mlock()'d to begin with. oldpass.assign(ui->passEdit1->text().toStdString().c_str()); newpass1.assign(ui->passEdit2->text().toStdString().c_str()); newpass2.assign(ui->passEdit3->text().toStdString().c_str()); switch(mode) { case Encrypt: { if(newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; } QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"), tr("WARNING: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR RCoinUSAS</b>!\nAre you sure you wish to encrypt your wallet?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval == QMessageBox::Yes) { if(newpass1 == newpass2) { if(model->setWalletEncrypted(true, newpass1)) { QMessageBox::warning(this, tr("Wallet encrypted"), tr("RCoinUSA will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your RCoinUSAs from being stolen by malware infecting your computer.")); QApplication::quit(); } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted.")); } QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } } else { QDialog::reject(); // Cancelled } } break; case Unlock: if(!model->setWalletLocked(false, oldpass)) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case Decrypt: if(!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case ChangePass: if(newpass1 == newpass2) { if(model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), tr("Wallet passphrase was succesfully changed.")); QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } break; } } void AskPassphraseDialog::textChanged() { // Validate input, set Ok button to enabled when accepable bool acceptable = false; switch(mode) { case Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; case Unlock: // Old passphrase x1 case Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; case ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable); } bool AskPassphraseDialog::event(QEvent *event) { // Detect Caps Lock key press. if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if (ke->key() == Qt::Key_CapsLock) { fCapsLock = !fCapsLock; } if (fCapsLock) { ui->capsLabel->setText(tr("Warning: The Caps Lock key is on.")); } else { ui->capsLabel->clear(); } } return QWidget::event(event); } bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event) { /* Detect Caps Lock. * There is no good OS-independent way to check a key state in Qt, but we * can detect Caps Lock by checking for the following condition: * Shift key is down and the result is a lower case character, or * Shift key is not down and the result is an upper case character. */ if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); QString str = ke->text(); if (str.length() != 0) { const QChar *psz = str.unicode(); bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0; if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) { fCapsLock = true; ui->capsLabel->setText(tr("Warning: The Caps Lock key is on.")); } else if (psz->isLetter()) { fCapsLock = false; ui->capsLabel->clear(); } } } else if (event->type() == QEvent::FocusIn) { if (object->inherits("QLineEdit")) { keyboard->setInput(object); } } return false; }
rcoinwallet/RCoinUSA
src/qt/askpassphrasedialog.cpp
C++
mit
9,309
namespace Mirage.Urbanization.ZoneStatisticsQuerying { public interface IQueryCrimeResult : IQueryCellValueResult { } }
Miragecoder/Urbanization
src/Mirage.Urbanization/ZoneStatisticsQuerying/IQueryCrimeResult.cs
C#
mit
123
# frozen_string_literal: true require 'spec_helper' require 'vk/api/ads/targ_suggestions_regions' RSpec.describe Vk::API::Ads::TargSuggestionsRegions do subject(:model) { described_class } it { is_expected.to be < Dry::Struct } it { is_expected.to be < Vk::Schema::Object } describe 'attributes' do subject(:attributes) { model.instance_methods(false) } it { is_expected.to include :id } it { is_expected.to include :name } it { is_expected.to include :type } end end
alsemyonov/vk
spec/vk/api/ads/targ_suggestions_regions_spec.rb
Ruby
mit
497
package percolate; /****************************************************************************** * Compilation: javac InteractivePercolationVisualizer.java * Execution: java InteractivePercolationVisualizer N * Dependencies: PercolationVisualizer.java Percolation.java * * This program takes the grid size N as a command-line argument. * Then, the user repeatedly clicks sites to open with the mouse. * After each site is opened, it draws full sites in light blue, * open sites (that aren't full) in white, and blocked sites in black. * ******************************************************************************/ import edu.princeton.cs.algs4.StdDraw; public class InteractivePercolationVisualizer { private static final int DELAY = 20; public static void main(String[] args) { // N-by-N percolation system (read from command-line, default = 10) int N = 10; if (args.length == 1) N = Integer.parseInt(args[0]); // turn on animation mode StdDraw.show(0); // repeatedly open site specified my mouse click and draw resulting system //StdOut.println(N); Percolation perc = new Percolation(N); PercolationVisualizer.draw(perc, N); StdDraw.show(DELAY); while (true) { // detected mouse click if (StdDraw.mousePressed()) { // screen coordinates double x = StdDraw.mouseX(); double y = StdDraw.mouseY(); // convert to row i, column j int i = (int) (N - Math.floor(y) - 1); int j = (int) (Math.floor(x)); // open site (i, j) provided it's in bounds if (i >= 0 && i < N && j >= 0 && j < N) { if (!perc.isOpen(i, j)) { //StdOut.println(i + " " + j); perc.open(i, j); } } // draw N-by-N percolation system PercolationVisualizer.draw(perc, N); } StdDraw.show(DELAY); } } }
TicknorN/B8-CSC301
Percolate/src/percolate/InteractivePercolationVisualizer.java
Java
mit
2,166
/*! \file */ /* ************************************************************************ * Copyright (c) 2019-2022 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * ************************************************************************ */ #include "auto_testing_bad_arg.hpp" #include "testing.hpp" template <typename T> void testing_gthr_bad_arg(const Arguments& arg) { static const size_t safe_size = 100; // Create rocsparse handle rocsparse_local_handle handle; // Allocate memory on device device_vector<rocsparse_int> dx_ind(safe_size); device_vector<T> dx_val(safe_size); device_vector<T> dy(safe_size); if(!dx_ind || !dx_val || !dy) { CHECK_HIP_ERROR(hipErrorOutOfMemory); return; } // Test rocsparse_gthr() EXPECT_ROCSPARSE_STATUS( rocsparse_gthr<T>(nullptr, safe_size, dy, dx_val, dx_ind, rocsparse_index_base_zero), rocsparse_status_invalid_handle); EXPECT_ROCSPARSE_STATUS( rocsparse_gthr<T>(handle, safe_size, nullptr, dx_val, dx_ind, rocsparse_index_base_zero), rocsparse_status_invalid_pointer); EXPECT_ROCSPARSE_STATUS( rocsparse_gthr<T>(handle, safe_size, dy, nullptr, dx_ind, rocsparse_index_base_zero), rocsparse_status_invalid_pointer); EXPECT_ROCSPARSE_STATUS( rocsparse_gthr<T>(handle, safe_size, dy, dx_val, nullptr, rocsparse_index_base_zero), rocsparse_status_invalid_pointer); } template <typename T> void testing_gthr(const Arguments& arg) { rocsparse_int M = arg.M; rocsparse_int nnz = arg.nnz; rocsparse_index_base base = arg.baseA; // Create rocsparse handle rocsparse_local_handle handle; // Argument sanity check before allocating invalid memory if(nnz <= 0) { static const size_t safe_size = 100; // Allocate memory on device device_vector<rocsparse_int> dx_ind(safe_size); device_vector<T> dx_val(safe_size); device_vector<T> dy(safe_size); if(!dx_ind || !dx_val || !dy) { CHECK_HIP_ERROR(hipErrorOutOfMemory); return; } CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_host)); EXPECT_ROCSPARSE_STATUS(rocsparse_gthr<T>(handle, nnz, dy, dx_val, dx_ind, base), nnz < 0 ? rocsparse_status_invalid_size : rocsparse_status_success); return; } // Allocate host memory host_vector<rocsparse_int> hx_ind(nnz); host_vector<T> hx_val_gold(nnz); host_vector<T> hy(M); // Initialize data on CPU rocsparse_seedrand(); rocsparse_init_index(hx_ind, nnz, 1, M); rocsparse_init<T>(hy, 1, M, 1); // Allocate device memory device_vector<rocsparse_int> dx_ind(nnz); device_vector<T> dx_val_1(nnz); device_vector<T> dx_val_2(nnz); device_vector<T> dy(M); if(!dx_ind || !dx_val_1 || !dx_val_2 || !dy) { CHECK_HIP_ERROR(hipErrorOutOfMemory); return; } // Copy data from CPU to device CHECK_HIP_ERROR(hipMemcpy(dx_ind, hx_ind, sizeof(rocsparse_int) * nnz, hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(dy, hy, sizeof(T) * M, hipMemcpyHostToDevice)); if(arg.unit_check) { // Pointer mode host CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_host)); CHECK_ROCSPARSE_ERROR(rocsparse_gthr<T>(handle, nnz, dy, dx_val_1, dx_ind, base)); // Pointer mode device CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_device)); CHECK_ROCSPARSE_ERROR(rocsparse_gthr<T>(handle, nnz, dy, dx_val_2, dx_ind, base)); // Copy output to host // CPU gthr host_gthr<rocsparse_int, T>(nnz, hy, hx_val_gold, hx_ind, base); hx_val_gold.unit_check(dx_val_1); hx_val_gold.unit_check(dx_val_2); } if(arg.timing) { int number_cold_calls = 2; int number_hot_calls = arg.iters; CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_host)); // Warm up for(int iter = 0; iter < number_cold_calls; ++iter) { CHECK_ROCSPARSE_ERROR(rocsparse_gthr<T>(handle, nnz, dy, dx_val_1, dx_ind, base)); } double gpu_time_used = get_time_us(); // Performance run for(int iter = 0; iter < number_hot_calls; ++iter) { CHECK_ROCSPARSE_ERROR(rocsparse_gthr<T>(handle, nnz, dy, dx_val_1, dx_ind, base)); } gpu_time_used = (get_time_us() - gpu_time_used) / number_hot_calls; double gbyte_count = gthr_gbyte_count<T>(nnz); double gpu_gbyte = get_gpu_gbyte(gpu_time_used, gbyte_count); display_timing_info("nnz", nnz, s_timing_info_bandwidth, gpu_gbyte, s_timing_info_time, get_gpu_time_msec(gpu_time_used)); } } #define INSTANTIATE(TYPE) \ template void testing_gthr_bad_arg<TYPE>(const Arguments& arg); \ template void testing_gthr<TYPE>(const Arguments& arg) INSTANTIATE(float); INSTANTIATE(double); INSTANTIATE(rocsparse_float_complex); INSTANTIATE(rocsparse_double_complex);
ROCmSoftwarePlatform/rocSPARSE
clients/testings/testing_gthr.cpp
C++
mit
6,546
<?php /** * @package start */ ?> <h1>integration</h1> <div class="content-section-b"> <div class="container"> <h1 class="title">Carreiras</h1> <div class="sidebar col-md-3"> <div> <h4 class='col-md-6'>total (<span id="total_vagas99">0</span>)</h4> <!--<div class="col-md-6 progress"> <div class="progress-bar" id="stream_progress" style="width: 0%;">0%</div> </div>--> </div> <div> <label class="sr-only" for="searchbox">Filtrar</label> <input type="text" class="form-control" id="searchbox" placeholder="Filtrar &hellip;" autocomplete="off"> <span class="glyphicon glyphicon-search search-icon"></span> </div> <br> <!--selects --> <div class="well"> <fieldset id="times_criteria"> <legend>Times</legend> <select class="form-control" id="times_filter" multiple="multiple"> </select> </fieldset> </div> <div class="well"> <fieldset id="local_criteria"> <legend>Localização</legend> <select class="form-control" id="local_filter" multiple="multiple"> </select> </fieldset> </div> <div class="well"> <fieldset id="tipo_criteria"> <legend>Tipo</legend> <select class="form-control" id="tipo_filter" multiple="multiple"> </select> </fieldset> </div> </div> <!-- /.col-md-3 --> <div class="col-md-9"> <div class="row"> <div class="content col-md-12"> <div id="pagination" class="vagas99-pagination col-md-9"></div> <div class="col-md-3 content"> Por Página: <span id="per_page" class="content"></span> </div> </div> </div> <!--teams and vagas--> <div class="row"> <div class="totalvagasteams"></div> </div> <div class="vagas99 row" id="vagas99"> </div> </div> <!-- /.col-md-9 --> </div> </div> <!-- /.container --> <script id="vagas99-template" type="text/html"> <div class="col-md-4 portfolio-item"> <div class="clearfix"></div> <a href="#"> <img class="img-responsive" src="http://placehold.it/700x400" alt=""> </a> <h3> <h4><a href="vaga.html?vagaid=<%= id %>"><%= _fid %> - <%= text %></a></h4> </h3> <h4><%= categories.team %></h4> <p><%= text %></p> </div> </script>
deigmaranderson/99carreiras
99carreiras/template-parts/integration.php
PHP
mit
2,732
namespace Bridge.Redux.Tests { using Html5; using QUnit; public static class ReduxThunkTests { public static void Run() { var initialCounter = new Counter { Count = 5 }; var counterReducer = BuildReducer.For<Counter>() .WhenActionHasType<Increment>((state, act) => new Counter { Count = state.Count + 1 }) .WhenActionHasType<Decrement>((state, act) => new Counter { Count = state.Count - 1 }) .WhenActionHasType<IncrementBy>((state, act) => new Counter { Count = state.Count + act.Value }) .Build(); var middleware = Redux.ApplyMiddleware(ReduxMiddleware.Thunk); var store = Redux.CreateStore(counterReducer, initialCounter, middleware); QUnit.Module("Redux Thunk Middleware"); QUnit.Test("Dispatching action with thunk middleware works", assert => { store.Dispatch(new Increment()); assert.Equal(store.GetState().Count, 6); }); QUnit.Test("Dispatching action after a timeout (async) works", assert => { var done = assert.Async(); store.ThunkDispatch(dispatch => { Window.SetTimeout(() => { var action = new IncrementBy { Value = 10 }; var normalized = action.NormalizeActionForDispatch(); dispatch(normalized); assert.Equal(store.GetState().Count, 16); done(); }, 500); }); }); } } }
Zaid-Ajaj/Bridge.Redux
Bridge.Redux.Tests/ReduxThunkTests.cs
C#
mit
1,774
<?php /* TwigBundle:Exception:traces.txt.twig */ class __TwigTemplate_39f631a2eb2e29d9f4069821c7f3afd5beaf2ed87b37023f3fdd2045c6e3f438 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 if (twig_length_filter($this->env, $this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "trace", array()))) { // line 2 $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "trace", array())); foreach ($context['_seq'] as $context["_key"] => $context["trace"]) { // line 3 $this->env->loadTemplate("TwigBundle:Exception:trace.txt.twig")->display(array("trace" => $context["trace"])); // line 4 echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['trace'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; } } public function getTemplateName() { return "TwigBundle:Exception:traces.txt.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 27 => 4, 25 => 3, 21 => 2, 19 => 1,); } }
spvernet/symfony_2
app/cache/dev/twig/39/f6/31a2eb2e29d9f4069821c7f3afd5beaf2ed87b37023f3fdd2045c6e3f438.php
PHP
mit
1,750
using Jobber.Core; using Jobber.Sample.Contract; namespace Jobber.Sample.JobProducer { class TodoJob : Job<Todo> { } }
GokGokalp/Jobber
Jobber.Sample.JobProducer/TodoJob.cs
C#
mit
134
function onInitSchema(schema, className) { schema.helpers = {}; }; export default onInitSchema;
jagi/meteor-astronomy
lib/modules/helpers/hooks/onInitSchema.js
JavaScript
mit
98
module Adman # Indicates this service is a web application WEB_APPLICATION = "_web_app" # Announces services on a network or other venue. class Campaign attr_reader :message attr_reader :venues # Create a new Campaign to advertize the given service. # # If the service given isn't already a Service (a String perhaps?) then the # Campaign will try to turn it into one. def initialize(service) # If this isn't yet a service try to turn it into one unless service.kind_of?(Service) service = Service.new(service) end @message = service @venues = [] end def add_venue(venue) @venues << venue self end # Start advertising this service def launch @venues.each do |venue| venue.register(message) end self end end # A Service which is announced by the announcer. # # A service is a general term and can be a web application, # mail server, or anything that can described in terms of a # service name, type, and port. class Service DEFAULT_PORT = 3000 DEFAULT_TYPE = "_web_app" include Comparable attr_reader :name attr_reader :port attr_reader :type # Compare this Service to another def <=>(other) if self.name < other.name return -1 elsif self.name > other.name return 1 elsif self.port < other.port return -1 elsif self.port > other.port return 1 elsif self.type < other.type return -1 elsif self.type > other.type return 1 else return 0 end end def initialize(service_name) @name = service_name # Set some defaults @port = 3000 @type = WEB_APPLICATION end end def self.announce(service_name) announcer = Announcer.new(service_name) announcer end end
MarkBennett/announcer
lib/announcer.rb
Ruby
mit
1,899
using System.Collections; using UnityEngine; [RequireComponent (typeof(Animator))] public class SpriteDestruction : MonoBehaviour { private SpriteBuilder m_spriteBuilder; private Animator m_animator; public float TimeToDestroy = 1; public int DestroySquarePixelSize = 10; public int DestroySquareCount = 5; void Awake () { m_animator = GetComponent<Animator> (); m_spriteBuilder = GetComponent<SpriteBuilder> (); } public IEnumerator DestroySprite () { m_animator.enabled = false; m_spriteBuilder.Build (); var rect = m_spriteBuilder.Sprite.rect; var minX = (int)rect.x; var maxX = (int)rect.xMax + 1 - DestroySquarePixelSize; var minY = (int)rect.y; var maxY = (int)rect.yMax + 1 - DestroySquarePixelSize; var interval = TimeToDestroy / DestroySquareCount; // Destroy any squares on Alien. for (int i = 0; i < DestroySquareCount; i++) { // Get random points to square. var beginX = Random.Range (minX, maxX); var endX = beginX + DestroySquarePixelSize; var beginY = Random.Range (minY, maxY); var endy = beginY + DestroySquarePixelSize; // Draw the square. for (var x = beginX; x <= endX; x++) { for (var y = beginY; y < endy; y++) { m_spriteBuilder.ClearColor (x, y); } } m_spriteBuilder.Rebuild (); yield return new WaitForSeconds (interval); } m_spriteBuilder.Build (); SendMessageUpwards ("OnSpriteDestructionEnd"); } }
skahal/SpaceInvadersRemake
src/SpaceInvadersRemake/Assets/Scripts/SpriteDestruction.cs
C#
mit
1,423
var angular = require('angular'); angular.module('rsInfiniteScrollDemo', [require('rs-infinite-scroll').default]) /*@ngInject*/ .controller('RsDemoController', ['$q', '$timeout', function($q, $timeout) { var ctrl = this; ctrl.scrollProxy = { loadPrevious, loadFollowing }; ctrl.dummyList = []; let init = function() { $timeout(function() { ctrl.dummyList = [ {index: 1}, {index: 2}, {index: 3}, {index: 4}, {index: 5}, {index: 6}, {index: 7}, {index: 8}, {index: 9}, {index: 10} ]; loadFollowing(); }, 5000); }; init(); function loadPrevious() { let first = ctrl.dummyList[0]; return addBefore(first); } function loadFollowing() { let last = ctrl.dummyList[ctrl.dummyList.length-1]; // should be safe after initialization if (!last) { var deferred = $q.defer(); deferred.resolve(); return deferred.promise; } return addAfter(last); } function addAfter(last) { var deferred = $q.defer(); deferred.resolve(); $timeout(() => { if (last.index > 1000) { deferred.resolve(); return; } for (let i = last.index+1; i < last.index+10; i++) { ctrl.dummyList.push({index: i}); } deferred.resolve(); }, 200); return deferred.promise; } function addBefore(first) { var deferred = $q.defer(); deferred.resolve(); $timeout(() => { if (first.index < -1000) { deferred.resolve(); return; } for (let i = first.index-1; i > first.index-10; i--) { ctrl.dummyList.unshift({index: i}); } deferred.resolve(); }, 200); return deferred.promise; } }]);
RetroSquareGroup/rs-infinite-scroll
demo/demo.js
JavaScript
mit
1,907
<?php /* * This file is part of the json-schema bundle. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace HadesArchitect\JsonSchemaBundle\Exception; use HadesArchitect\JsonSchemaBundle\Error\Error; class ViolationException extends JsonSchemaException { /** * @var Error[] */ protected $errors = array(); /** * @param Error[] $errors */ public function __construct(array $errors) { $message = ''; foreach ($errors as $error) { $message .= (string) $error . '. '; $this->addError($error); } parent::__construct(rtrim($message)); } public function addError(Error $error) { $this->errors[] = $error; } public function getErrors() { return $this->errors; } }
HadesArchitect/JsonSchemaBundle
Exception/ViolationException.php
PHP
mit
898
/*************************************** ** Tsunagari Tile Engine ** ** window.cpp ** ** Copyright 2011-2014 PariahSoft LLC ** ***************************************/ // ********** // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ********** #include <stdlib.h> #include "window.h" #include "world.h" GameWindow::GameWindow() : keysDown(KB_SIZE) { } GameWindow::~GameWindow() { } void GameWindow::emitKeyDown(KeyboardKey key) { keysDown[key]++; if (keysDown[KBEscape] && (keysDown[KBLeftShift] || keysDown[KBRightShift])) { exit(0); } if (keysDown[key]) World::instance().buttonDown(key); } void GameWindow::emitKeyUp(KeyboardKey key) { keysDown[key]--; if (!keysDown[key]) World::instance().buttonUp(key); } bool GameWindow::isKeyDown(KeyboardKey key) { return keysDown[key] != false; } BitRecord GameWindow::getKeysDown() { return keysDown; }
pariahsoft/TsunagariC
src/window.cpp
C++
mit
1,938
class MagicDictionary { public: map<int, vector<string>> m; /** Initialize your data structure here. */ MagicDictionary() { } /** Build a dictionary through a list of words */ void buildDict(vector<string> dict) { for (auto &i : dict) { m[i.length()].push_back(i); } } /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */ bool search(string word) { int len = word.length(); for (auto &i : m[len]) { int count = 0; for (int k = 0; k < len; k++) { if (i[k] == word[k]) { count++; } } if (count + 1 == len) { return true; } } return false; } }; /** * Your MagicDictionary object will be instantiated and called as such: * MagicDictionary obj = new MagicDictionary(); * obj.buildDict(dict); * bool param_2 = obj.search(word); */
MegaShow/college-programming
OJ/LeetCode/676 Implement Magic Dictionary.cpp
C++
mit
1,046
<?php return array ( 'id' => 'zte_z750c_ver1', 'fallback' => 'generic_android_ver4_1', 'capabilities' => array ( 'model_name' => 'Z750C', 'brand_name' => 'ZTE', 'marketing_name' => 'Savvy', 'physical_screen_height' => '88', 'physical_screen_width' => '53', 'resolution_width' => '480', 'resolution_height' => '800', ), );
cuckata23/wurfl-data
data/zte_z750c_ver1.php
PHP
mit
361
/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. */ package com.microsoft.o365_android_onenote_rest; import com.microsoft.AzureADModule; import com.microsoft.AzureAppCompatActivity; import com.microsoft.live.LiveAuthClient; import com.microsoft.o365_android_onenote_rest.application.SnippetApp; import com.microsoft.o365_android_onenote_rest.conf.ServiceConstants; import com.microsoft.o365_android_onenote_rest.inject.AzureModule; import com.microsoft.o365_android_onenote_rest.inject.ObjectGraphInjector; import com.microsoft.o365_android_onenote_rest.model.Scope; import java.util.ArrayList; import javax.inject.Inject; import dagger.ObjectGraph; import timber.log.Timber; public abstract class BaseActivity extends AzureAppCompatActivity implements ObjectGraphInjector { @Inject protected LiveAuthClient mLiveAuthClient; public static final Iterable<String> sSCOPES = new ArrayList<String>() {{ for (Scope.wl scope : Scope.wl.values()) { Timber.i("Adding scope: " + scope); add(scope.getScope()); } for (Scope.office scope : Scope.office.values()) { Timber.i("Adding scope: " + scope); add(scope.getScope()); } }}; @Override protected AzureADModule getAzureADModule() { AzureADModule.Builder builder = new AzureADModule.Builder(this); builder.validateAuthority(true) .skipBroker(true) .authenticationResourceId(ServiceConstants.AUTHENTICATION_RESOURCE_ID) .authorityUrl(ServiceConstants.AUTHORITY_URL) .redirectUri(ServiceConstants.REDIRECT_URI) .clientId(ServiceConstants.CLIENT_ID); return builder.build(); } @Override protected Object[] getModules() { return new Object[]{new AzureModule()}; } @Override protected ObjectGraph getRootGraph() { return SnippetApp.getApp().mObjectGraph; } @Override public void inject(Object target) { mObjectGraph.inject(target); } } // ********************************************************* // // Android-REST-API-Explorer, https://github.com/OneNoteDev/Android-REST-API-Explorer // // Copyright (c) Microsoft Corporation // All rights reserved. // // MIT License: // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // *********************************************************
OneNoteDev/Android-REST-API-Explorer
app/src/main/java/com/microsoft/o365_android_onenote_rest/BaseActivity.java
Java
mit
3,525
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Paypal * @copyright Copyright (c) 2006-2019 Magento, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Fieldset renderer for PayPal solutions which have dependencies on other solutions * * @category Mage * @package Mage_Paypal * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Paypal_Block_Adminhtml_System_Config_Fieldset_PathDependent extends Mage_Paypal_Block_Adminhtml_System_Config_Fieldset_Payment { /** * Check whether current payment method has active dependencies * * @param array $groupConfig * @return bool */ public function hasActivePathDependencies($groupConfig) { $activityPath = isset($groupConfig['hide_case_path']) ? $groupConfig['hide_case_path'] : ''; return !empty($activityPath) && (bool)(string)$this->_getConfigDataModel()->getConfigDataValue($activityPath); } /** * Do not render solution if disabled * * @param Varien_Data_Form_Element_Abstract $element * @return string */ public function render(Varien_Data_Form_Element_Abstract $element) { if (!$this->hasActivePathDependencies($this->getGroup($element)->asArray())) { return parent::render($element); } return ''; } }
portchris/NaturalRemedyCompany
src/app/code/core/Mage/Paypal/Block/Adminhtml/System/Config/Fieldset/PathDependent.php
PHP
mit
2,121
<?php namespace Domora\TvGuide\Data; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; use JMS\Serializer\Annotation as Serializer; /** * @ORM\Entity * @ORM\Table(name="service") */ class Service { /** * @ORM\Id * @ORM\Column(type="string") * @Serializer\Groups({"list", "service"}) */ private $id; /** * @ORM\Column(type="string") * @Serializer\Groups({"list", "service"}) */ private $name; /** * @ORM\Column(type="string") * @Serializer\Groups({"list", "service"}) */ private $country; /** * @ORM\OneToMany(targetEntity="ServiceChannelAssociation", mappedBy="service") * @Serializer\Type("array<Domora\TvGuide\Data\ServiceChannelAssociation>") * @Serializer\Groups({"service"}) */ private $channels; public function __construct() { $this->channels = new ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set id * * @param string id * @return Channel */ public function setId($id) { $this->id = $id; return $this; } /** * Set name * * @param string $name * @return Channel */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set country * * @param string $country * @return Channel */ public function setCountry($country) { $this->country = $country; return $this; } /** * Get country * * @return string */ public function getCountry() { return $this->country; } /** * Add channels * * @param \Domora\TvGuide\Data\ServiceChannelAssociation $channels * * @return Service */ public function addChannel(\Domora\TvGuide\Data\ServiceChannelAssociation $channels) { $this->channels[] = $channels; return $this; } /** * Remove channels * * @param \Domora\TvGuide\Data\ServiceChannelAssociation $channels */ public function removeChannel(\Domora\TvGuide\Data\ServiceChannelAssociation $channels) { $this->channels->removeElement($channels); } /** * Get channels * * @return \Doctrine\Common\Collections\Collection */ public function getChannels() { return $this->channels; } }
domora/tvguide
src/Domora/TvGuide/Data/Service.php
PHP
mit
2,698
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NotificationSenderUtility")] [assembly: AssemblyDescription("Class Library to communicate with the Push Notification Service")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft Corp.")] [assembly: AssemblyProduct("Using Push Notifications Hands-on Lab")] [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4cb73b37-8cd0-456a-8c69-ea3e6622582b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
DDReaper/XNAGameStudio
Samples/PushRecipe_WP7_SL/Source/WindowsPhone.Recipes.Push.Messasges/Properties/AssemblyInfo.cs
C#
mit
1,525
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { reddit: { userAgent: 'USER_AGENT', clientId: 'CLIENT ID', clientSecret: 'CLIENT SECRET', username: 'BOT USERNAME', password: 'BOT PASSWORD' }, mods: ['MODERATOR_1', 'MODERATOR_2'] };
cmhoc/fuckmwbot
dist/config.js
JavaScript
mit
308
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Powder_Plastic_Coat_Model extends CI_Model { private $powder_plastic_coatTable = 'powder_plastic_coat'; private $powder_plastic_coatColumn = 'powder_plastic_coat_id'; public function __construct() { parent::__construct(); } public function form_input_attributes($data, $id) { if(isset($id) && !empty($id)) { $data_split = explode('_', $data); $this->db->where($this->powder_plastic_coatColumn, $id); $query = $this->db->get($this->powder_plastic_coatTable); foreach ($query->result() as $row) { $value = $row->$data; } if(count($data_split) > 2) { $attributes = array( 'name' => $data_split[3], 'id' => $data_split[3], 'type' => 'text', 'value' => $value, 'class' => 'form-control input-md', 'placeholder' => 'insert '.str_replace('_', ' ', $data).' here' ); } else { $attributes = array( 'name' => $data_split[3], 'id' => $data_split[3], 'type' => 'text', 'value' => $value, 'class' => 'form-control input-md', 'placeholder' => 'insert '.str_replace('_', ' ', $data).' here' ); } } else { $data_split = explode('_', $data); if(count($data_split) > 2) { $attributes = array( 'name' => $data_split[3], 'id' => $data_split[3], 'type' => 'text', 'class' => 'form-control input-md', 'placeholder' => 'insert '.str_replace('_', ' ', $data_split[3]).' here' ); } else { $attributes = array( 'name' => $data_split[3], 'id' => $data_split[3], 'type' => 'text', 'class' => 'form-control input-md', 'placeholder' => 'insert '.str_replace('_', ' ', $data_split[3]).' here' ); } } return $attributes; } public function form_textarea_attributes($data, $id) { if(isset($id) && !empty($id)) { $this->db->where($this->powder_plastic_coatColumn, $id); $query = $this->db->get($this->powder_plastic_coatTable); foreach ($query->result() as $row) { $value = $row->$data; } $attributes = array( 'name' => $data, 'id' => $data, 'rows' => '5', 'value' => $value, 'class' => 'auto-size form-control', 'placeholder' => 'insert '.str_replace('_', ' ', $data).' here' ); } else { $attributes = array( 'name' => $data, 'id' => $data, 'rows' => '5', 'class' => 'auto-size form-control', 'placeholder' => 'insert '.str_replace('_', ' ', $data).' here' ); } return $attributes; } public function form_input_numeric_attributes($data, $id) { if(isset($id) && !empty($id)) { $data_split = explode('_', $data); $this->db->where($this->powder_plastic_coatColumn, $id); $query = $this->db->get($this->powder_plastic_coatTable); foreach ($query->result() as $row) { $value = $row->$data; } if(count($data_split) > 2) { $attributes = array( 'name' => $data_split[3].'_'.$data_split[4], 'id' => $data_split[3].'_'.$data_split[4], 'type' => 'text', 'value' => $value, 'class' => 'form-control input-md numeric', 'placeholder' => 'insert '.str_replace('_', ' ', $data_split[3].' '.$data_split[4]).' here' ); } else { $attributes = array( 'name' => $data_split[3].'_'.$data_split[4], 'id' => $data_split[3].'_'.$data_split[4], 'type' => 'text', 'value' => $value, 'class' => 'form-control input-md numeric', 'placeholder' => 'insert '.str_replace('_', ' ', $data_split[3].' '.$data_split[4]).' here' ); } } else { $data_split = explode('_', $data); if(count($data_split) > 2) { $attributes = array( 'name' => $data_split[3].'_'.$data_split[4], 'id' => $data_split[3].'_'.$data_split[4], 'type' => 'text', 'class' => 'form-control input-md numeric', 'placeholder' => 'insert '.str_replace('_', ' ', $data_split[3].' '.$data_split[4]).' here' ); } else { $attributes = array( 'name' => $data_split[3].'_'.$data_split[4], 'id' => $data_split[3].'_'.$data_split[4], 'type' => 'text', 'class' => 'form-control input-md numeric', 'placeholder' => 'insert '.str_replace('_', ' ', $data_split[3].' '.$data_split[4]).' here' ); } } return $attributes; } public function find($id) { $this->db->select('*'); $this->db->from('powder_plastic_coat as dep'); $this->db->join('created as cre','dep.powder_plastic_coat_id = cre.created_table_id'); $this->db->where('cre.created_table','powder_plastic_coat'); $this->db->where('dep.powder_plastic_coat_id', $id); $query = $this->db->get(); foreach ($query->result() as $row) { $arr[] = array( 'powder_plastic_coat_id' => $row->powder_plastic_coat_id, 'powder_plastic_coat_code' => $row->powder_plastic_coat_code, 'derpartment_name' => $row->powder_plastic_coat_name, 'powder_plastic_coat_description' => $row->powder_plastic_coat_description ); } return $arr; } public function insert($data) { $this->db->insert($this->powder_plastic_coatTable, $data); return $this->db->insert_id(); } public function modify($data, $id) { $this->db->where($this->powder_plastic_coatColumn, $id); $this->db->update($this->powder_plastic_coatTable, $data); return true; } public function get_all_powder_plastic_coat($start_from=0, $limit=0) { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable.' as pow'); $this->db->join('status as stat','pow.powder_plastic_coat_id = stat.status_table_id'); $this->db->where('stat.status_table', $this->powder_plastic_coatTable); $this->db->where('stat.status_code', 1); $this->db->order_by('pow.'.$this->powder_plastic_coatColumn, 'DESC'); $query = $this->db->limit( $limit, $start_from )->get(); return $query; } public function get_alls_powder_plastic_coat() { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable.' as pow'); $this->db->join('status as stat','pow.powder_plastic_coat_id = stat.status_table_id'); $this->db->where('stat.status_table', $this->powder_plastic_coatTable); $this->db->where('stat.status_code', 1); $this->db->order_by('pow.'.$this->powder_plastic_coatColumn, 'DESC'); $query = $this->db->get(); return $query; } public function like_powder_plastic_coat($wildcard='', $start_from=0, $limit=0) { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable.' as pow'); $this->db->join('status as stat','pow.powder_plastic_coat_id = stat.status_table_id'); $this->db->join('unit_of_measurement as uom','pow.unit_of_measurement_id = uom.unit_of_measurement_id'); $this->db->where('stat.status_table', $this->powder_plastic_coatTable); $this->db->where('stat.status_code', 1); $this->db->group_start(); $this->db->or_where('pow.powder_plastic_coat_id LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_code LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_name LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_description LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_weighted_ave LIKE', '%' . $wildcard . '%'); $this->db->or_where('uom.unit_of_measurement_name LIKE', '%' . $wildcard . '%'); $this->db->group_end(); $this->db->order_by('pow.'.$this->powder_plastic_coatColumn, 'DESC'); $query = $this->db->limit( $limit, $start_from )->get(); return $query; } public function likes_powder_plastic_coat($wildcard='') { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable.' as pow'); $this->db->join('status as stat','pow.powder_plastic_coat_id = stat.status_table_id'); $this->db->join('unit_of_measurement as uom','pow.unit_of_measurement_id = uom.unit_of_measurement_id'); $this->db->where('stat.status_table', $this->powder_plastic_coatTable); $this->db->where('stat.status_code', 1); $this->db->group_start(); $this->db->or_where('pow.powder_plastic_coat_id LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_code LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_name LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_description LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_weighted_ave LIKE', '%' . $wildcard . '%'); $this->db->or_where('uom.unit_of_measurement_name LIKE', '%' . $wildcard . '%'); $this->db->group_end(); $this->db->order_by('pow.'.$this->powder_plastic_coatColumn, 'DESC'); $query = $this->db->get(); return $query; } public function get_all_archived_powder_plastic_coat($start_from=0, $limit=0) { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable.' as dep'); $this->db->join('status as stat','dep.powder_plastic_coat_id = stat.status_table_id'); $this->db->where('stat.status_table', $this->powder_plastic_coatTable); $this->db->where('stat.status_code', 0); $this->db->order_by('dep.'.$this->powder_plastic_coatColumn, 'DESC'); $query = $this->db->limit( $limit, $start_from )->get(); return $query; } public function get_alls_archived_powder_plastic_coat() { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable.' as dep'); $this->db->join('status as stat','dep.powder_plastic_coat_id = stat.status_table_id'); $this->db->where('stat.status_table', $this->powder_plastic_coatTable); $this->db->where('stat.status_code', 0); $this->db->order_by('dep.'.$this->powder_plastic_coatColumn, 'DESC'); $query = $this->db->get(); return $query; } public function like_archived_powder_plastic_coat($wildcard='', $start_from=0, $limit=0) { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable.' as pow'); $this->db->join('status as stat','pow.powder_plastic_coat_id = stat.status_table_id'); $this->db->join('unit_of_measurement as uom','pow.unit_of_measurement_id = uom.unit_of_measurement_id'); $this->db->where('stat.status_table', $this->powder_plastic_coatTable); $this->db->where('stat.status_code', 0); $this->db->group_start(); $this->db->or_where('pow.powder_plastic_coat_id LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_code LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_name LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_description LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_weighted_ave LIKE', '%' . $wildcard . '%'); $this->db->or_where('uom.unit_of_measurement_name LIKE', '%' . $wildcard . '%'); $this->db->group_end(); $this->db->order_by('pow.'.$this->powder_plastic_coatColumn, 'DESC'); $query = $this->db->limit( $limit, $start_from )->get(); return $query; } public function likes_archived_powder_plastic_coat($wildcard='') { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable.' as pow'); $this->db->join('status as stat','pow.powder_plastic_coat_id = stat.status_table_id'); $this->db->join('unit_of_measurement as uom','pow.unit_of_measurement_id = uom.unit_of_measurement_id'); $this->db->where('stat.status_table', $this->powder_plastic_coatTable); $this->db->where('stat.status_code', 0); $this->db->group_start(); $this->db->or_where('pow.powder_plastic_coat_id LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_code LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_name LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_description LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_weighted_ave LIKE', '%' . $wildcard . '%'); $this->db->or_where('uom.unit_of_measurement_name LIKE', '%' . $wildcard . '%'); $this->db->group_end(); $this->db->order_by('pow.'.$this->powder_plastic_coatColumn, 'DESC'); $query = $this->db->get(); return $query; } public function get_powder_plastic_coat_name_by_id($id) { $this->db->where($this->powder_plastic_coatColumn, $id); $query = $this->db->get($this->powder_plastic_coatTable); foreach($query->result() as $row) { $id = $row->powder_plastic_coat_name; } return $id; } public function form_select_attributes($data) { $attributes = array( 'name' => $data, 'id' => $data, 'class' => 'selectpicker', 'data-live-search' => 'true' ); return $attributes; } public function form_select_options($data) { $query = $this->db->get($this->powder_plastic_coatTable); $arr[] = array( '0' => 'select '.str_replace('_', ' ', $data).' here', ); foreach ($query->result() as $row) { $arr[] = array( $row->powder_plastic_coat_id => $row->powder_plastic_coat_name ); } $array = array(); foreach($arr as $arrs) foreach($arrs as $key => $val) $array[$key] = $val; return $array; } public function form_selected_options($id) { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable); $this->db->where($this->powder_plastic_coatColumn, $id); $query = $this->db->get(); if($query->num_rows() > 0) { foreach ($query->result() as $row) { $id = $row->powder_plastic_coat_id; } return $id; } else { return $id = '0'; } } }
aliudin-ftc/just-in-time-version-2
application/models/Powder_Plastic_Coat_Model.php
PHP
mit
16,688
# frozen_string_literal: true require 'spec_helper' describe Gitlab::Ci::Pipeline::Seed::Environment do let_it_be(:project) { create(:project) } let(:job) { build(:ci_build, project: project) } let(:seed) { described_class.new(job) } let(:attributes) { {} } before do job.assign_attributes(**attributes) end describe '#to_resource' do subject { seed.to_resource } context 'when job has environment attribute' do let(:attributes) do { environment: 'production', options: { environment: { name: 'production' } } } end it 'returns a persisted environment object' do expect(subject).to be_a(Environment) expect(subject).to be_persisted expect(subject.project).to eq(project) expect(subject.name).to eq('production') end context 'when environment has already existed' do let!(:environment) { create(:environment, project: project, name: 'production') } it 'returns the existing environment object' do expect(subject).to be_persisted expect(subject).to eq(environment) end end end end end
stoplightio/gitlabhq
spec/lib/gitlab/ci/pipeline/seed/environment_spec.rb
Ruby
mit
1,171
<?php namespace Phrest\API; use PHPUnit\Framework\TestCase; use Zend\Diactoros\ServerRequest; class RESTActionTraitTestClassBase { use RESTActionTrait; } class RESTActionTraitTestClass extends RESTActionTraitTestClassBase { public function get() { } public function delete() { } } class RESTActionTraitTest extends TestCase { public function testConstructor() { $class = new RESTActionTraitTestClass(); self::assertInstanceOf(RESTActionTraitTestClass::class, $class); } private function createClass(\Monolog\Handler\HandlerInterface $handler): RESTActionTraitTestClass { $class = new RESTActionTraitTestClass(); $class->setLogger( new \Monolog\Logger('test', [$handler]) ); return $class; } public function testProcessMethodNotExists() { self::expectException(\Phrest\Http\Exception::class); self::expectExceptionMessage('Method not allowed'); self::expectExceptionCode(405); $testHandler = new \Monolog\Handler\TestHandler(); $class = $this->createClass($testHandler); try { $class->process( new \Zend\Diactoros\ServerRequest( [], [], null, 'thisMethodDoesNotExists', 'php://memory' ), new \Zend\Expressive\Delegate\NotFoundDelegate( new \Zend\Diactoros\Response() ) ); } catch (\Phrest\Http\Exception $e) { self::assertArraySubset([ [ 'message' => 'Phrest\API\RESTActionTrait::process called', 'context' => [ 'method' => 'thismethoddoesnotexists' ], 'level' => 100, 'level_name' => 'DEBUG', 'channel' => 'test', ] ], $testHandler->getRecords()); self::assertEquals(0, $e->error()->code()); self::assertEquals('Method not allowed', $e->error()->message()); $errors = $e->error()->errors(); self::assertCount(1, $errors); self::assertEquals(0, $errors[0]->code()); self::assertEquals('Method "thismethoddoesnotexists" not allowed', $errors[0]->message()); throw $e; } } public function testProcessOptions() { $testHandler = new \Monolog\Handler\TestHandler(); $class = $this->createClass($testHandler); $response = $class->process( new \Zend\Diactoros\ServerRequest( [], [], null, 'options', 'php://memory' ), new \Zend\Expressive\Delegate\NotFoundDelegate( new \Zend\Diactoros\Response() ) ); self::assertArraySubset([ [ 'message' => 'Phrest\API\RESTActionTrait::process called', 'context' => [ 'method' => 'options' ], 'level' => 100, 'level_name' => 'DEBUG', 'channel' => 'test', ] ], $testHandler->getRecords()); self::assertEquals(204, $response->getStatusCode()); self::assertEquals('', $response->getBody()->getContents()); self::assertEquals([ 'Allow' => [ 'GET, DELETE' ] ], $response->getHeaders()); } public function testOnRESTRequest() { $testHandler = new \Monolog\Handler\TestHandler(); $class = $this->createClass($testHandler); $response = $class->process( new \Zend\Diactoros\ServerRequest( [], [], null, 'GET', 'php://memory' ), new \Zend\Expressive\Delegate\NotFoundDelegate( new \Zend\Diactoros\Response() ) ); self::assertArraySubset([ [ 'message' => 'Phrest\API\RESTActionTrait::process called', 'context' => [ 'method' => 'get' ], 'level' => 100, 'level_name' => 'DEBUG', 'channel' => 'test', ] ], $testHandler->getRecords()); self::assertEquals(204, $response->getStatusCode()); self::assertEquals('', $response->getBody()->getContents()); } }
DonUrks/phrest
tests/Phrest/API/RESTActionTraitTest.php
PHP
mit
4,648
using Naxis.Core.Components; namespace Naxis.Core.Security { public class AuthedUser { /// <summary> /// 授权服务 /// </summary> private static readonly IAuthenticationService Service = ObjectContainer.Resolve<IAuthenticationService>(); /// <summary> /// 获取当前用户信息 /// </summary> public static AuthUser Current { get { return Service.GetAuthenticatedUser(); } } } }
swpudp/Naxis
Naxis.Common/Security/AuthedUser.cs
C#
mit
494
<?php $pageTitle = "News Feed"; require('includes/header.php'); $my_friends=$mysqli->query("SELECT friendArray FROM profile WHERE userID=$userID"); $myfriends=mysqli_fetch_row($my_friends); $myfriends=implode("",$myfriends); $my_friends_array=explode(",",$myfriends); //echo $my_friends_array; ?> <link href="css/4Inst.css" rel="stylesheet"> <div class="container"> <h3>News Feed</h3> <div class="SetCenterImage"> <?php $query_image = $mysqli->query("SELECT * FROM PhotoUpload WHERE circleShared='' ORDER BY datestamp DESC"); while($query_image_row=mysqli_fetch_array($query_image)){ $photoUserID = $query_image_row['userID']; $photoTime=$query_image_row['datestamp']; if(in_array($photoUserID,$my_friends_array)){ $photoURL = $query_image_row['photo']; $photoID = $query_image_row['photoID']; //get photo uploader name $getuserNames = $mysqli->query("SELECT firstname, lastname FROM Profile WHERE userID=$photoUserID"); $getuserNamesrow = mysqli_fetch_array($getuserNames); $photoUserFname = $getuserNamesrow['firstname']; $photoUserLname = $getuserNamesrow['lastname']; echo '<div class="col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-body"> <a href="photoInfo.php?photoid='.$photoID.'"class="thumbnail"> <img src="'.$photoURL.'"> </a> </div> <div class="panel-footer"> <h4>'.$photoUserFname.' '.$photoUserLname.' <small>on '.$photoTime.'</small></h4> </div> </div> </div>'; } else { } } ?> </div> </div> <?php require('includes/footer.php');?>
mgander/4inst
home.php
PHP
mit
1,563
"use strict"; var inspirationArchitectFactory = require('../inspiration-architect.min'); var should = require('should'); var _get = require('lodash/get'); var _set = require('lodash/set'); var globalTests = require('./global-tests'); var factoryTests = require('./factory-tests'); var config_files = require('../test/fixtures/sample-app/config/*.js', {mode: 'hash', options: {dot: true}}); var empty_config_files = require('../test/fixtures/empty/*.js', {mode: 'hash'}); var provider_files = require('../test/fixtures/sample-app/providers/*.js', {mode: 'hash'}); var empty_provider_files = require('../test/fixtures/empty/*.js', {mode: 'hash'}); factoryTests(inspirationArchitectFactory); describe('browserify tests', function() { describe('different config files', function() { var factory_config = { config_files: config_files }; var Inspiration = inspirationArchitectFactory(factory_config); it('should run the basic tests', function() { globalTests(Inspiration); }); it('should honor the server config files', function(done) { var inspiration = new Inspiration(); inspiration.init(function(err) { if (err) { throw err; } should(inspiration.app.config('a_sample')).equal('one'); should(inspiration.app.config('b_sample')).equal('two'); should(inspiration.app.config('e_sample.f_sample.g_sample')).equal(5); should(inspiration.app.config('external.h_sample')).equal('hello'); done(); }); }); it('should be able to overwrite server config files', function(done) { var config = { a_sample: 'overwritten', b_sample: 'also overwritten', external: { h_sample: 'this is also overwritten' } }; var inspiration = new Inspiration({ config: config }); inspiration.init(function(err) { if (err) { throw err; } should(inspiration.app.config('a_sample')).equal(config.a_sample); should(inspiration.app.config('b_sample')).equal(config.b_sample); should(inspiration.app.config('external.h_sample')).equal(config.external.h_sample); should(inspiration.app.config('external.i_sample')).not.equal(undefined); done(); }); }); }); describe('no config files', function() { var factory_config = { config_files: empty_config_files }; var Inspiration = inspirationArchitectFactory(factory_config); it('should run the basic tests', function() { globalTests(Inspiration); }); it('should be able to overwrite empty server config files', function(done) { var config = { a_sample: 'overwritten', b_sample: 'also overwritten', external: { h_sample: 'this is also overwritten' } }; var inspiration = new Inspiration({ config: config }); inspiration.init(function(err) { if (err) { throw err; } should(inspiration.app.config('a_sample')).equal(config.a_sample); should(inspiration.app.config('b_sample')).equal(config.b_sample); should(inspiration.app.config('external.h_sample')).equal(config.external.h_sample); done(); }); }); }); describe('reference server providers', function() { var factory_config = { provider_files: provider_files }; var Inspiration = inspirationArchitectFactory(factory_config); it('should run the server providers based on the config', function(done) { var inspiration = new Inspiration({ config: { providers: [ 'addSomethingAsync', 'addSomething', function(app, done) { app.doSomethingElse = function() { return 3; }; done(); } ] } }); inspiration.init(function(err) { if (err) { throw err; } inspiration.app.doSomethingAsync().should.equal(1); inspiration.app.doSomething().should.equal(2); inspiration.app.doSomethingElse().should.equal(3); done(); }); }); }); describe('no provider files', function() { var factory_config = { provider_files: empty_provider_files }; var Inspiration = inspirationArchitectFactory(factory_config); it('should run the basic tests', function() { globalTests(Inspiration); }); it('should still run initial providers', function(done) { var inspiration = new Inspiration({ providers: [ function(app, done) { app.something_property = 1; done(); }, function(app, done) { app.something_other_property = 2; done(); } ], config: { providers: [ function(app, done) { app.something_third_property = 3; done(); } ] } }); inspiration.init(function(err) { if (err) { throw err; } inspiration.app.something_property.should.equal(1); inspiration.app.something_other_property.should.equal(2); inspiration.app.something_third_property.should.equal(3); done(); }); }); }); describe('different factory config values combined', function() { var config_env_filename = 'local'; var config_app_filename = 'application'; var config_providers_path = 'these.are.my.providers'; var app_config_path = 'locals.config'; var factory_config = { config_files: {}, config_env_filename: config_env_filename, config_app_filename: config_app_filename, config_providers_path: config_providers_path, app_config_path: app_config_path, provider_files: provider_files }; factory_config.config_files[config_env_filename] = { greeting: 'aloha' }; factory_config.config_files[config_app_filename] = { greeting: 'hello', parting: 'goodbye' }; _set(factory_config.config_files[config_app_filename], config_providers_path, [ 'addSomething' ]); var Inspiration = inspirationArchitectFactory(factory_config); it('should honor the factory config', function(done) { var inspiration = new Inspiration(); inspiration.test = true; inspiration.init(function(err) { if (err) { throw err; } var config = _get(inspiration.app, app_config_path); should(config('greeting')).equal('aloha'); should(config('parting')).equal('goodbye'); inspiration.app.doSomething().should.equal(2); done(); }); }); }); });
musejs/inspiration-architect
test-src/browserify.js
JavaScript
mit
8,096
using System; using System.IO; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Security.Cryptography; namespace Radical.Windows.Bootstrap { //courtesy of NServiceBus https://github.com/Particular/NServiceBus/blob/4954af83fad81cc80769c8ed161ee4a37812d443/src/NServiceBus.Core/Hosting/Helpers/AssemblyValidator.cs class AssemblyValidator { public static void ValidateAssemblyFile(string assemblyPath, out bool shouldLoad, out string reason) { using (var stream = File.OpenRead(assemblyPath)) using (var file = new PEReader(stream)) { var hasMetadata = false; try { hasMetadata = file.HasMetadata; } catch (BadImageFormatException) { } if (!hasMetadata) { shouldLoad = false; reason = "File is not a .NET assembly."; return; } var reader = file.GetMetadataReader(); var assemblyDefinition = reader.GetAssemblyDefinition(); if (!assemblyDefinition.PublicKey.IsNil) { var publicKey = reader.GetBlobBytes(assemblyDefinition.PublicKey); var publicKeyToken = GetPublicKeyToken(publicKey); if (IsRuntimeAssembly(publicKeyToken)) { shouldLoad = false; reason = "File is a .NET runtime assembly."; return; } } shouldLoad = true; reason = "File is a .NET assembly."; } } static byte[] GetPublicKeyToken(byte[] publicKey) { using (var sha1 = SHA1.Create()) { var hash = sha1.ComputeHash(publicKey); var publicKeyToken = new byte[8]; for (var i = 0; i < 8; i++) { publicKeyToken[i] = hash[hash.Length - (i + 1)]; } return publicKeyToken; } } public static bool IsRuntimeAssembly(byte[] publicKeyToken) { var tokenString = BitConverter.ToString(publicKeyToken).Replace("-", string.Empty).ToLowerInvariant(); //Compare token to known Microsoft tokens switch (tokenString) { case "b77a5c561934e089": case "7cec85d7bea7798e": case "b03f5f7f11d50a3a": case "31bf3856ad364e35": case "cc7b13ffcd2ddd51": case "adb9793829ddae60": return true; default: return false; } } } }
RadicalFx/Radical.Windows
src/Radical.Windows/Bootstrap/AssemblyValidator.cs
C#
mit
2,902
var amqp=require("amqplib"); amqp.connect('amqp://localhost').then(function(connection){ return connection.createChannel().then(function(ch){ var ex="logs"; ch.assertExchange(ex,'fanout',{durable:true}); var ok=ch.assertQueue('',{exclusive:true}) .then(function(q){ console.log("[x]Waiting for message in '%s' ",q.queue); return ch.bindQueue(q.queue,ex,''); }).then(function(q){ return ch.consume(q.queue,function(msg){ console.log("[x]Receiving message:'%s'",msg.content.toString()); },{noAck:true}); }); }) }).then(null,console.warn);
zhangmingkai4315/RabbitMQ-Nodejs
pub_sub/receive_logs.js
JavaScript
mit
569
#include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include <QString> #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #include <QUrl> #include <QTextDocument> // For Qt::escape #include <QAbstractItemView> #include <QApplication> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { // NovaCoin: check prefix if(uri.scheme() != QString("testfaucetcoin")) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; QList<QPair<QString, QString> > items = uri.queryItems(); for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert testfaucetcoin:// to testfaucetcoin: // // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host, // which will lower-case it (and thus invalidate the address). if(uri.startsWith("testfaucetcoin://")) { uri.replace(0, 12, "testfaucetcoin:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { QString escaped = Qt::escape(str); if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item QApplication::clipboard()->setText(selection.at(0).data(role).toString()); } } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = qApp->widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt>") && !Qt::mightBeRichText(tooltip)) { // Prefix <qt/> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt>" + HtmlEscape(tooltip, true) + "<qt/>"; widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "testfaucetcoin.lnk"; } bool GetStartOnSystemStartup() { // check for Bitcoin.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "testfaucetcoin.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a bitcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=testfaucetcoin\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #else // TODO: OSX startup stuff; see: // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("testfaucetcoin-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " testfaucetcoin-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("testfaucetcoin-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stdout, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil
testfaucetcoin/testfaucetcoin
src/qt/guiutil.cpp
C++
mit
13,417
<?php namespace Tests\App; use App\VCS\Git; use App\VCS\Tagged; use Illuminate\Filesystem\Filesystem; use Mockery; use App\VCS\Repository; use Symfony\Component\Process\Exception\ProcessFailedException; use Symfony\Component\Process\Process; class GitTest extends \TestCase { /** @var Mockery\MockInterface */ protected $repository; /** @var Mockery\MockInterface */ protected $filesystem; /** @var Mockery\MockInterface */ protected $version; /** @var Git */ protected $git; public function setUp() { parent::setUp(); $this->repository = Mockery::mock(Repository::class); $this->filesystem = Mockery::mock(Filesystem::class); $this->version = Mockery::mock(Tagged::class)->shouldIgnoreMissing(); $this->git = new Git($this->filesystem); } /** * @test */ public function canCloneRepository() { $path = uniqid(); $this->git = Mockery::mock(Git::class.'[temporaryPath]', [$this->filesystem]); $this->git->shouldAllowMockingProtectedMethods(); $this->git->shouldReceive('temporaryPath')->andReturn($path); $this->repository->shouldReceive('path')->andReturn($path); $this->repository->shouldReceive('setPath')->with($path)->once(); $this->repository->shouldReceive('sshUrl')->andReturn(uniqid()); // passing an empty string in place of a "command" that's normally passed $process = Mockery::mock(Process::class.'[setWorkingDirectory,run,isSuccessful]', ['']); $process->shouldReceive('setWorkingDirectory')->with($path)->once(); $process->shouldReceive('run')->once(); $process->shouldReceive('isSuccessful')->andReturnTrue(); app()->instance(Process::class, $process); $this->assertEquals($this->repository, $this->git->clone($this->repository, $this->version)); } /** * @test */ public function cloneRepositoryComplainsWhenFails() { $this->expectException(ProcessFailedException::class); $this->filesystem->shouldReceive('makeDirectory')->once(); $this->repository->shouldIgnoreMissing(); // passing an empty string in place of a "command" that's normally passed $process = Mockery::mock(Process::class.'[isSuccessful]', ['']); $process->shouldReceive('isSuccessful')->andReturnFalse(); $process->shouldIgnoreMissing(); app()->instance(Process::class, $process); $this->assertEquals($this->repository, $this->git->clone($this->repository, $this->version)); } /** * @test */ public function canCheckoutTag() { $path = uniqid(); $this->repository->shouldReceive('path')->andReturn($path); // passing an empty string in place of a "command" that's normally passed $process = Mockery::mock(Process::class.'[setWorkingDirectory,run,isSuccessful]', ['']); $process->shouldReceive('setWorkingDirectory')->with($path)->once(); $process->shouldReceive('run')->once(); $process->shouldReceive('isSuccessful')->andReturnTrue(); app()->instance(Process::class, $process); $this->assertTrue($this->git->checkoutTag($this->repository, $this->version)); } /** * @test */ public function checkoutTagComplainsWhenFails() { $this->expectException(ProcessFailedException::class); $this->repository->shouldIgnoreMissing(); // passing an empty string in place of a "command" that's normally passed $process = Mockery::mock(Process::class.'[isSuccessful]', ['']); $process->shouldReceive('isSuccessful')->andReturnFalse(); $process->shouldIgnoreMissing(); app()->instance(Process::class, $process); $this->assertTrue($this->git->checkoutTag($this->repository, $this->version)); } }
realpage/asset-publisher
tests/unit/VCS/GitTest.php
PHP
mit
3,894
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Topics.Radical.Model { /// <summary> /// Applied to properties asks that models skip this property when notifying property changes. /// </summary> [AttributeUsage( AttributeTargets.Property )] public sealed class SkipPropertyValidationAttribute : Attribute { } }
micdenny/radical
src/net35/Radical/Model/SkipPropertyValidationAttribute.cs
C#
mit
392
/* * SonarLint for Visual Studio * Copyright (C) 2016-2021 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System; using System.Collections.Generic; using System.IO.Abstractions.TestingHelpers; using System.Linq; using FluentAssertions; using Microsoft.VisualStudio.CodeAnalysis.RuleSets; namespace SonarLint.VisualStudio.Integration.UnitTests { internal class ConfigurableRuleSetSerializer : IRuleSetSerializer { private readonly Dictionary<string, RuleSet> savedRuleSets = new Dictionary<string, RuleSet>(StringComparer.OrdinalIgnoreCase); private readonly MockFileSystem fileSystem; private readonly Dictionary<string, int> ruleSetLoaded = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); public ConfigurableRuleSetSerializer(MockFileSystem fileSystem) { this.fileSystem = fileSystem; } #region IRuleSetFileSystem RuleSet IRuleSetSerializer.LoadRuleSet(string path) { this.savedRuleSets.TryGetValue(path, out RuleSet rs); this.ruleSetLoaded.TryGetValue(path, out int counter); this.ruleSetLoaded[path] = ++counter; rs?.Validate(); return rs; } void IRuleSetSerializer.WriteRuleSetFile(RuleSet ruleSet, string path) { if (!this.savedRuleSets.TryGetValue(path, out _)) { this.savedRuleSets[path] = ruleSet; } this.fileSystem.AddFile(path, new MockFileData("")); } #endregion IRuleSetFileSystem #region Test Helpers public IEnumerable<string> RegisteredRuleSets { get { return this.savedRuleSets.Keys; } } public void RegisterRuleSet(RuleSet ruleSet) { this.RegisterRuleSet(ruleSet, ruleSet.FilePath); } public void RegisterRuleSet(RuleSet ruleSet, string path) { this.savedRuleSets[path] = ruleSet; this.fileSystem.AddFile(path, new MockFileData("")); } public void ClearRuleSets() { foreach (var filePath in fileSystem.AllFiles) { fileSystem.RemoveFile(filePath); } savedRuleSets.Clear(); } public void AssertRuleSetExists(string path) { fileSystem.GetFile(path).Should().NotBe(null); } public void AssertRuleSetNotExists(string path) { fileSystem.GetFile(path).Should().Be(null); } public void AssertRuleSetsAreEqual(string ruleSetPath, RuleSet expectedRuleSet) { this.AssertRuleSetExists(ruleSetPath); RuleSet actualRuleSet = this.savedRuleSets[ruleSetPath]; actualRuleSet.Should().NotBeNull("Expected rule set to be written"); RuleSetAssert.AreEqual(expectedRuleSet, actualRuleSet); } public void AssertRuleSetsAreSame(string ruleSetPath, RuleSet expectedRuleSet) { this.AssertRuleSetExists(ruleSetPath); RuleSet actualRuleSet = this.savedRuleSets[ruleSetPath]; actualRuleSet.Should().Be(expectedRuleSet); } public void AssertRuleSetLoaded(string ruleSet, int expectedNumberOfTimes) { this.ruleSetLoaded.TryGetValue(ruleSet, out int actual); actual.Should().Be(expectedNumberOfTimes, "RuleSet {0} was loaded unexpected number of times", ruleSet); } #endregion Test Helpers } }
SonarSource-VisualStudio/sonarlint-visualstudio
src/TestInfrastructure/Framework/ConfigurableRuleSetSerializer.cs
C#
mit
4,356
package com.mdsol.mauth.proxy; import com.typesafe.config.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.UUID; public class ProxyConfig { private static final Logger logger = LoggerFactory.getLogger(ProxyConfig.class); public static final String V2_ONLY_SIGN_REQUESTS = "mauth.v2_only_sign_requests"; public static final String V2_ONLY_AUTHTICATE = "mauth.v2_only_authenticate"; private final int proxyPort; private final int bufferSizeInByes; private String privateKey; private final UUID appUuid; private boolean v2OnlySignRequests = false; private boolean v2OnlyAuthenticate = false; public ProxyConfig(Config config) { this( config.getInt("proxy.port"), config.getInt("proxy.buffer_size_in_bytes"), UUID.fromString(config.getString("app.uuid")), config.getString("app.private_key"), config.getBoolean(V2_ONLY_SIGN_REQUESTS), config.getBoolean(V2_ONLY_AUTHTICATE) ); } public ProxyConfig(int proxyPort, int bufferSizeInByes, UUID appUuid, String privateKey, boolean v2OnlySignRequests, boolean v2OnlyAuthenticate) { this.proxyPort = proxyPort; this.bufferSizeInByes = bufferSizeInByes; this.appUuid = appUuid; this.privateKey = privateKey; this.v2OnlySignRequests = v2OnlySignRequests; this.v2OnlyAuthenticate = v2OnlyAuthenticate; } public int getProxyPort() { return proxyPort; } public int getBufferSizeInByes() { return bufferSizeInByes; } public String getPrivateKey() { return privateKey; } public UUID getAppUuid() { return appUuid; } public boolean isV2OnlySignRequests() { return v2OnlySignRequests; } public boolean isV2OnlySignAuthenticate() { return v2OnlyAuthenticate; } }
mdsol/mauth-java-client
modules/mauth-proxy/src/main/java/com/mdsol/mauth/proxy/ProxyConfig.java
Java
mit
1,784
<?php class updatePitchDeck_m extends CI_Model{ function __construct(){ parent::__construct(); } function updateIdeaGen($data){ $sql = "update idea_genboard set problem = ? , people = ? , behavior = ? , solution = ? where idea_id = ?"; $query = $this->db->query($sql,array($data['problem'],$data['people'],$data['behavior'],$data['solution'],$data['idea_id'])); if($query){ $sql1 = "select * from ungen_pitchdeck where idea_id = ? "; $query1 = $this->db->query($sql1,array($data['idea_id'])); if($query1->num_rows()>0){ $row = $query1->row(); $session = array( 'ungen_id'=>$row->ungen_id ); $this->session->set_userdata($session); return true; } } } function updateBMC($data){ $sql = "update bmc set cust_segment = ? , cust_relationship = ? , channels = ? , value_proposition = ? , key_activities = ? , key_sources = ? , key_partners = ? , cost_structures = ? , revenue_streams = ? where bmc_id = ? "; $query = $this->db->query($sql,array($data['segment'],$data['relationship'],$data['channels'],$data['proposition'],$data['activities'],$data['resources'],$data['partners'],$data['structure'],$data['streams'],$data['bmc_id'])); if($query){ $session = array( 'bmcid'=>$data['bmc_id'] ); $this->session->set_tempdata($session); return true; } } function updateValueProp($data){ $sql = "update value_prop set wants = ? , needs = ? , fears = ? , benefits = ? , experience = ? , features = ? , company = ? , product = ? , ideal_cust = ? , substitutes = ? where valueprop_id = ? "; $query = $this->db->query($sql,array($data['wants'],$data['needs'],$data['fears'],$data['benefits'],$data['experience'],$data['features'],$data['company'],$data['product'],$data['ideal_cust'],$data['substitutes'],$data['valueprop_id'])); if($query){ $sql1 = "select * from ungen_pitchdeck where valueprop_id = ? "; $query1 = $this->db->query($sql1,array($data['valueprop_id'])); if($query1->num_rows()>0){ $row = $query1->row(); $session = array( 'ungen_id'=>$row->ungen_id ); $this->session->set_userdata($session); return true; } } } function updateValidationBoard($data){ $sql = "update validation_board set stage= ? , customer = ? , problem = ? , solution = ? , risk_assumpt = ? , solution_criteria = ? , results = ? , learnings = ? , customer2 = ? , problem2 = ? , solution2 = ? , risk_assumpt2 = ? , solution_criteria2 = ? , results2 = ? , learnings2 = ? , customer3 = ? , problem3 = ? , solution3 = ? , risk_assumpt3 = ? , solution_criteria3 = ? , results3 = ? , learnings3 = ? where valid_id = ?"; $query = $this->db->query($sql,array($data['stage'],$data['customer'],$data['problem'],$data['solution'],$data['risk_assumpt'],$data['solution_criteria'],$data['results'],$data['learnings'],$data['customer2'],$data['problem2'],$data['solution2'],$data['risk_assumpt2'],$data['solution_criteria2'],$data['results2'],$data['learnings2'],$data['customer3'],$data['problem3'],$data['solution3'],$data['risk_assumpt3'],$data['solution_criteria3'],$data['results3'],$data['learnings3'],$data['valid_id'])); if($query){ $sql1 = "select * from ungen_pitchdeck where valid_id = ? "; $query1 = $this->db->query($sql1,array($data['valid_id'])); if($query1->num_rows()>0){ $row = $query1->row(); $session = array( 'ungen_id'=>$row->ungen_id ); $this->session->set_userdata($session); return true; } } } } ?>
jLKisni/PitchItUp
application/modules/Web/models/updatePitchDeck_m.php
PHP
mit
3,710
#ifndef M3D_RANDOM_UTILS_H #define M3D_RANDOM_UTILS_H #include <stdlib.h> #include <math.h> namespace m3D { namespace utils { float ranf() { return ((float) rand()) / ((float) RAND_MAX); } float box_muller(float m, float s) { float x1, x2, w, y1; static float y2; static int use_last = 0; static int initialized_rand = 0; if (!initialized_rand) { #if BSD srandomdev(); #endif initialized_rand = 1; } if (use_last) /* use value from previous call */ { y1 = y2; use_last = 0; } else { do { x1 = 2.0 * ranf() - 1.0; x2 = 2.0 * ranf() - 1.0; w = x1 * x1 + x2 * x2; } while (w >= 1.0); w = sqrt((-2.0 * log(w)) / w); y1 = x1 * w; y2 = x2 * w; use_last = 1; } return ( m + y1 * s); } } } #endif
meteo-ubonn/meanie3D
src/utils/rand_utils.cpp
C++
mit
1,159
package co.navdeep.popmovies.tmdb.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Genre { @SerializedName("id") @Expose private Integer id; @SerializedName("name") @Expose private String name; /** * * @return * The id */ public Integer getId() { return id; } /** * * @param id * The id */ public void setId(Integer id) { this.id = id; } /** * * @return * The name */ public String getName() { return name; } /** * * @param name * The name */ public void setName(String name) { this.name = name; } }
navdeepsekhon/PopMovies
app/src/main/java/co/navdeep/popmovies/tmdb/model/Genre.java
Java
mit
778
#include <cstring> #include <occa/types/bits.hpp> #include <occa/types/primitive.hpp> #include <occa/internal/io.hpp> #include <occa/internal/utils/lex.hpp> #include <occa/internal/utils/string.hpp> namespace occa { primitive::primitive(const char *c) { *this = load(c); } primitive::primitive(const std::string &s) { const char *c = s.c_str(); *this = load(c); } primitive primitive::load(const char *&c, const bool includeSign) { bool loadedFormattedValue = false; bool unsigned_ = false; bool negative = false; bool decimal = false; bool float_ = false; int longs = 0; int digits = 0; const char *c0 = c; primitive p; const int cLength = strlen(c); if(cLength >= 4){ if (strncmp(c, "true", 4) == 0) { p = true; p.source = "true"; c += 4; return p; } } if(cLength >= 5){ if (strncmp(c, "false", 5) == 0) { p = false; p.source = "false"; c += 5; return p; } } if ((*c == '+') || (*c == '-')) { if (!includeSign) { return primitive(); } negative = (*c == '-'); ++c; lex::skipWhitespace(c); } if (*c == '0') { ++digits; ++c; const char C = uppercase(*c); if ((C == 'B') || (C == 'X')) { loadedFormattedValue = true; if (C == 'B') { p = primitive::loadBinary(++c, negative); } else if (C == 'X') { p = primitive::loadHex(++c, negative); } if (p.type & primitiveType::none) { c = c0; return primitive(); } } else { --c; } } if (!loadedFormattedValue) { while (true) { if (('0' <= *c) && (*c <= '9')) { ++digits; } else if (*c == '.') { decimal = true; } else { break; } ++c; } } if (!loadedFormattedValue && !digits) { c = c0; p.source = std::string(c0, c - c0); return p; } while(*c != '\0') { const char C = uppercase(*c); if (C == 'L') { ++longs; ++c; } else if (C == 'U') { unsigned_ = true; ++c; } else if (!loadedFormattedValue) { if (C == 'E') { primitive exp = primitive::load(++c); // Check if there was an 'F' in exp decimal = true; float_ = (exp.type & primitiveType::isFloat); break; } else if (C == 'F') { float_ = true; ++c; } else { break; } } else { break; } } if (loadedFormattedValue) { // Hex and binary only handle U, L, and LL if (longs == 0) { if (unsigned_) { p = p.to<uint32_t>(); } else { p = p.to<int32_t>(); } } else if (longs >= 1) { if (unsigned_) { p = p.to<uint64_t>(); } else { p = p.to<int64_t>(); } } } else { // Handle the multiple other formats with normal digits if (decimal || float_) { if (float_) { p = (float) occa::parseFloat(std::string(c0, c - c0)); } else { p = (double) occa::parseDouble(std::string(c0, c - c0)); } } else { uint64_t value_ = parseInt(std::string(c0, c - c0)); if (longs == 0) { if (unsigned_) { p = (uint32_t) value_; } else { p = (int32_t) value_; } } else if (longs >= 1) { if (unsigned_) { p = (uint64_t) value_; } else { p = (int64_t) value_; } } } } p.source = std::string(c0, c - c0); return p; } primitive primitive::load(const std::string &s, const bool includeSign) { const char *c = s.c_str(); return load(c, includeSign); } primitive primitive::loadBinary(const char *&c, const bool isNegative) { const char *c0 = c; uint64_t value_ = 0; while (*c == '0' || *c == '1') { value_ = (value_ << 1) | (*c - '0'); ++c; } if (c == c0) { return primitive(); } const int bits = c - c0 + isNegative; if (bits < 8) { return isNegative ? primitive((int8_t) -value_) : primitive((uint8_t) value_); } else if (bits < 16) { return isNegative ? primitive((int16_t) -value_) : primitive((uint16_t) value_); } else if (bits < 32) { return isNegative ? primitive((int32_t) -value_) : primitive((uint32_t) value_); } else { return isNegative ? primitive((int64_t) -value_) : primitive((uint64_t) value_); } } primitive primitive::loadHex(const char *&c, const bool isNegative) { const char *c0 = c; uint64_t value_ = 0; while (true) { const char C = uppercase(*c); if (('0' <= C) && (C <= '9')) { value_ = (value_ << 4) | (C - '0'); } else if (('A' <= C) && (C <= 'F')) { value_ = (value_ << 4) | (10 + C - 'A'); } else { break; } ++c; } if (c == c0) { return primitive(); } const int bits = 4*(c - c0) + isNegative; if (bits < 8) { return isNegative ? primitive((int8_t) -value_) : primitive((uint8_t) value_); } else if (bits < 16) { return isNegative ? primitive((int16_t) -value_) : primitive((uint16_t) value_); } else if (bits < 32) { return isNegative ? primitive((int32_t) -value_) : primitive((uint32_t) value_); } else { return isNegative ? primitive((int64_t) -value_) : primitive((uint64_t) value_); } } std::string primitive::toString() const { if (source.size()) { return source; } std::string str; switch (type) { case primitiveType::bool_ : str = (value.bool_ ? "true" : "false"); break; case primitiveType::uint8_ : str = occa::toString((uint64_t) value.uint8_); break; case primitiveType::uint16_ : str = occa::toString((uint64_t) value.uint16_); break; case primitiveType::uint32_ : str = occa::toString((uint64_t) value.uint32_); break; case primitiveType::uint64_ : str = occa::toString((uint64_t) value.uint64_); break; case primitiveType::int8_ : str = occa::toString((int64_t) value.int8_); break; case primitiveType::int16_ : str = occa::toString((int64_t) value.int16_); break; case primitiveType::int32_ : str = occa::toString((int64_t) value.int32_); break; case primitiveType::int64_ : str = occa::toString((int64_t) value.int64_); break; case primitiveType::float_ : str = occa::toString(value.float_); break; case primitiveType::double_ : str = occa::toString(value.double_); break; case primitiveType::none : default: return ""; break; } if (type & (primitiveType::uint64_ | primitiveType::int64_)) { str += 'L'; } return str; } //---[ Misc Methods ]----------------- uint64_t primitive::sizeof_() const { switch(type) { case primitiveType::bool_ : return sizeof(bool); case primitiveType::uint8_ : return sizeof(uint8_t); case primitiveType::uint16_ : return sizeof(uint16_t); case primitiveType::uint32_ : return sizeof(uint32_t); case primitiveType::uint64_ : return sizeof(uint64_t); case primitiveType::int8_ : return sizeof(int8_t); case primitiveType::int16_ : return sizeof(int16_t); case primitiveType::int32_ : return sizeof(int32_t); case primitiveType::int64_ : return sizeof(int64_t); case primitiveType::float_ : return sizeof(float); case primitiveType::double_ : return sizeof(double); case primitiveType::ptr : return sizeof(void*); default: return 0; } } //==================================== //---[ Unary Operators ]-------------- primitive primitive::not_(const primitive &p) { switch(p.type) { case primitiveType::bool_ : return primitive(!p.value.bool_); case primitiveType::int8_ : return primitive(!p.value.int8_); case primitiveType::uint8_ : return primitive(!p.value.uint8_); case primitiveType::int16_ : return primitive(!p.value.int16_); case primitiveType::uint16_ : return primitive(!p.value.uint16_); case primitiveType::int32_ : return primitive(!p.value.int32_); case primitiveType::uint32_ : return primitive(!p.value.uint32_); case primitiveType::int64_ : return primitive(!p.value.int64_); case primitiveType::uint64_ : return primitive(!p.value.uint64_); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator ! to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator ! to double type"); break; default: ; } return primitive(); } primitive primitive::positive(const primitive &p) { switch(p.type) { case primitiveType::bool_ : return primitive(+p.value.bool_); case primitiveType::int8_ : return primitive(+p.value.int8_); case primitiveType::uint8_ : return primitive(+p.value.uint8_); case primitiveType::int16_ : return primitive(+p.value.int16_); case primitiveType::uint16_ : return primitive(+p.value.uint16_); case primitiveType::int32_ : return primitive(+p.value.int32_); case primitiveType::uint32_ : return primitive(+p.value.uint32_); case primitiveType::int64_ : return primitive(+p.value.int64_); case primitiveType::uint64_ : return primitive(+p.value.uint64_); case primitiveType::float_ : return primitive(+p.value.float_); case primitiveType::double_ : return primitive(+p.value.double_); default: ; } return primitive(); } primitive primitive::negative(const primitive &p) { switch(p.type) { case primitiveType::bool_ : return primitive(-p.value.bool_); case primitiveType::int8_ : return primitive(-p.value.int8_); case primitiveType::uint8_ : return primitive(-p.value.uint8_); case primitiveType::int16_ : return primitive(-p.value.int16_); case primitiveType::uint16_ : return primitive(-p.value.uint16_); case primitiveType::int32_ : return primitive(-p.value.int32_); case primitiveType::uint32_ : return primitive(-p.value.uint32_); case primitiveType::int64_ : return primitive(-p.value.int64_); case primitiveType::uint64_ : return primitive(-p.value.uint64_); case primitiveType::float_ : return primitive(-p.value.float_); case primitiveType::double_ : return primitive(-p.value.double_); default: ; } return primitive(); } primitive primitive::tilde(const primitive &p) { switch(p.type) { case primitiveType::bool_ : return primitive(!p.value.bool_); case primitiveType::int8_ : return primitive(~p.value.int8_); case primitiveType::uint8_ : return primitive(~p.value.uint8_); case primitiveType::int16_ : return primitive(~p.value.int16_); case primitiveType::uint16_ : return primitive(~p.value.uint16_); case primitiveType::int32_ : return primitive(~p.value.int32_); case primitiveType::uint32_ : return primitive(~p.value.uint32_); case primitiveType::int64_ : return primitive(~p.value.int64_); case primitiveType::uint64_ : return primitive(~p.value.uint64_); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator ~ to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator ~ to double type"); break; default: ; } return primitive(); } primitive& primitive::leftIncrement(primitive &p) { switch(p.type) { case primitiveType::bool_ : OCCA_FORCE_ERROR("Cannot apply operator ++ to bool type"); break; case primitiveType::int8_ : ++p.value.int8_; return p; case primitiveType::uint8_ : ++p.value.uint8_; return p; case primitiveType::int16_ : ++p.value.int16_; return p; case primitiveType::uint16_ : ++p.value.uint16_; return p; case primitiveType::int32_ : ++p.value.int32_; return p; case primitiveType::uint32_ : ++p.value.uint32_; return p; case primitiveType::int64_ : ++p.value.int64_; return p; case primitiveType::uint64_ : ++p.value.uint64_; return p; case primitiveType::float_ : ++p.value.float_; return p; case primitiveType::double_ : ++p.value.double_; return p; default: ; } return p; } primitive& primitive::leftDecrement(primitive &p) { switch(p.type) { case primitiveType::bool_ : OCCA_FORCE_ERROR("Cannot apply operator -- to bool type"); break; case primitiveType::int8_ : --p.value.int8_; return p; case primitiveType::uint8_ : --p.value.uint8_; return p; case primitiveType::int16_ : --p.value.int16_; return p; case primitiveType::uint16_ : --p.value.uint16_; return p; case primitiveType::int32_ : --p.value.int32_; return p; case primitiveType::uint32_ : --p.value.uint32_; return p; case primitiveType::int64_ : --p.value.int64_; return p; case primitiveType::uint64_ : --p.value.uint64_; return p; case primitiveType::float_ : --p.value.float_; return p; case primitiveType::double_ : --p.value.double_; return p; default: ; } return p; } primitive primitive::rightIncrement(primitive &p) { primitive oldP = p; switch(p.type) { case primitiveType::bool_ : OCCA_FORCE_ERROR("Cannot apply operator ++ to bool type"); break; case primitiveType::int8_ : p.value.int8_++; return oldP; case primitiveType::uint8_ : p.value.uint8_++; return oldP; case primitiveType::int16_ : p.value.int16_++; return oldP; case primitiveType::uint16_ : p.value.uint16_++; return oldP; case primitiveType::int32_ : p.value.int32_++; return oldP; case primitiveType::uint32_ : p.value.uint32_++; return oldP; case primitiveType::int64_ : p.value.int64_++; return oldP; case primitiveType::uint64_ : p.value.uint64_++; return oldP; case primitiveType::float_ : p.value.float_++; return oldP; case primitiveType::double_ : p.value.double_++; return oldP; default: ; } return oldP; } primitive primitive::rightDecrement(primitive &p) { primitive oldP = p; switch(p.type) { case primitiveType::bool_ : OCCA_FORCE_ERROR("Cannot apply operator -- to bool type"); break; case primitiveType::int8_ : p.value.int8_--; return oldP; case primitiveType::uint8_ : p.value.uint8_--; return oldP; case primitiveType::int16_ : p.value.int16_--; return oldP; case primitiveType::uint16_ : p.value.uint16_--; return oldP; case primitiveType::int32_ : p.value.int32_--; return oldP; case primitiveType::uint32_ : p.value.uint32_--; return oldP; case primitiveType::int64_ : p.value.int64_--; return oldP; case primitiveType::uint64_ : p.value.uint64_--; return oldP; case primitiveType::float_ : p.value.float_--; return oldP; case primitiveType::double_ : p.value.double_--; return oldP; default: ; } return oldP; } //==================================== //---[ Boolean Operators ]------------ primitive primitive::lessThan(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() < b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() < b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() < b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() < b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() < b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() < b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() < b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() < b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() < b.to<uint64_t>()); case primitiveType::float_ : return primitive(a.to<float>() < b.to<float>()); case primitiveType::double_ : return primitive(a.to<double>() < b.to<double>()); default: ; } return primitive(); } primitive primitive::lessThanEq(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() <= b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() <= b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() <= b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() <= b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() <= b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() <= b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() <= b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() <= b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() <= b.to<uint64_t>()); case primitiveType::float_ : return primitive(a.to<float>() <= b.to<float>()); case primitiveType::double_ : return primitive(a.to<double>() <= b.to<double>()); default: ; } return primitive(); } primitive primitive::equal(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() == b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() == b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() == b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() == b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() == b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() == b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() == b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() == b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() == b.to<uint64_t>()); case primitiveType::float_ : return primitive(areBitwiseEqual(a.value.float_, b.value.float_)); case primitiveType::double_ : return primitive(areBitwiseEqual(a.value.double_, b.value.double_)); default: ; } return primitive(); } primitive primitive::compare(const primitive &a, const primitive &b) { if (lessThan(a, b)) { return -1; } return greaterThan(a, b) ? 1 : 0; } primitive primitive::notEqual(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() != b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() != b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() != b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() != b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() != b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() != b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() != b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() != b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() != b.to<uint64_t>()); case primitiveType::float_ : return primitive(!areBitwiseEqual(a.value.float_, b.value.float_)); case primitiveType::double_ : return primitive(!areBitwiseEqual(a.value.double_, b.value.double_)); default: ; } return primitive(); } primitive primitive::greaterThanEq(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() >= b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() >= b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() >= b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() >= b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() >= b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() >= b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() >= b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() >= b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() >= b.to<uint64_t>()); case primitiveType::float_ : return primitive(a.to<float>() >= b.to<float>()); case primitiveType::double_ : return primitive(a.to<double>() >= b.to<double>()); default: ; } return primitive(); } primitive primitive::greaterThan(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() > b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() > b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() > b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() > b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() > b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() > b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() > b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() > b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() > b.to<uint64_t>()); case primitiveType::float_ : return primitive(a.to<float>() > b.to<float>()); case primitiveType::double_ : return primitive(a.to<double>() > b.to<double>()); default: ; } return primitive(); } primitive primitive::and_(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() && b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() && b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() && b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() && b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() && b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() && b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() && b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() && b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() && b.to<uint64_t>()); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator && to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator && to double type"); break; default: ; } return primitive(); } primitive primitive::or_(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() || b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() || b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() || b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() || b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() || b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() || b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() || b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() || b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() || b.to<uint64_t>()); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator || to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator || to double type"); break; default: ; } return primitive(); } //==================================== //---[ Binary Operators ]------------- primitive primitive::mult(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() * b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() * b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() * b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() * b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() * b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() * b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() * b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() * b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() * b.to<uint64_t>()); case primitiveType::float_ : return primitive(a.to<float>() * b.to<float>()); case primitiveType::double_ : return primitive(a.to<double>() * b.to<double>()); default: ; } return primitive(); } primitive primitive::add(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() + b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() + b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() + b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() + b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() + b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() + b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() + b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() + b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() + b.to<uint64_t>()); case primitiveType::float_ : return primitive(a.to<float>() + b.to<float>()); case primitiveType::double_ : return primitive(a.to<double>() + b.to<double>()); default: ; } return primitive(); } primitive primitive::sub(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() - b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() - b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() - b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() - b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() - b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() - b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() - b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() - b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() - b.to<uint64_t>()); case primitiveType::float_ : return primitive(a.to<float>() - b.to<float>()); case primitiveType::double_ : return primitive(a.to<double>() - b.to<double>()); default: ; } return primitive(); } primitive primitive::div(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() / b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() / b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() / b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() / b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() / b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() / b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() / b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() / b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() / b.to<uint64_t>()); case primitiveType::float_ : return primitive(a.to<float>() / b.to<float>()); case primitiveType::double_ : return primitive(a.to<double>() / b.to<double>()); default: ; } return primitive(); } primitive primitive::mod(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() % b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() % b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() % b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() % b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() % b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() % b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() % b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() % b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() % b.to<uint64_t>()); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator % to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator % to double type"); break; default: ; } return primitive(); } primitive primitive::bitAnd(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() & b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() & b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() & b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() & b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() & b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() & b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() & b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() & b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() & b.to<uint64_t>()); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator & to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator & to double type"); break; default: ; } return primitive(); } primitive primitive::bitOr(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() | b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() | b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() | b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() | b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() | b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() | b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() | b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() | b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() | b.to<uint64_t>()); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator | to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator | to double type"); break; default: ; } return primitive(); } primitive primitive::xor_(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() ^ b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() ^ b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() ^ b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() ^ b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() ^ b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() ^ b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() ^ b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() ^ b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() ^ b.to<uint64_t>()); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator ^ to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator ^ to double type"); break; default: ; } return primitive(); } primitive primitive::rightShift(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() >> b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() >> b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() >> b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() >> b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() >> b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() >> b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() >> b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() >> b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() >> b.to<uint64_t>()); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator >> to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator >> to double type"); break; default: ; } return primitive(); } primitive primitive::leftShift(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() << b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() << b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() << b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() << b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() << b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() << b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() << b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() << b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() << b.to<uint64_t>()); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator << to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator << to double type"); break; default: ; } return primitive(); } //==================================== //---[ Assignment Operators ]--------- primitive& primitive::assign(primitive &a, const primitive &b) { a = b; return a; } primitive& primitive::multEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() * b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() * b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() * b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() * b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() * b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() * b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() * b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() * b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() * b.to<uint64_t>()); break; case primitiveType::float_ : a = (a.to<float>() * b.to<float>()); break; case primitiveType::double_ : a = (a.to<double>() * b.to<double>()); break; default: ; } return a; } primitive& primitive::addEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() + b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() + b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() + b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() + b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() + b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() + b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() + b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() + b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() + b.to<uint64_t>()); break; case primitiveType::float_ : a = (a.to<float>() + b.to<float>()); break; case primitiveType::double_ : a = (a.to<double>() + b.to<double>()); break; default: ; } return a; } primitive& primitive::subEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() - b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() - b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() - b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() - b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() - b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() - b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() - b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() - b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() - b.to<uint64_t>()); break; case primitiveType::float_ : a = (a.to<float>() - b.to<float>()); break; case primitiveType::double_ : a = (a.to<double>() - b.to<double>()); break; default: ; } return a; } primitive& primitive::divEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() / b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() / b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() / b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() / b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() / b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() / b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() / b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() / b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() / b.to<uint64_t>()); break; case primitiveType::float_ : a = (a.to<float>() / b.to<float>()); break; case primitiveType::double_ : a = (a.to<double>() / b.to<double>()); break; default: ; } return a; } primitive& primitive::modEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() % b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() % b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() % b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() % b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() % b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() % b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() % b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() % b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() % b.to<uint64_t>()); break; case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator % to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator % to double type"); break; default: ; } return a; } primitive& primitive::bitAndEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() & b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() & b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() & b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() & b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() & b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() & b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() & b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() & b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() & b.to<uint64_t>()); break; case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator & to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator & to double type"); break; default: ; } return a; } primitive& primitive::bitOrEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() | b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() | b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() | b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() | b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() | b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() | b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() | b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() | b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() | b.to<uint64_t>()); break; case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator | to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator | to double type"); break; default: ; } return a; } primitive& primitive::xorEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() ^ b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() ^ b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() ^ b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() ^ b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() ^ b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() ^ b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() ^ b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() ^ b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() ^ b.to<uint64_t>()); break; case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator ^ to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator ^ to double type"); break; default: ; } return a; } primitive& primitive::rightShiftEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() >> b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() >> b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() >> b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() >> b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() >> b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() >> b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() >> b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() >> b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() >> b.to<uint64_t>()); break; case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator >> to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator >> to double type"); break; default: ; } return a; } primitive& primitive::leftShiftEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() << b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() << b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() << b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() << b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() << b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() << b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() << b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() << b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() << b.to<uint64_t>()); break; case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator << to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator << to double type"); break; default: ; } return a; } //==================================== io::output& operator << (io::output &out, const primitive &p) { out << p.toString(); return out; } }
libocca/occa
src/types/primitive.cpp
C++
mit
49,514
/** * pax * https://github.com/reekoheek/pax * * Copyright (c) 2013 PT Sagara Xinix Solusitama * Licensed under the MIT license. * https://github.com/reekoheek/pax/blob/master/LICENSE * * Composer command * */ var spawn = require('child_process').spawn, d = require('simply-deferred'); module.exports = function(pax, args, opts) { var deferred = d.Deferred(), packageFile = 'package.json'; var found = require('matchdep').filterDev('grunt-' + args[0], process.cwd() + '/' + packageFile); if (found.length <= 0) { var insDep = spawn('npm', ['install', 'grunt-' + args[0], '--save-dev'], {stdio: 'inherit'}); insDep.on('close', function(code) { if (code > 0) { deferred.reject(new Error('NPM error occured.')); } else { deferred.resolve(); } }); } else { pax.log.info(args[0], 'already exists.'); deferred.resolve(); } return deferred.promise(); };
krisanalfa/pax
lib/commands/grunt/add.js
JavaScript
mit
1,004
/* globals require module */ const modelRegistrator = require("./utils/model-registrator"); module.exports = modelRegistrator.register("Superhero", { name: { type: String, required: true }, secretIdentity: { type: String, required: true }, alignment: { type: String, required: true }, story: { type: String, required: true }, imageUrl: { type: String, required: true }, fractions: [{}], powers: [{}], city: {}, country: {}, planet: {}, user: {} });
Minkov/Superheroes-Universe
models/superhero-model.js
JavaScript
mit
594
var engine = require('../data.js'); var collection = engine.getCollection('posts'); var requiredKeys = ['title', 'markdown', 'body', 'slug', 'createdAt']; var requiredMessage = 'You must provide at least these keys: ' + requiredKeys.join(', '); function _dummyIndex(err, indexName) { if (err) { throw new Error(err); } console.log('Created', indexName); } collection.ensureIndex('slug', {unique: true}, _dummyIndex); collection.ensureIndex({createdAt: -1}, {w: 1}, _dummyIndex); collection.ensureIndex({tags: 1}, {_tiarr: true}, _dummyIndex); module.exports.list = listPosts; module.exports.listByDate = listPostsByDate; module.exports.listByTag = listPostsByTag; module.exports.get = getPost; module.exports.upsert = upsertPost; module.exports.create = createPost; module.exports.update = updatePost; module.exports.remove = removePost; module.exports.addComment = addComment; function dateLimit(year, month) { var MIN_MONTH = 1; var MAX_MONTH = 12; var currDate = new Date(); var hasMonth = Number.isFinite(month); var upper, lower; year = year || currDate.getFullYear(); month = month || currDate.getMonth(); if (hasMonth) { lower = year + '-' + month + '-1'; if (month + 1 > MAX_MONTH) { upper = (year + 1) + '-1-1'; } else { upper = year + '-' + (month + 1) + '-1'; } } else { lower = year + '-1-1'; upper = (year + 1) + '-1-1'; } return [new Date(Date.parse(lower)), new Date(Date.parse(upper))]; } function clone(original, edited) { var properties = ['title', 'body', 'markdown', 'tags']; properties.forEach(function (key) { original[key] = edited[key]; }); return original; } function validate(data) { var dataKeys = Object.keys(data); var hasKeys = requiredKeys.map(function (key) { return dataKeys.indexOf(key) > -1; }).reduce(function (accum, value) { return accum && value; }); return hasKeys; } function listPosts(options) { var page = options.page || 0; // posts per page var limit = options.limit || 5; // skip how many posts var skip = limit * page; collection.find( {}, { limit: limit, skip: skip, sort: {createdAt: -1} }, options.callback ); } function listPostsByTag(options) { collection.find( {tags: options.tag}, options.callback ); } function listPostsByDate(options) { var limits = dateLimit(options.year, options.month); collection.find( {publishAt: {$gt: limits[0], $lt: limits[1]}}, options.callback ); } function getPost(options) { collection.findOne({slug: options.slug}, options.callback); } function upsertPost(options) { collection.update( {slug: options.slug}, options.data, {upsert: true}, options.callback ); } function createPost(options) { if (!validate(options.data)) { return options.callback(new Error(requiredMessage)); } collection.insert(options.data, options.callback); } function updatePost(options) { getPost({ slug: options.slug, callback: function retrieved(err, item) { collection.update( {slug: options.slug}, clone(item, options.data), options.callback ); } }); } function removePost(options) { collection.remove({slug: options.slug}, options.callback); } function addComment(options) { getPost({ slug: options.slug, callback: function retrieved(err, item) { if (!item.comments) { item.comments = []; } item.comments.push(options.comment); item.comments = item.comments.sort(function sortByDate(a, b) { return b.createdAt.valueOf() - a.createdAt.valueOf(); }); collection.update( {slug: options.slug}, item, options.callback ); } }); }
joaodubas/blog
lib/data-post/index.js
JavaScript
mit
3,760
package edu.psu.sweng500.emrms.service; import edu.psu.sweng500.emrms.application.ApplicationSessionHelper; import edu.psu.sweng500.emrms.mappers.ChartingMapper; import edu.psu.sweng500.emrms.model.HAuditRecord; import edu.psu.sweng500.emrms.model.HProblem; import edu.psu.sweng500.emrms.util.PersonPatientUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service("manageProblemService") public class ManageProblemServiceImpl implements ManageProblemService{ @Autowired private ChartingMapper chartingMapper; @Autowired private AuditEventService auditEventService; @Autowired private PersonPatientUtils patientUtils; @Autowired private ApplicationSessionHelper sessionHelper; public void setChartingMapper(ChartingMapper chartingMapper) { this.chartingMapper = chartingMapper; } @Override public int AddProblem(HProblem problem) { chartingMapper.addProblem(problem); HAuditRecord auditRecord = new HAuditRecord(); auditRecord.setEventName("Add Problem"); auditRecord.setUserId(sessionHelper.getPhysicianName()); auditRecord.setPolicyId(17); auditRecord.setPatient_ObjectID(problem.getPatientID()); auditRecord.setPatientName(patientUtils.getPatientName(problem.getPatientID())); auditRecord.setEncounter_ObjectID(problem.getEncObjectId()); auditEventService.auditEvent(auditRecord); return 0; } @Override public int ReviseProblem(HProblem problem) { chartingMapper.reviseProblem(problem); HAuditRecord auditRecord = new HAuditRecord(); auditRecord.setEventName("Revise Problem"); auditRecord.setUserId(sessionHelper.getPhysicianName()); auditRecord.setPolicyId(18); auditRecord.setPatient_ObjectID(problem.getPatientID()); auditRecord.setPatientName(patientUtils.getPatientName(problem.getPatientID())); auditRecord.setEncounter_ObjectID(problem.getEncObjectId()); auditEventService.auditEvent(auditRecord); return 0; } @Override public int DeleteProblem(HProblem problem) { chartingMapper.deleteProblem(problem); HAuditRecord auditRecord = new HAuditRecord(); auditRecord.setEventName("Delete Problem"); auditRecord.setUserId(sessionHelper.getPhysicianName()); auditRecord.setPolicyId(22); auditRecord.setPatient_ObjectID(problem.getPatientID()); auditRecord.setPatientName(patientUtils.getPatientName(problem.getPatientID())); auditRecord.setEncounter_ObjectID(problem.getEncObjectId()); auditEventService.auditEvent(auditRecord); return 0; } @Override public List<HProblem> GetProblemsList(int patientObjId, int encObjId) { return chartingMapper.getPatientProblemList(patientObjId,encObjId); } }
Nilbog21/EMRMS
src/main/java/edu/psu/sweng500/emrms/service/ManageProblemServiceImpl.java
Java
mit
2,947
#include "world/Obstacle.h" #include <math.h> using namespace manip_core; using namespace matrices; using namespace Eigen; Obstacle::Obstacle(const Vector3& p1, const Vector3& p2, const Vector3& p3, bool donttouch) : p1_(p1) , p2_(p2) , p3_(p3) , p4_(p1+ (p3 - p2)) , u_(p3-p1) , v_(p2-p1) , n_(u_.cross(v_)) , donttouch_(donttouch) ,onlyThreePoints_(true) { InitObstacle(); } Obstacle::Obstacle(const Vector3& p1, const Vector3& p2, const Vector3& p3, const Vector3& p4, bool donttouch) : p1_(p1) , p2_(p2) , p3_(p3) , p4_(p4) , u_(p3-p4) , v_(p1-p4) , n_(u_.cross(v_)) , donttouch_(donttouch) , onlyThreePoints_(false) { InitObstacle(); } void Obstacle::InitObstacle() { Vector3 normal = n_; a_ = (float)(normal.x()); b_ = (float)(normal.y()); c_ = (float)(normal.z()); //if (c_ < 0) c_ = -c_; norm_ = (float)(normal.norm()); normsquare_ = norm_ * norm_; d_ = (float)(-(a_ * p1_.x() + b_ * p1_.y() + c_ * p1_.z())); center_ = p1_ + ((p4_ - p1_) + (p2_ - p1_)) / 2 ; basis_ = Matrix4::Zero(); Vector3 x = (p3_ - p4_); x.normalize(); Vector3 y = (p1_ - p4_); y.normalize(); normal.normalize(); basis_.block(0,0,3,1) = x; basis_.block(0,1,3,1) = y; basis_.block(0,2,3,1) = normal; basis_.block(0,3,3,1) = p4_; basis_(3,3) = 1; basisInverse_ = basis_.inverse(); w_ = (float)((p3_ - p4_).norm()); h_ = (float)((p1_ - p4_).norm()); /*triangle1_ = tree::MakeTriangle(p1, p2, p3); triangle2_ = tree::MakeTriangle(p1, p4, p3);*/ } Obstacle::~Obstacle() { // NOTHING } numeric Obstacle::Distance(const Vector3& point, Vector3& getCoordinates) const { // http://fr.wikipedia.org/wiki/Distance_d%27un_point_%C3%A0_un_plan numeric lambda = - ((a_ * point.x() + b_ * point.y() + c_ * point.z() + d_) / normsquare_); getCoordinates(0) = lambda * a_ + point.x(); getCoordinates(1) = lambda * b_ + point.y(); getCoordinates(2) = lambda * c_ + point.z(); return (abs(lambda) * norm_); } bool Obstacle::IsAbove(const matrices::Vector3& point) const { Vector3 nNormal = n_; nNormal.normalize(); Vector3 projection; numeric distance = Distance(point, projection); return (point - ( projection + distance * nNormal )).norm() < 0.000000001; } const matrices::Vector3 Obstacle::ProjectUp(const matrices::Vector3& point) const// projects a points onto obstacle plan and rises it up a little { matrices::Vector3 res = matrices::matrix4TimesVect3(basisInverse_, point); matrices::Vector3 nNormal = n_; nNormal.normalize(); res(2) = nNormal(2) * 0.1; return matrices::matrix4TimesVect3(basis_, res); } //bool Obstacle::ContainsPlanar(const Vector3& point) const //{ // double xc, yc, zc; // xc = point(0); yc = point(1); // return ((xc > 0 && xc < w_) && // (yc > 0 && yc < h_) ; //}
stonneau/manipulabilityreduced
src/world/Obstacle.cpp
C++
mit
2,741
package com.hps.wizard.sample.states; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.TextView; import com.hps.wizard.StateFragment; import com.hps.wizard.AbstractWizardActivity; import com.hps.wizard.sample.R; /** * This fragment is a state fragment which accepts two possible next states and a label. It then moves forward to the appropriate state based on user selection. */ public class AreYouSure extends StateFragment { public static final String ARE_YOU_SURE_TEXT = "text"; public static final String YES_STATE = "yesState"; public static final String NO_STATE = "noState"; private static final String CHECKED_BUTTON_ID = "checkedId"; private RadioButton yes, no; private RadioGroup choiceGroup; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_state_are_your_sure, container, false); Bundle args = getArguments(); String message = args.getString(ARE_YOU_SURE_TEXT); TextView tv = (TextView) v.findViewById(R.id.textView); tv.setText(message); yes = (RadioButton) v.findViewById(R.id.yes); no = (RadioButton) v.findViewById(R.id.no); choiceGroup = (RadioGroup) v.findViewById(R.id.choiceGroup); /** * Set up a listener to enable or disable the next button. */ OnCheckedChangeListener thingListener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (getWizardActivity() != null) { getWizardActivity().enableButton(AbstractWizardActivity.NEXT_BUTTON, group.getCheckedRadioButtonId() != -1, AreYouSure.this); } } }; choiceGroup.setOnCheckedChangeListener(thingListener); /** * Check the correct radio button if we're rebuilding the screen after orientation change. */ if (getArguments() != null) { int checkedId = getArguments().getInt(CHECKED_BUTTON_ID, -1); if (checkedId != -1) { choiceGroup.check(checkedId); } } return v; } @Override public String getTitle() { return "Are You Sure?"; } @Override public String getPreviousButtonLabel() { return getWizardActivity().getString(R.string.wizard_previous); } @Override public boolean canGoForward() { /** * We can go forward only if the fragment has been created and the user has selected yes or no. */ return yes != null && (yes.isChecked() || no.isChecked()); } @SuppressWarnings("unchecked") @Override public StateDefinition getNextState() { Bundle args = getArguments(); Class<? extends StateFragment> nextState; /** * Select the correct state based on which radio button is checked. */ if (yes.isChecked()) { nextState = (Class<? extends StateFragment>) args.getSerializable(YES_STATE); } else { nextState = (Class<? extends StateFragment>) args.getSerializable(NO_STATE); } return new StateDefinition(nextState, null); } @Override public Bundle getSavedInstanceState() { Bundle bundle = getBundleToSave(); /** * Store off which radio button was checked (if any). */ if (choiceGroup != null) { bundle.putInt(CHECKED_BUTTON_ID, choiceGroup.getCheckedRadioButtonId()); } return bundle; } }
HeartlandPaymentSystems/Android-Wizard-Framework
WizardSample/src/com/hps/wizard/sample/states/AreYouSure.java
Java
mit
3,465
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.aspose.imaging.examples; /** * * @author mfazi */ public final class Assert { public static void areEqual(Object left, Object right) { if (!left.equals(right)) throw new AssertionError(left + " != " + right); } public static void areEqual(Object left, Object right, String msg) { if (!left.equals(right)) throw new AssertionError(msg); } public static void areEqual(long left, long right, String msg) { if (left != right) throw new AssertionError(left + " != " + right); } public static void areEqual(float left, float right, float epsilon) { assert Math.abs(left - right) < epsilon; } public static void areNotEqual(Object left, Object right) { assert !left.equals(right); } public static void assertTrue(boolean value) { if (!value) throw new AssertionError("value is false"); } public static void assertTrue(boolean value, String msg) { assert value : msg; } }
aspose-imaging/Aspose.Imaging-for-Java
Examples/src/main/java/com/aspose/imaging/examples/Assert.java
Java
mit
1,281
using System; using System.IO; using NUnit.Framework; namespace EventStreams.Persistence.FileSystem { using Resources; using Serialization.Events; using Streams; [TestFixture] public class FileSystemPersistenceStrategyTests { private readonly RepositoryHierarchy _repositoryPath = new RepositoryHierarchy(AppDomain.CurrentDomain.BaseDirectory); [Test] public void Given_first_set_when_written_to_disk_and_when_read_back_in_then_content_is_as_expected() { var identity = new Guid("E34900D6-6C63-4066-988F-DCEC25B482FA"); var filename = _repositoryPath.For(identity); File.Delete(filename); var fspe = new FileSystemPersistenceStrategy(_repositoryPath, EventReaderWriterPair.Null); fspe.Store(identity, MockEventStreams.First); Assert.AreEqual(File.ReadAllText(filename), ResourceProvider.Get("First.e")); } [Test] public void Given_first_set_and_second_set_when_written_to_disk_individually_and_when_read_back_in_then_content_is_as_expected() { var identity = new Guid("E34900D6-6C63-4066-988F-DCEC25B482FA"); var filename = _repositoryPath.For(identity); File.Delete(filename); var fspe = new FileSystemPersistenceStrategy(_repositoryPath, EventReaderWriterPair.Null); fspe.Store(identity, MockEventStreams.First); fspe.Store(identity, MockEventStreams.Second); Assert.AreEqual(File.ReadAllText(filename), ResourceProvider.Get("First_and_second.e")); } } }
nbevans/EventStreams
EventStreams.Tests/Persistence/FileSystem/FileSystemPersistenceStrategyTests.cs
C#
mit
1,664
<?php $navbar = [ "config" => [ "navbar-class" => "navbar" ], "items" => [ "start" => [ "text" => "Start", "route" => "", ], "about" => [ "text" => "About", "route" => "about", ], "report" => [ "text" => "Report", "route" => "report", ], ] ]; $navHtml = ""; $navClass = $navbar["config"]["navbar-class"]; // Create url using $app->url->create(); foreach ($navbar["items"] as $items => $item) { $nav = $item["route"]; $url = $app->url->create("$nav"); $navHtml .= '<li><a href="' . $url . '">' . $item["text"] . '</a></li>'; } ?> <nav class="<?= $navClass ?>"> <ul> <?= $navHtml ?> </ul> </nav>
Marv2/anax-lite
view/navbar1/navbar.php
PHP
mit
772