code
stringlengths 4
1.01M
| language
stringclasses 2
values |
|---|---|
'use strict';
goog.provide('Blockly.JavaScript.serial');
goog.require('Blockly.JavaScript');
Blockly.JavaScript.serial_print = function() {
var content = Blockly.JavaScript.valueToCode(this, 'CONTENT', Blockly.JavaScript.ORDER_ATOMIC) || '\"\"'
var code = 'serial.writeString(\'\' + '+content+');\n';
return code;
};
Blockly.JavaScript.serial_println = function() {
var content = Blockly.JavaScript.valueToCode(this, 'CONTENT', Blockly.JavaScript.ORDER_ATOMIC) || '\"\"'
var code = 'serial.writeLine(\'\' + '+content+');\n';
return code;
};
Blockly.JavaScript.serial_print_hex = function() {
var content = Blockly.JavaScript.valueToCode(this, 'CONTENT', Blockly.JavaScript.ORDER_ATOMIC) || '0';
var code = 'serial.writeLine('+content+'.toString(16));\n';
return code;
};
Blockly.JavaScript.serial_receive_data_event = function() {
var char_marker = Blockly.JavaScript.valueToCode(this, 'char_marker', Blockly.JavaScript.ORDER_ATOMIC) || ';';
var branch = Blockly.JavaScript.statementToCode(this, 'DO');
Blockly.JavaScript.definitions_['func_serial_receive_data_event_' + char_marker.charCodeAt(1)] = "serial.onDataReceived(" + char_marker + ", () => {\n" + branch + "};\n";
};
Blockly.JavaScript.serial_readstr = function() {
var code ="serial.readString()";
return [code,Blockly.JavaScript.ORDER_ATOMIC];
};
Blockly.JavaScript.serial_readline = function() {
var code ="serial.readLine()";
return [code,Blockly.JavaScript.ORDER_ATOMIC];
};
Blockly.JavaScript.serial_readstr_until = function() {
var char_marker = this.getFieldValue('char_marker');
var code ="serial.readUntil("+char_marker + ")";
return [code,Blockly.JavaScript.ORDER_ATOMIC];
};
Blockly.JavaScript.serial_softserial = function () {
var dropdown_pin1 = Blockly.JavaScript.valueToCode(this, 'RX',Blockly.JavaScript.ORDER_ATOMIC);
var dropdown_pin2 = Blockly.JavaScript.valueToCode(this, 'TX',Blockly.JavaScript.ORDER_ATOMIC);
var baudrate = this.getFieldValue('baudrate');
return "serial.redirect(" + dropdown_pin1 + ", " + dropdown_pin2 + ", BaudRate.BaudRate" + baudrate + ");\n";
};
|
Java
|
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.cloud.spanner_v1.proto import (
result_set_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2,
)
from google.cloud.spanner_v1.proto import (
spanner_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2,
)
from google.cloud.spanner_v1.proto import (
transaction_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2,
)
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
class SpannerStub(object):
"""Cloud Spanner API
The Cloud Spanner API can be used to manage sessions and execute
transactions on data stored in Cloud Spanner databases.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.CreateSession = channel.unary_unary(
"/google.spanner.v1.Spanner/CreateSession",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CreateSessionRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.FromString,
)
self.BatchCreateSessions = channel.unary_unary(
"/google.spanner.v1.Spanner/BatchCreateSessions",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BatchCreateSessionsRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BatchCreateSessionsResponse.FromString,
)
self.GetSession = channel.unary_unary(
"/google.spanner.v1.Spanner/GetSession",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.GetSessionRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.FromString,
)
self.ListSessions = channel.unary_unary(
"/google.spanner.v1.Spanner/ListSessions",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ListSessionsRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ListSessionsResponse.FromString,
)
self.DeleteSession = channel.unary_unary(
"/google.spanner.v1.Spanner/DeleteSession",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.DeleteSessionRequest.SerializeToString,
response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
)
self.ExecuteSql = channel.unary_unary(
"/google.spanner.v1.Spanner/ExecuteSql",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.FromString,
)
self.ExecuteStreamingSql = channel.unary_stream(
"/google.spanner.v1.Spanner/ExecuteStreamingSql",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.FromString,
)
self.ExecuteBatchDml = channel.unary_unary(
"/google.spanner.v1.Spanner/ExecuteBatchDml",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteBatchDmlRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteBatchDmlResponse.FromString,
)
self.Read = channel.unary_unary(
"/google.spanner.v1.Spanner/Read",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.FromString,
)
self.StreamingRead = channel.unary_stream(
"/google.spanner.v1.Spanner/StreamingRead",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.FromString,
)
self.BeginTransaction = channel.unary_unary(
"/google.spanner.v1.Spanner/BeginTransaction",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BeginTransactionRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2.Transaction.FromString,
)
self.Commit = channel.unary_unary(
"/google.spanner.v1.Spanner/Commit",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitResponse.FromString,
)
self.Rollback = channel.unary_unary(
"/google.spanner.v1.Spanner/Rollback",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.RollbackRequest.SerializeToString,
response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
)
self.PartitionQuery = channel.unary_unary(
"/google.spanner.v1.Spanner/PartitionQuery",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionQueryRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.FromString,
)
self.PartitionRead = channel.unary_unary(
"/google.spanner.v1.Spanner/PartitionRead",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionReadRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.FromString,
)
class SpannerServicer(object):
"""Cloud Spanner API
The Cloud Spanner API can be used to manage sessions and execute
transactions on data stored in Cloud Spanner databases.
"""
def CreateSession(self, request, context):
"""Creates a new session. A session can be used to perform
transactions that read and/or modify data in a Cloud Spanner database.
Sessions are meant to be reused for many consecutive
transactions.
Sessions can only execute one transaction at a time. To execute
multiple concurrent read-write/write-only transactions, create
multiple sessions. Note that standalone reads and queries use a
transaction internally, and count toward the one transaction
limit.
Active sessions use additional server resources, so it is a good idea to
delete idle and unneeded sessions.
Aside from explicit deletes, Cloud Spanner can delete sessions for which no
operations are sent for more than an hour. If a session is deleted,
requests to it return `NOT_FOUND`.
Idle sessions can be kept alive by sending a trivial SQL query
periodically, e.g., `"SELECT 1"`.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def BatchCreateSessions(self, request, context):
"""Creates multiple new sessions.
This API can be used to initialize a session cache on the clients.
See https://goo.gl/TgSFN2 for best practices on session cache management.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def GetSession(self, request, context):
"""Gets a session. Returns `NOT_FOUND` if the session does not exist.
This is mainly useful for determining whether a session is still
alive.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ListSessions(self, request, context):
"""Lists all sessions in a given database.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def DeleteSession(self, request, context):
"""Ends a session, releasing server resources associated with it. This will
asynchronously trigger cancellation of any operations that are running with
this session.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExecuteSql(self, request, context):
"""Executes an SQL statement, returning all results in a single reply. This
method cannot be used to return a result set larger than 10 MiB;
if the query yields more data than that, the query fails with
a `FAILED_PRECONDITION` error.
Operations inside read-write transactions might return `ABORTED`. If
this occurs, the application should restart the transaction from
the beginning. See [Transaction][google.spanner.v1.Transaction] for more details.
Larger result sets can be fetched in streaming fashion by calling
[ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] instead.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExecuteStreamingSql(self, request, context):
"""Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the result
set as a stream. Unlike [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], there
is no limit on the size of the returned result set. However, no
individual row in the result set can exceed 100 MiB, and no
column value can exceed 10 MiB.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExecuteBatchDml(self, request, context):
"""Executes a batch of SQL DML statements. This method allows many statements
to be run with lower latency than submitting them sequentially with
[ExecuteSql][google.spanner.v1.Spanner.ExecuteSql].
Statements are executed in sequential order. A request can succeed even if
a statement fails. The [ExecuteBatchDmlResponse.status][google.spanner.v1.ExecuteBatchDmlResponse.status] field in the
response provides information about the statement that failed. Clients must
inspect this field to determine whether an error occurred.
Execution stops after the first failed statement; the remaining statements
are not executed.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def Read(self, request, context):
"""Reads rows from the database using key lookups and scans, as a
simple key/value style alternative to
[ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. This method cannot be used to
return a result set larger than 10 MiB; if the read matches more
data than that, the read fails with a `FAILED_PRECONDITION`
error.
Reads inside read-write transactions might return `ABORTED`. If
this occurs, the application should restart the transaction from
the beginning. See [Transaction][google.spanner.v1.Transaction] for more details.
Larger result sets can be yielded in streaming fashion by calling
[StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def StreamingRead(self, request, context):
"""Like [Read][google.spanner.v1.Spanner.Read], except returns the result set as a
stream. Unlike [Read][google.spanner.v1.Spanner.Read], there is no limit on the
size of the returned result set. However, no individual row in
the result set can exceed 100 MiB, and no column value can exceed
10 MiB.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def BeginTransaction(self, request, context):
"""Begins a new transaction. This step can often be skipped:
[Read][google.spanner.v1.Spanner.Read], [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and
[Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a
side-effect.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def Commit(self, request, context):
"""Commits a transaction. The request includes the mutations to be
applied to rows in the database.
`Commit` might return an `ABORTED` error. This can occur at any time;
commonly, the cause is conflicts with concurrent
transactions. However, it can also happen for a variety of other
reasons. If `Commit` returns `ABORTED`, the caller should re-attempt
the transaction from the beginning, re-using the same session.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def Rollback(self, request, context):
"""Rolls back a transaction, releasing any locks it holds. It is a good
idea to call this for any transaction that includes one or more
[Read][google.spanner.v1.Spanner.Read] or [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and
ultimately decides not to commit.
`Rollback` returns `OK` if it successfully aborts the transaction, the
transaction was already aborted, or the transaction is not
found. `Rollback` never returns `ABORTED`.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def PartitionQuery(self, request, context):
"""Creates a set of partition tokens that can be used to execute a query
operation in parallel. Each of the returned partition tokens can be used
by [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] to specify a subset
of the query result to read. The same session and read-only transaction
must be used by the PartitionQueryRequest used to create the
partition tokens and the ExecuteSqlRequests that use the partition tokens.
Partition tokens become invalid when the session used to create them
is deleted, is idle for too long, begins a new transaction, or becomes too
old. When any of these happen, it is not possible to resume the query, and
the whole operation must be restarted from the beginning.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def PartitionRead(self, request, context):
"""Creates a set of partition tokens that can be used to execute a read
operation in parallel. Each of the returned partition tokens can be used
by [StreamingRead][google.spanner.v1.Spanner.StreamingRead] to specify a subset of the read
result to read. The same session and read-only transaction must be used by
the PartitionReadRequest used to create the partition tokens and the
ReadRequests that use the partition tokens. There are no ordering
guarantees on rows returned among the returned partition tokens, or even
within each individual StreamingRead call issued with a partition_token.
Partition tokens become invalid when the session used to create them
is deleted, is idle for too long, begins a new transaction, or becomes too
old. When any of these happen, it is not possible to resume the read, and
the whole operation must be restarted from the beginning.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def add_SpannerServicer_to_server(servicer, server):
rpc_method_handlers = {
"CreateSession": grpc.unary_unary_rpc_method_handler(
servicer.CreateSession,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CreateSessionRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.SerializeToString,
),
"BatchCreateSessions": grpc.unary_unary_rpc_method_handler(
servicer.BatchCreateSessions,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BatchCreateSessionsRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BatchCreateSessionsResponse.SerializeToString,
),
"GetSession": grpc.unary_unary_rpc_method_handler(
servicer.GetSession,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.GetSessionRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.SerializeToString,
),
"ListSessions": grpc.unary_unary_rpc_method_handler(
servicer.ListSessions,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ListSessionsRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ListSessionsResponse.SerializeToString,
),
"DeleteSession": grpc.unary_unary_rpc_method_handler(
servicer.DeleteSession,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.DeleteSessionRequest.FromString,
response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
),
"ExecuteSql": grpc.unary_unary_rpc_method_handler(
servicer.ExecuteSql,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.SerializeToString,
),
"ExecuteStreamingSql": grpc.unary_stream_rpc_method_handler(
servicer.ExecuteStreamingSql,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.SerializeToString,
),
"ExecuteBatchDml": grpc.unary_unary_rpc_method_handler(
servicer.ExecuteBatchDml,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteBatchDmlRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteBatchDmlResponse.SerializeToString,
),
"Read": grpc.unary_unary_rpc_method_handler(
servicer.Read,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.SerializeToString,
),
"StreamingRead": grpc.unary_stream_rpc_method_handler(
servicer.StreamingRead,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.SerializeToString,
),
"BeginTransaction": grpc.unary_unary_rpc_method_handler(
servicer.BeginTransaction,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BeginTransactionRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2.Transaction.SerializeToString,
),
"Commit": grpc.unary_unary_rpc_method_handler(
servicer.Commit,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitResponse.SerializeToString,
),
"Rollback": grpc.unary_unary_rpc_method_handler(
servicer.Rollback,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.RollbackRequest.FromString,
response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
),
"PartitionQuery": grpc.unary_unary_rpc_method_handler(
servicer.PartitionQuery,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionQueryRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.SerializeToString,
),
"PartitionRead": grpc.unary_unary_rpc_method_handler(
servicer.PartitionRead,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionReadRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
"google.spanner.v1.Spanner", rpc_method_handlers
)
server.add_generic_rpc_handlers((generic_handler,))
|
Java
|
package com.comps.util;
import com.google.gson.Gson;
public class GsonManager {
private static Gson instance;
public static Gson getInstance(){
if (instance == null){
instance = new Gson();
}
return instance;
}
}
|
Java
|
/**
* Blueprint API Configuration
* (sails.config.blueprints)
*
* These settings are for the global configuration of blueprint routes and
* request options (which impact the behavior of blueprint actions).
*
* You may also override any of these settings on a per-controller basis
* by defining a '_config' key in your controller defintion, and assigning it
* a configuration object with overrides for the settings in this file.
* A lot of the configuration options below affect so-called "CRUD methods",
* or your controllers' `find`, `create`, `update`, and `destroy` actions.
*
* It's important to realize that, even if you haven't defined these yourself, as long as
* a model exists with the same name as the controller, Sails will respond with built-in CRUD
* logic in the form of a JSON API, including support for sort, pagination, and filtering.
*
* For more information on the blueprint API, check out:
* http://sailsjs.org/#/documentation/reference/blueprint-api
*
* For more information on the settings in this file, see:
* http://sailsjs.org/#/documentation/reference/sails.config/sails.config.blueprints.html
*
*/
module.exports.blueprints = {
/***************************************************************************
* *
* Action routes speed up the backend development workflow by *
* eliminating the need to manually bind routes. When enabled, GET, POST, *
* PUT, and DELETE routes will be generated for every one of a controller's *
* actions. *
* *
* If an `index` action exists, additional naked routes will be created for *
* it. Finally, all `actions` blueprints support an optional path *
* parameter, `id`, for convenience. *
* *
* `actions` are enabled by default, and can be OK for production-- *
* however, if you'd like to continue to use controller/action autorouting *
* in a production deployment, you must take great care not to *
* inadvertently expose unsafe/unintentional controller logic to GET *
* requests. *
* *
***************************************************************************/
actions: true,
/***************************************************************************
* *
* RESTful routes (`sails.config.blueprints.rest`) *
* *
* REST blueprints are the automatically generated routes Sails uses to *
* expose a conventional REST API on top of a controller's `find`, *
* `create`, `update`, and `destroy` actions. *
* *
* For example, a BoatController with `rest` enabled generates the *
* following routes: *
* ::::::::::::::::::::::::::::::::::::::::::::::::::::::: *
* GET /boat/:id? -> BoatController.find *
* POST /boat -> BoatController.create *
* PUT /boat/:id -> BoatController.update *
* DELETE /boat/:id -> BoatController.destroy *
* *
* `rest` blueprint routes are enabled by default, and are suitable for use *
* in a production scenario, as long you take standard security precautions *
* (combine w/ policies, etc.) *
* *
***************************************************************************/
rest: true,
/***************************************************************************
* *
* Shortcut routes are simple helpers to provide access to a *
* controller's CRUD methods from your browser's URL bar. When enabled, *
* GET, POST, PUT, and DELETE routes will be generated for the *
* controller's`find`, `create`, `update`, and `destroy` actions. *
* *
* `shortcuts` are enabled by default, but should be disabled in *
* production. *
* *
***************************************************************************/
shortcuts: true,
/***************************************************************************
* *
* An optional mount path for all blueprint routes on a controller, *
* including `rest`, `actions`, and `shortcuts`. This allows you to take *
* advantage of blueprint routing, even if you need to namespace your API *
* methods. *
* *
* (NOTE: This only applies to blueprint autoroutes, not manual routes from *
* `sails.config.routes`) *
* *
***************************************************************************/
prefix: '/api/v1.0',
/***************************************************************************
* *
* Whether to pluralize controller names in blueprint routes. *
* *
* (NOTE: This only applies to blueprint autoroutes, not manual routes from *
* `sails.config.routes`) *
* *
* For example, REST blueprints for `FooController` with `pluralize` *
* enabled: *
* GET /foos/:id? *
* POST /foos *
* PUT /foos/:id? *
* DELETE /foos/:id? *
* *
***************************************************************************/
// pluralize: false,
/***************************************************************************
* *
* Whether the blueprint controllers should populate model fetches with *
* data from other models which are linked by associations *
* *
* If you have a lot of data in one-to-many associations, leaving this on *
* may result in very heavy api calls *
* *
***************************************************************************/
// populate: true,
/****************************************************************************
* *
* Whether to run Model.watch() in the find and findOne blueprint actions. *
* Can be overridden on a per-model basis. *
* *
****************************************************************************/
// autoWatch: true,
/****************************************************************************
* *
* The default number of records to show in the response from a "find" *
* action. Doubles as the default size of populated arrays if populate is *
* true. *
* *
****************************************************************************/
// defaultLimit: 30
};
|
Java
|
-------------------------------------------------------------------------------
-- budget info
-------------------------------------------------------------------------------
CREATE TABLE BUDGET_INFO(
ID BIGINT NOT NULL,
NAME VARCHAR(200),
CREATE_TIME DATETIME,
STATUS VARCHAR(50),
TYPE VARCHAR(50),
MONEY DOUBLE,
START_TIME DATETIME,
END_TIME DATETIME,
DESCRIPTION TEXT,
USER_ID VARCHAR(64),
TENANT_ID VARCHAR(64),
CONSTRAINT PK_BUDGET_INFO PRIMARY KEY(ID)
) ENGINE=INNODB CHARSET=UTF8;
|
Java
|
import { IInjectable } from "../common/common";
import { TypedMap } from "../common/common";
import { StateProvider } from "./stateProvider";
import { ResolveContext } from "../resolve/resolveContext";
import * as angular from 'angular';
import IScope = angular.IScope;
/**
* Annotates a controller expression (may be a controller function(), a "controllername",
* or "controllername as name")
*
* - Temporarily decorates $injector.instantiate.
* - Invokes $controller() service
* - Calls $injector.instantiate with controller constructor
* - Annotate constructor
* - Undecorate $injector
*
* returns an array of strings, which are the arguments of the controller expression
*/
export declare function annotateController(controllerExpression: (IInjectable | string)): string[];
declare module "../router" {
interface UIRouter {
/** @hidden TODO: move this to ng1.ts */
stateProvider: StateProvider;
}
}
export declare function watchDigests($rootScope: IScope): void;
export declare const getLocals: (ctx: ResolveContext) => TypedMap<any>;
|
Java
|
// This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import static org.sosy_lab.java_smt.api.FormulaType.BooleanType;
import static org.sosy_lab.java_smt.api.FormulaType.IntegerType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.testing.EqualsTester;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.SolverException;
@RunWith(Parameterized.class)
public class FormulaManagerTest extends SolverBasedTest0 {
@Parameters(name = "{0}")
public static Object[] getAllSolvers() {
return Solvers.values();
}
@Parameter(0)
public Solvers solver;
@Override
protected Solvers solverToUse() {
return solver;
}
@Test
public void testEmptySubstitution() throws SolverException, InterruptedException {
// Boolector does not support substitution
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
assume().withMessage("Princess fails").that(solver).isNotEqualTo(Solvers.PRINCESS);
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
FunctionDeclaration<BooleanFormula> uf2Decl =
fmgr.declareUF("uf", BooleanType, IntegerType, IntegerType);
BooleanFormula f1 = fmgr.callUF(uf2Decl, variable1, variable3);
BooleanFormula f2 = fmgr.callUF(uf2Decl, variable2, variable4);
BooleanFormula input = bmgr.xor(f1, f2);
BooleanFormula out = mgr.substitute(input, ImmutableMap.of());
assertThatFormula(out).isEquivalentTo(input);
}
@Test
public void testNoSubstitution() throws SolverException, InterruptedException {
// Boolector does not support substitution
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
assume().withMessage("Princess fails").that(solver).isNotEqualTo(Solvers.PRINCESS);
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
FunctionDeclaration<BooleanFormula> uf2Decl =
fmgr.declareUF("uf", BooleanType, IntegerType, IntegerType);
BooleanFormula f1 = fmgr.callUF(uf2Decl, variable1, variable3);
BooleanFormula f2 = fmgr.callUF(uf2Decl, variable2, variable4);
BooleanFormula input = bmgr.xor(f1, f2);
Map<BooleanFormula, BooleanFormula> substitution =
ImmutableMap.of(
bmgr.makeVariable("a"), bmgr.makeVariable("a1"),
bmgr.makeVariable("b"), bmgr.makeVariable("b1"),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")), bmgr.makeVariable("e"));
BooleanFormula out = mgr.substitute(input, substitution);
assertThatFormula(out).isEquivalentTo(input);
}
@Test
public void testSubstitution() throws SolverException, InterruptedException {
// Boolector does not support substitution
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BooleanFormula input =
bmgr.or(
bmgr.and(bmgr.makeVariable("a"), bmgr.makeVariable("b")),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")));
BooleanFormula out =
mgr.substitute(
input,
ImmutableMap.of(
bmgr.makeVariable("a"), bmgr.makeVariable("a1"),
bmgr.makeVariable("b"), bmgr.makeVariable("b1"),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")), bmgr.makeVariable("e")));
assertThatFormula(out)
.isEquivalentTo(
bmgr.or(
bmgr.and(bmgr.makeVariable("a1"), bmgr.makeVariable("b1")),
bmgr.makeVariable("e")));
}
@Test
public void testSubstitutionTwice() throws SolverException, InterruptedException {
// Boolector does not support substitution
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BooleanFormula input =
bmgr.or(
bmgr.and(bmgr.makeVariable("a"), bmgr.makeVariable("b")),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")));
ImmutableMap<BooleanFormula, BooleanFormula> substitution =
ImmutableMap.of(
bmgr.makeVariable("a"), bmgr.makeVariable("a1"),
bmgr.makeVariable("b"), bmgr.makeVariable("b1"),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")), bmgr.makeVariable("e"));
BooleanFormula out = mgr.substitute(input, substitution);
assertThatFormula(out)
.isEquivalentTo(
bmgr.or(
bmgr.and(bmgr.makeVariable("a1"), bmgr.makeVariable("b1")),
bmgr.makeVariable("e")));
BooleanFormula out2 = mgr.substitute(out, substitution);
assertThatFormula(out2).isEquivalentTo(out);
}
@Test
public void formulaEqualsAndHashCode() {
// Solvers without integers (Boolector) get their own test below
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
FunctionDeclaration<IntegerFormula> fb = fmgr.declareUF("f_b", IntegerType, IntegerType);
new EqualsTester()
.addEqualityGroup(bmgr.makeBoolean(true))
.addEqualityGroup(bmgr.makeBoolean(false))
.addEqualityGroup(bmgr.makeVariable("bool_a"))
.addEqualityGroup(imgr.makeVariable("int_a"))
// Way of creating numbers should not make a difference.
.addEqualityGroup(
imgr.makeNumber(0.0),
imgr.makeNumber(0L),
imgr.makeNumber(BigInteger.ZERO),
imgr.makeNumber(BigDecimal.ZERO),
imgr.makeNumber("0"))
.addEqualityGroup(
imgr.makeNumber(1.0),
imgr.makeNumber(1L),
imgr.makeNumber(BigInteger.ONE),
imgr.makeNumber(BigDecimal.ONE),
imgr.makeNumber("1"))
// The same formula when created twice should compare equal.
.addEqualityGroup(bmgr.makeVariable("bool_b"), bmgr.makeVariable("bool_b"))
.addEqualityGroup(
bmgr.and(bmgr.makeVariable("bool_a"), bmgr.makeVariable("bool_b")),
bmgr.and(bmgr.makeVariable("bool_a"), bmgr.makeVariable("bool_b")))
.addEqualityGroup(
imgr.equal(imgr.makeNumber(0), imgr.makeVariable("int_a")),
imgr.equal(imgr.makeNumber(0), imgr.makeVariable("int_a")))
// UninterpretedFunctionDeclarations should not compare equal to Formulas,
// but declaring one twice needs to return the same UIF.
.addEqualityGroup(
fmgr.declareUF("f_a", IntegerType, IntegerType),
fmgr.declareUF("f_a", IntegerType, IntegerType))
.addEqualityGroup(fb)
.addEqualityGroup(fmgr.callUF(fb, imgr.makeNumber(0)))
.addEqualityGroup(fmgr.callUF(fb, imgr.makeNumber(1)), fmgr.callUF(fb, imgr.makeNumber(1)))
.testEquals();
}
@Test
public void bitvectorFormulaEqualsAndHashCode() {
// Boolector does not support integers and it is easier to make a new test with bvs
requireBitvectors();
FunctionDeclaration<BitvectorFormula> fb =
fmgr.declareUF(
"f_bv",
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8));
new EqualsTester()
.addEqualityGroup(bmgr.makeBoolean(true))
.addEqualityGroup(bmgr.makeBoolean(false))
.addEqualityGroup(bmgr.makeVariable("bool_a"))
.addEqualityGroup(bvmgr.makeVariable(8, "bv_a"))
// Way of creating numbers should not make a difference.
.addEqualityGroup(
bvmgr.makeBitvector(8, 0L),
bvmgr.makeBitvector(8, 0),
bvmgr.makeBitvector(8, BigInteger.ZERO))
.addEqualityGroup(
bvmgr.makeBitvector(8, 1L),
bvmgr.makeBitvector(8, 1),
bvmgr.makeBitvector(8, BigInteger.ONE))
// The same formula when created twice should compare equal.
.addEqualityGroup(bmgr.makeVariable("bool_b"), bmgr.makeVariable("bool_b"))
.addEqualityGroup(
bmgr.and(bmgr.makeVariable("bool_a"), bmgr.makeVariable("bool_b")),
bmgr.and(bmgr.makeVariable("bool_a"), bmgr.makeVariable("bool_b")))
.addEqualityGroup(
bvmgr.equal(bvmgr.makeBitvector(8, 0), bvmgr.makeVariable(8, "int_a")),
bvmgr.equal(bvmgr.makeBitvector(8, 0), bvmgr.makeVariable(8, "int_a")))
// UninterpretedFunctionDeclarations should not compare equal to Formulas,
// but declaring one twice needs to return the same UIF.
.addEqualityGroup(
fmgr.declareUF(
"f_a",
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8)),
fmgr.declareUF(
"f_a",
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8)))
.addEqualityGroup(fb)
.addEqualityGroup(fmgr.callUF(fb, bvmgr.makeBitvector(8, 0)))
.addEqualityGroup(
fmgr.callUF(fb, bvmgr.makeBitvector(8, 1)), // why not equal?!
fmgr.callUF(fb, bvmgr.makeBitvector(8, 1)))
.testEquals();
}
@Test
public void variableNameExtractorTest() {
// Since Boolector does not support integers we use bitvectors
if (imgr != null) {
BooleanFormula constr =
bmgr.or(
imgr.equal(
imgr.subtract(
imgr.add(imgr.makeVariable("x"), imgr.makeVariable("z")),
imgr.makeNumber(10)),
imgr.makeVariable("y")),
imgr.equal(imgr.makeVariable("xx"), imgr.makeVariable("zz")));
assertThat(mgr.extractVariables(constr).keySet()).containsExactly("x", "y", "z", "xx", "zz");
assertThat(mgr.extractVariablesAndUFs(constr)).isEqualTo(mgr.extractVariables(constr));
} else {
BooleanFormula bvConstr =
bmgr.or(
bvmgr.equal(
bvmgr.subtract(
bvmgr.add(bvmgr.makeVariable(8, "x"), bvmgr.makeVariable(8, "z")),
bvmgr.makeBitvector(8, 10)),
bvmgr.makeVariable(8, "y")),
bvmgr.equal(bvmgr.makeVariable(8, "xx"), bvmgr.makeVariable(8, "zz")));
requireVisitor();
assertThat(mgr.extractVariables(bvConstr).keySet())
.containsExactly("x", "y", "z", "xx", "zz");
assertThat(mgr.extractVariablesAndUFs(bvConstr)).isEqualTo(mgr.extractVariables(bvConstr));
}
}
@Test
public void ufNameExtractorTest() {
// Since Boolector does not support integers we use bitvectors for constraints
if (imgr != null) {
BooleanFormula constraint =
imgr.equal(
fmgr.declareAndCallUF("uf1", IntegerType, ImmutableList.of(imgr.makeVariable("x"))),
fmgr.declareAndCallUF("uf2", IntegerType, ImmutableList.of(imgr.makeVariable("y"))));
assertThat(mgr.extractVariablesAndUFs(constraint).keySet())
.containsExactly("uf1", "uf2", "x", "y");
assertThat(mgr.extractVariables(constraint).keySet()).containsExactly("x", "y");
} else {
BooleanFormula bvConstraint =
bvmgr.equal(
fmgr.declareAndCallUF(
"uf1",
FormulaType.getBitvectorTypeWithSize(8),
ImmutableList.of(bvmgr.makeVariable(8, "x"))),
fmgr.declareAndCallUF(
"uf2",
FormulaType.getBitvectorTypeWithSize(8),
ImmutableList.of(bvmgr.makeVariable(8, "y"))));
requireVisitor();
assertThat(mgr.extractVariablesAndUFs(bvConstraint).keySet())
.containsExactly("uf1", "uf2", "x", "y");
assertThat(mgr.extractVariables(bvConstraint).keySet()).containsExactly("x", "y");
}
}
@Test
public void simplifyIntTest() throws SolverException, InterruptedException {
requireIntegers();
// x=1 && y=x+2 && z=y+3 --> simplified: x=1 && y=3 && z=6
IntegerFormula num1 = imgr.makeNumber(1);
IntegerFormula num2 = imgr.makeNumber(2);
IntegerFormula num3 = imgr.makeNumber(3);
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula y = imgr.makeVariable("y");
IntegerFormula z = imgr.makeVariable("z");
BooleanFormula f =
bmgr.and(
imgr.equal(x, num1),
imgr.equal(y, imgr.add(x, num2)),
imgr.equal(z, imgr.add(y, num3)));
assertThatFormula(mgr.simplify(f)).isEquisatisfiableTo(f);
}
@Test
public void simplifyArrayTest() throws SolverException, InterruptedException {
requireIntegers();
requireArrays();
// exists arr : (arr[0]=5 && x=arr[0]) --> simplified: x=5
ArrayFormula<IntegerFormula, IntegerFormula> arr =
amgr.makeArray("arr", new ArrayFormulaType<>(IntegerType, IntegerType));
IntegerFormula index = imgr.makeNumber(0);
IntegerFormula value = imgr.makeNumber(5);
IntegerFormula x = imgr.makeVariable("x");
ArrayFormula<IntegerFormula, IntegerFormula> write = amgr.store(arr, index, value);
IntegerFormula read = amgr.select(write, index);
BooleanFormula f = imgr.equal(x, read);
assertThatFormula(mgr.simplify(f)).isEquisatisfiableTo(f);
}
}
|
Java
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0-b52-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.09.17 at 02:39:44 오후 KST
//
package com.athena.chameleon.engine.entity.xml.application.jeus.v5_0;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
/**
* <p>Java class for vendorType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="vendorType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}token">
* <enumeration value="oracle"/>
* <enumeration value="sybase"/>
* <enumeration value="mssql"/>
* <enumeration value="db2"/>
* <enumeration value="tibero"/>
* <enumeration value="informix"/>
* <enumeration value="mysql"/>
* <enumeration value="others"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlEnum
public enum VendorType {
@XmlEnumValue("db2")
DB_2("db2"),
@XmlEnumValue("informix")
INFORMIX("informix"),
@XmlEnumValue("mssql")
MSSQL("mssql"),
@XmlEnumValue("mysql")
MYSQL("mysql"),
@XmlEnumValue("oracle")
ORACLE("oracle"),
@XmlEnumValue("others")
OTHERS("others"),
@XmlEnumValue("sybase")
SYBASE("sybase"),
@XmlEnumValue("tibero")
TIBERO("tibero");
private final String value;
VendorType(String v) {
value = v;
}
public String value() {
return value;
}
public static VendorType fromValue(String v) {
for (VendorType c: VendorType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v.toString());
}
}
|
Java
|
#!/bin/bash
SOURCE="${BASH_SOURCE[0]}"
while [ -h ${SOURCE} ];do
DIR=$( cd -P $( dirname ${SOURCE} ) && pwd )
SOURCE="$(readlink ${SOURCE})"
[[ ${SOURCE} != /* ]] && SOURCE=${DIR}/${SOURCE}
done
BASEDIR="$( cd -P $( dirname ${SOURCE} ) && pwd )"
cd ${BASEDIR}
docker build -t zkpregistry.com:5043/alpine-tomcat:jre7tomcat7 -f ${BASEDIR}/Dockerfile ${BASEDIR}/
|
Java
|
package it.unibz.inf.ontop.renderer;
/*
* #%L
* ontop-obdalib-core
* %%
* Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import it.unibz.inf.ontop.io.PrefixManager;
import it.unibz.inf.ontop.io.SimplePrefixManager;
import it.unibz.inf.ontop.model.Constant;
import it.unibz.inf.ontop.model.DatatypeFactory;
import it.unibz.inf.ontop.model.ExpressionOperation;
import it.unibz.inf.ontop.model.Function;
import it.unibz.inf.ontop.model.Predicate;
import it.unibz.inf.ontop.model.Term;
import it.unibz.inf.ontop.model.URIConstant;
import it.unibz.inf.ontop.model.URITemplatePredicate;
import it.unibz.inf.ontop.model.ValueConstant;
import it.unibz.inf.ontop.model.Variable;
import it.unibz.inf.ontop.model.impl.OBDADataFactoryImpl;
import it.unibz.inf.ontop.model.impl.OBDAVocabulary;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* A utility class to render a Target Query object into its representational
* string.
*/
public class TargetQueryRenderer {
private static final DatatypeFactory dtfac = OBDADataFactoryImpl.getInstance().getDatatypeFactory();
/**
* Transforms the given <code>OBDAQuery</code> into a string. The method requires
* a prefix manager to shorten full IRI name.
*/
public static String encode(List<Function> input, PrefixManager prefixManager) {
TurtleWriter turtleWriter = new TurtleWriter();
List<Function> body = input;
for (Function atom : body) {
String subject, predicate, object = "";
String originalString = atom.getFunctionSymbol().toString();
if (isUnary(atom)) {
Term subjectTerm = atom.getTerm(0);
subject = getDisplayName(subjectTerm, prefixManager);
predicate = "a";
object = getAbbreviatedName(originalString, prefixManager, false);
if (originalString.equals(object)) {
object = "<" + object + ">";
}
}
else if (originalString.equals("triple")) {
Term subjectTerm = atom.getTerm(0);
subject = getDisplayName(subjectTerm, prefixManager);
Term predicateTerm = atom.getTerm(1);
predicate = getDisplayName(predicateTerm, prefixManager);
Term objectTerm = atom.getTerm(2);
object = getDisplayName(objectTerm, prefixManager);
}
else {
Term subjectTerm = atom.getTerm(0);
subject = getDisplayName(subjectTerm, prefixManager);
predicate = getAbbreviatedName(originalString, prefixManager, false);
if (originalString.equals(predicate)) {
predicate = "<" + predicate + ">";
}
Term objectTerm = atom.getTerm(1);
object = getDisplayName(objectTerm, prefixManager);
}
turtleWriter.put(subject, predicate, object);
}
return turtleWriter.print();
}
/**
* Checks if the atom is unary or not.
*/
private static boolean isUnary(Function atom) {
return atom.getArity() == 1 ? true : false;
}
/**
* Prints the short form of the predicate (by omitting the complete URI and
* replacing it by a prefix name).
*
* Note that by default this method will consider a set of predefined
* prefixes, i.e., rdf:, rdfs:, owl:, xsd: and quest: To support this
* prefixes the method will temporally add the prefixes if they dont exist
* already, taken care to remove them if they didn't exist.
*
* The implementation requires at the moment, the implementation requires
* cloning the existing prefix manager, and hence this is highly inefficient
* method. *
*/
private static String getAbbreviatedName(String uri, PrefixManager pm, boolean insideQuotes) {
// Cloning the existing manager
PrefixManager prefManClone = new SimplePrefixManager();
Map<String,String> currentMap = pm.getPrefixMap();
for (String prefix: currentMap.keySet()) {
prefManClone.addPrefix(prefix, pm.getURIDefinition(prefix));
}
return prefManClone.getShortForm(uri, insideQuotes);
}
private static String appendTerms(Term term){
if (term instanceof Constant){
String st = ((Constant) term).getValue();
if (st.contains("{")){
st = st.replace("{", "\\{");
st = st.replace("}", "\\}");
}
return st;
}else{
return "{"+((Variable) term).getName()+"}";
}
}
//Appends nested concats
public static void getNestedConcats(StringBuilder stb, Term term1, Term term2){
if (term1 instanceof Function){
Function f = (Function) term1;
getNestedConcats(stb, f.getTerms().get(0), f.getTerms().get(1));
}else{
stb.append(appendTerms(term1));
}
if (term2 instanceof Function){
Function f = (Function) term2;
getNestedConcats(stb, f.getTerms().get(0), f.getTerms().get(1));
}else{
stb.append(appendTerms(term2));
}
}
/**
* Prints the text representation of different terms.
*/
private static String getDisplayName(Term term, PrefixManager prefixManager) {
StringBuilder sb = new StringBuilder();
if (term instanceof Function) {
Function function = (Function) term;
Predicate functionSymbol = function.getFunctionSymbol();
String fname = getAbbreviatedName(functionSymbol.toString(), prefixManager, false);
if (function.isDataTypeFunction()) {
// if the function symbol is a data type predicate
if (dtfac.isLiteral(functionSymbol)) {
// if it is rdfs:Literal
int arity = function.getArity();
if (arity == 1) {
// without the language tag
Term var = function.getTerms().get(0);
sb.append(getDisplayName(var, prefixManager));
sb.append("^^rdfs:Literal");
} else if (arity == 2) {
// with the language tag
Term var = function.getTerms().get(0);
Term lang = function.getTerms().get(1);
sb.append(getDisplayName(var, prefixManager));
sb.append("@");
if (lang instanceof ValueConstant) {
// Don't pass this to getDisplayName() because
// language constant is not written as @"lang-tag"
sb.append(((ValueConstant) lang).getValue());
} else {
sb.append(getDisplayName(lang, prefixManager));
}
}
} else { // for the other data types
Term var = function.getTerms().get(0);
sb.append(getDisplayName(var, prefixManager));
sb.append("^^");
sb.append(fname);
}
} else if (functionSymbol instanceof URITemplatePredicate) {
Term firstTerm = function.getTerms().get(0);
if(firstTerm instanceof Variable)
{
sb.append("<{");
sb.append(((Variable) firstTerm).getName());
sb.append("}>");
}
else {
String template = ((ValueConstant) firstTerm).getValue();
// Utilize the String.format() method so we replaced placeholders '{}' with '%s'
String templateFormat = template.replace("{}", "%s");
List<String> varNames = new ArrayList<String>();
for (Term innerTerm : function.getTerms()) {
if (innerTerm instanceof Variable) {
varNames.add(getDisplayName(innerTerm, prefixManager));
}
}
String originalUri = String.format(templateFormat, varNames.toArray());
if (originalUri.equals(OBDAVocabulary.RDF_TYPE)) {
sb.append("a");
} else {
String shortenUri = getAbbreviatedName(originalUri, prefixManager, false); // shorten the URI if possible
if (!shortenUri.equals(originalUri)) {
sb.append(shortenUri);
} else {
// If the URI can't be shorten then use the full URI within brackets
sb.append("<");
sb.append(originalUri);
sb.append(">");
}
}
}
}
else if (functionSymbol == ExpressionOperation.CONCAT) { //Concat
List<Term> terms = function.getTerms();
sb.append("\"");
getNestedConcats(sb, terms.get(0),terms.get(1));
sb.append("\"");
//sb.append("^^rdfs:Literal");
}
else { // for any ordinary function symbol
sb.append(fname);
sb.append("(");
boolean separator = false;
for (Term innerTerm : function.getTerms()) {
if (separator) {
sb.append(", ");
}
sb.append(getDisplayName(innerTerm, prefixManager));
separator = true;
}
sb.append(")");
}
} else if (term instanceof Variable) {
sb.append("{");
sb.append(((Variable) term).getName());
sb.append("}");
} else if (term instanceof URIConstant) {
String originalUri = term.toString();
String shortenUri = getAbbreviatedName(originalUri, prefixManager, false); // shorten the URI if possible
if (!shortenUri.equals(originalUri)) {
sb.append(shortenUri);
} else {
// If the URI can't be shorten then use the full URI within brackets
sb.append("<");
sb.append(originalUri);
sb.append(">");
}
} else if (term instanceof ValueConstant) {
sb.append("\"");
sb.append(((ValueConstant) term).getValue());
sb.append("\"");
}
return sb.toString();
}
private TargetQueryRenderer() {
// Prevent initialization
}
}
|
Java
|
#define SQLITE_ASCII
#define SQLITE_DISABLE_LFS
#define SQLITE_ENABLE_OVERSIZE_CELL_CHECK
#define SQLITE_MUTEX_OMIT
#define SQLITE_OMIT_AUTHORIZATION
#define SQLITE_OMIT_DEPRECATED
#define SQLITE_OMIT_GET_TABLE
#define SQLITE_OMIT_INCRBLOB
#define SQLITE_OMIT_LOOKASIDE
#define SQLITE_OMIT_SHARED_CACHE
#define SQLITE_OMIT_UTF16
#define SQLITE_OMIT_WAL
#define SQLITE_OS_WIN
#define SQLITE_SYSTEM_MALLOC
#define VDBE_PROFILE_OFF
#define WINDOWS_MOBILE
#define NDEBUG
#define _MSC_VER
#define YYFALLBACK
//#define SQLITE_HAS_CODEC
using System;
using System.Diagnostics;
using System.Text;
using u8 = System.Byte;
using u32 = System.UInt32;
namespace Community.CsharpSqlite
{
using sqlite3_value = Sqlite3.Mem;
public partial class Sqlite3
{
/*
** 2003 April 6
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the ATTACH and DETACH commands.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#include "sqliteInt.h"
#if !SQLITE_OMIT_ATTACH
/*
** Resolve an expression that was part of an ATTACH or DETACH statement. This
** is slightly different from resolving a normal SQL expression, because simple
** identifiers are treated as strings, not possible column names or aliases.
**
** i.e. if the parser sees:
**
** ATTACH DATABASE abc AS def
**
** it treats the two expressions as literal strings 'abc' and 'def' instead of
** looking for columns of the same name.
**
** This only applies to the root node of pExpr, so the statement:
**
** ATTACH DATABASE abc||def AS 'db2'
**
** will fail because neither abc or def can be resolved.
*/
static int resolveAttachExpr( NameContext pName, Expr pExpr )
{
int rc = SQLITE_OK;
if ( pExpr != null )
{
if ( pExpr.op != TK_ID )
{
rc = sqlite3ResolveExprNames( pName, ref pExpr );
if ( rc == SQLITE_OK && sqlite3ExprIsConstant( pExpr ) == 0 )
{
sqlite3ErrorMsg( pName.pParse, "invalid name: \"%s\"", pExpr.u.zToken );
return SQLITE_ERROR;
}
}
else
{
pExpr.op = TK_STRING;
}
}
return rc;
}
/*
** An SQL user-function registered to do the work of an ATTACH statement. The
** three arguments to the function come directly from an attach statement:
**
** ATTACH DATABASE x AS y KEY z
**
** SELECT sqlite_attach(x, y, z)
**
** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
** third argument.
*/
static void attachFunc(
sqlite3_context context,
int NotUsed,
sqlite3_value[] argv
)
{
int i;
int rc = 0;
sqlite3 db = sqlite3_context_db_handle( context );
string zName;
string zFile;
string zPath = "";
string zErr = "";
int flags;
Db aNew = null;
string zErrDyn = "";
sqlite3_vfs pVfs = null;
UNUSED_PARAMETER( NotUsed );
zFile = argv[0].z != null && ( argv[0].z.Length > 0 ) && argv[0].flags != MEM_Null ? sqlite3_value_text( argv[0] ) : "";
zName = argv[1].z != null && ( argv[1].z.Length > 0 ) && argv[1].flags != MEM_Null ? sqlite3_value_text( argv[1] ) : "";
//if( zFile==null ) zFile = "";
//if ( zName == null ) zName = "";
/* Check for the following errors:
**
** * Too many attached databases,
** * Transaction currently open
** * Specified database name already being used.
*/
if ( db.nDb >= db.aLimit[SQLITE_LIMIT_ATTACHED] + 2 )
{
zErrDyn = sqlite3MPrintf( db, "too many attached databases - max %d",
db.aLimit[SQLITE_LIMIT_ATTACHED]
);
goto attach_error;
}
if ( 0 == db.autoCommit )
{
zErrDyn = sqlite3MPrintf( db, "cannot ATTACH database within transaction" );
goto attach_error;
}
for ( i = 0; i < db.nDb; i++ )
{
string z = db.aDb[i].zName;
Debug.Assert( z != null && zName != null );
if ( z.Equals( zName, StringComparison.InvariantCultureIgnoreCase ) )
{
zErrDyn = sqlite3MPrintf( db, "database %s is already in use", zName );
goto attach_error;
}
}
/* Allocate the new entry in the db.aDb[] array and initialise the schema
** hash tables.
*/
/* Allocate the new entry in the db.aDb[] array and initialise the schema
** hash tables.
*/
//if( db.aDb==db.aDbStatic ){
// aNew = sqlite3DbMallocRaw(db, sizeof(db.aDb[0])*3 );
// if( aNew==0 ) return;
// memcpy(aNew, db.aDb, sizeof(db.aDb[0])*2);
//}else {
if ( db.aDb.Length <= db.nDb )
Array.Resize( ref db.aDb, db.nDb + 1 );//aNew = sqlite3DbRealloc(db, db.aDb, sizeof(db.aDb[0])*(db.nDb+1) );
if ( db.aDb == null )
return; // if( aNew==0 ) return;
//}
db.aDb[db.nDb] = new Db();//db.aDb = aNew;
aNew = db.aDb[db.nDb];//memset(aNew, 0, sizeof(*aNew));
// memset(aNew, 0, sizeof(*aNew));
/* Open the database file. If the btree is successfully opened, use
** it to obtain the database schema. At this point the schema may
** or may not be initialised.
*/
flags = (int)db.openFlags;
rc = sqlite3ParseUri( db.pVfs.zName, zFile, ref flags, ref pVfs, ref zPath, ref zErr );
if ( rc != SQLITE_OK )
{
//if ( rc == SQLITE_NOMEM )
//db.mallocFailed = 1;
sqlite3_result_error( context, zErr, -1 );
//sqlite3_free( zErr );
return;
}
Debug.Assert( pVfs != null);
flags |= SQLITE_OPEN_MAIN_DB;
rc = sqlite3BtreeOpen( pVfs, zPath, db, ref aNew.pBt, 0, (int)flags );
//sqlite3_free( zPath );
db.nDb++;
if ( rc == SQLITE_CONSTRAINT )
{
rc = SQLITE_ERROR;
zErrDyn = sqlite3MPrintf( db, "database is already attached" );
}
else if ( rc == SQLITE_OK )
{
Pager pPager;
aNew.pSchema = sqlite3SchemaGet( db, aNew.pBt );
//if ( aNew.pSchema == null )
//{
// rc = SQLITE_NOMEM;
//}
//else
if ( aNew.pSchema.file_format != 0 && aNew.pSchema.enc != ENC( db ) )
{
zErrDyn = sqlite3MPrintf( db,
"attached databases must use the same text encoding as main database" );
rc = SQLITE_ERROR;
}
pPager = sqlite3BtreePager( aNew.pBt );
sqlite3PagerLockingMode( pPager, db.dfltLockMode );
sqlite3BtreeSecureDelete( aNew.pBt,
sqlite3BtreeSecureDelete( db.aDb[0].pBt, -1 ) );
}
aNew.safety_level = 3;
aNew.zName = zName;//sqlite3DbStrDup(db, zName);
//if( rc==SQLITE_OK && aNew.zName==0 ){
// rc = SQLITE_NOMEM;
//}
#if SQLITE_HAS_CODEC
if ( rc == SQLITE_OK )
{
//extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
//extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
int nKey;
string zKey;
int t = sqlite3_value_type( argv[2] );
switch ( t )
{
case SQLITE_INTEGER:
case SQLITE_FLOAT:
zErrDyn = "Invalid key value"; //sqlite3DbStrDup( db, "Invalid key value" );
rc = SQLITE_ERROR;
break;
case SQLITE_TEXT:
case SQLITE_BLOB:
nKey = sqlite3_value_bytes( argv[2] );
zKey = sqlite3_value_blob( argv[2] ).ToString(); // (char *)sqlite3_value_blob(argv[2]);
rc = sqlite3CodecAttach( db, db.nDb - 1, zKey, nKey );
break;
case SQLITE_NULL:
/* No key specified. Use the key from the main database */
sqlite3CodecGetKey( db, 0, out zKey, out nKey ); //sqlite3CodecGetKey(db, 0, (void**)&zKey, nKey);
if ( nKey > 0 || sqlite3BtreeGetReserve( db.aDb[0].pBt ) > 0 )
{
rc = sqlite3CodecAttach( db, db.nDb - 1, zKey, nKey );
}
break;
}
}
#endif
/* If the file was opened successfully, read the schema for the new database.
** If this fails, or if opening the file failed, then close the file and
** remove the entry from the db.aDb[] array. i.e. put everything back the way
** we found it.
*/
if ( rc == SQLITE_OK )
{
sqlite3BtreeEnterAll( db );
rc = sqlite3Init( db, ref zErrDyn );
sqlite3BtreeLeaveAll( db );
}
if ( rc != 0 )
{
int iDb = db.nDb - 1;
Debug.Assert( iDb >= 2 );
if ( db.aDb[iDb].pBt != null )
{
sqlite3BtreeClose( ref db.aDb[iDb].pBt );
db.aDb[iDb].pBt = null;
db.aDb[iDb].pSchema = null;
}
sqlite3ResetInternalSchema( db, -1 );
db.nDb = iDb;
if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM )
{
//// db.mallocFailed = 1;
sqlite3DbFree( db, ref zErrDyn );
zErrDyn = sqlite3MPrintf( db, "out of memory" );
}
else if ( zErrDyn == "" )
{
zErrDyn = sqlite3MPrintf( db, "unable to open database: %s", zFile );
}
goto attach_error;
}
return;
attach_error:
/* Return an error if we get here */
if ( zErrDyn != "" )
{
sqlite3_result_error( context, zErrDyn, -1 );
sqlite3DbFree( db, ref zErrDyn );
}
if ( rc != 0 )
sqlite3_result_error_code( context, rc );
}
/*
** An SQL user-function registered to do the work of an DETACH statement. The
** three arguments to the function come directly from a detach statement:
**
** DETACH DATABASE x
**
** SELECT sqlite_detach(x)
*/
static void detachFunc(
sqlite3_context context,
int NotUsed,
sqlite3_value[] argv
)
{
string zName = argv[0].z != null && ( argv[0].z.Length > 0 ) ? sqlite3_value_text( argv[0] ) : "";//(sqlite3_value_text(argv[0]);
sqlite3 db = sqlite3_context_db_handle( context );
int i;
Db pDb = null;
StringBuilder zErr = new StringBuilder( 200 );
UNUSED_PARAMETER( NotUsed );
if ( zName == null )
zName = "";
for ( i = 0; i < db.nDb; i++ )
{
pDb = db.aDb[i];
if ( pDb.pBt == null )
continue;
if ( pDb.zName.Equals( zName, StringComparison.InvariantCultureIgnoreCase ) )
break;
}
if ( i >= db.nDb )
{
sqlite3_snprintf( 200, zErr, "no such database: %s", zName );
goto detach_error;
}
if ( i < 2 )
{
sqlite3_snprintf( 200, zErr, "cannot detach database %s", zName );
goto detach_error;
}
if ( 0 == db.autoCommit )
{
sqlite3_snprintf( 200, zErr,
"cannot DETACH database within transaction" );
goto detach_error;
}
if ( sqlite3BtreeIsInReadTrans( pDb.pBt ) || sqlite3BtreeIsInBackup( pDb.pBt ) )
{
sqlite3_snprintf( 200, zErr, "database %s is locked", zName );
goto detach_error;
}
sqlite3BtreeClose( ref pDb.pBt );
pDb.pBt = null;
pDb.pSchema = null;
sqlite3ResetInternalSchema( db, -1 );
return;
detach_error:
sqlite3_result_error( context, zErr.ToString(), -1 );
}
/*
** This procedure generates VDBE code for a single invocation of either the
** sqlite_detach() or sqlite_attach() SQL user functions.
*/
static void codeAttach(
Parse pParse, /* The parser context */
int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
FuncDef pFunc, /* FuncDef wrapper for detachFunc() or attachFunc() */
Expr pAuthArg, /* Expression to pass to authorization callback */
Expr pFilename, /* Name of database file */
Expr pDbname, /* Name of the database to use internally */
Expr pKey /* Database key for encryption extension */
)
{
NameContext sName;
Vdbe v;
sqlite3 db = pParse.db;
int regArgs;
sName = new NameContext();// memset( &sName, 0, sizeof(NameContext));
sName.pParse = pParse;
if (
SQLITE_OK != resolveAttachExpr( sName, pFilename ) ||
SQLITE_OK != resolveAttachExpr( sName, pDbname ) ||
SQLITE_OK != resolveAttachExpr( sName, pKey )
)
{
pParse.nErr++;
goto attach_end;
}
#if !SQLITE_OMIT_AUTHORIZATION
if( pAuthArg ){
char *zAuthArg;
if( pAuthArg->op==TK_STRING ){
zAuthArg = pAuthArg->u.zToken;
}else{
zAuthArg = 0;
}
int rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
if(rc!=SQLITE_OK ){
goto attach_end;
}
}
#endif //* SQLITE_OMIT_AUTHORIZATION */
v = sqlite3GetVdbe( pParse );
regArgs = sqlite3GetTempRange( pParse, 4 );
sqlite3ExprCode( pParse, pFilename, regArgs );
sqlite3ExprCode( pParse, pDbname, regArgs + 1 );
sqlite3ExprCode( pParse, pKey, regArgs + 2 );
Debug.Assert( v != null /*|| db.mallocFailed != 0 */ );
if ( v != null )
{
sqlite3VdbeAddOp3( v, OP_Function, 0, regArgs + 3 - pFunc.nArg, regArgs + 3 );
Debug.Assert( pFunc.nArg == -1 || ( pFunc.nArg & 0xff ) == pFunc.nArg );
sqlite3VdbeChangeP5( v, (u8)( pFunc.nArg ) );
sqlite3VdbeChangeP4( v, -1, pFunc, P4_FUNCDEF );
/* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
** statement only). For DETACH, set it to false (expire all existing
** statements).
*/
sqlite3VdbeAddOp1( v, OP_Expire, ( type == SQLITE_ATTACH ) ? 1 : 0 );
}
attach_end:
sqlite3ExprDelete( db, ref pFilename );
sqlite3ExprDelete( db, ref pDbname );
sqlite3ExprDelete( db, ref pKey );
}
/*
** Called by the parser to compile a DETACH statement.
**
** DETACH pDbname
*/
static FuncDef detach_func = new FuncDef(
1, /* nArg */
SQLITE_UTF8, /* iPrefEnc */
0, /* flags */
null, /* pUserData */
null, /* pNext */
detachFunc, /* xFunc */
null, /* xStep */
null, /* xFinalize */
"sqlite_detach", /* zName */
null, /* pHash */
null /* pDestructor */
);
static void sqlite3Detach( Parse pParse, Expr pDbname )
{
codeAttach( pParse, SQLITE_DETACH, detach_func, pDbname, null, null, pDbname );
}
/*
** Called by the parser to compile an ATTACH statement.
**
** ATTACH p AS pDbname KEY pKey
*/
static FuncDef attach_func = new FuncDef(
3, /* nArg */
SQLITE_UTF8, /* iPrefEnc */
0, /* flags */
null, /* pUserData */
null, /* pNext */
attachFunc, /* xFunc */
null, /* xStep */
null, /* xFinalize */
"sqlite_attach", /* zName */
null, /* pHash */
null /* pDestructor */
);
static void sqlite3Attach( Parse pParse, Expr p, Expr pDbname, Expr pKey )
{
codeAttach( pParse, SQLITE_ATTACH, attach_func, p, p, pDbname, pKey );
}
#endif // * SQLITE_OMIT_ATTACH */
/*
** Initialize a DbFixer structure. This routine must be called prior
** to passing the structure to one of the sqliteFixAAAA() routines below.
**
** The return value indicates whether or not fixation is required. TRUE
** means we do need to fix the database references, FALSE means we do not.
*/
static int sqlite3FixInit(
DbFixer pFix, /* The fixer to be initialized */
Parse pParse, /* Error messages will be written here */
int iDb, /* This is the database that must be used */
string zType, /* "view", "trigger", or "index" */
Token pName /* Name of the view, trigger, or index */
)
{
sqlite3 db;
if ( NEVER( iDb < 0 ) || iDb == 1 )
return 0;
db = pParse.db;
Debug.Assert( db.nDb > iDb );
pFix.pParse = pParse;
pFix.zDb = db.aDb[iDb].zName;
pFix.zType = zType;
pFix.pName = pName;
return 1;
}
/*
** The following set of routines walk through the parse tree and assign
** a specific database to all table references where the database name
** was left unspecified in the original SQL statement. The pFix structure
** must have been initialized by a prior call to sqlite3FixInit().
**
** These routines are used to make sure that an index, trigger, or
** view in one database does not refer to objects in a different database.
** (Exception: indices, triggers, and views in the TEMP database are
** allowed to refer to anything.) If a reference is explicitly made
** to an object in a different database, an error message is added to
** pParse.zErrMsg and these routines return non-zero. If everything
** checks out, these routines return 0.
*/
static int sqlite3FixSrcList(
DbFixer pFix, /* Context of the fixation */
SrcList pList /* The Source list to check and modify */
)
{
int i;
string zDb;
SrcList_item pItem;
if ( NEVER( pList == null ) )
return 0;
zDb = pFix.zDb;
for ( i = 0; i < pList.nSrc; i++ )
{//, pItem++){
pItem = pList.a[i];
if ( pItem.zDatabase == null )
{
pItem.zDatabase = zDb;// sqlite3DbStrDup( pFix.pParse.db, zDb );
}
else if ( !pItem.zDatabase.Equals( zDb ,StringComparison.InvariantCultureIgnoreCase ) )
{
sqlite3ErrorMsg( pFix.pParse,
"%s %T cannot reference objects in database %s",
pFix.zType, pFix.pName, pItem.zDatabase );
return 1;
}
#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER
if ( sqlite3FixSelect( pFix, pItem.pSelect ) != 0 )
return 1;
if ( sqlite3FixExpr( pFix, pItem.pOn ) != 0 )
return 1;
#endif
}
return 0;
}
#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER
static int sqlite3FixSelect(
DbFixer pFix, /* Context of the fixation */
Select pSelect /* The SELECT statement to be fixed to one database */
)
{
while ( pSelect != null )
{
if ( sqlite3FixExprList( pFix, pSelect.pEList ) != 0 )
{
return 1;
}
if ( sqlite3FixSrcList( pFix, pSelect.pSrc ) != 0 )
{
return 1;
}
if ( sqlite3FixExpr( pFix, pSelect.pWhere ) != 0 )
{
return 1;
}
if ( sqlite3FixExpr( pFix, pSelect.pHaving ) != 0 )
{
return 1;
}
pSelect = pSelect.pPrior;
}
return 0;
}
static int sqlite3FixExpr(
DbFixer pFix, /* Context of the fixation */
Expr pExpr /* The expression to be fixed to one database */
)
{
while ( pExpr != null )
{
if ( ExprHasAnyProperty( pExpr, EP_TokenOnly ) )
break;
if ( ExprHasProperty( pExpr, EP_xIsSelect ) )
{
if ( sqlite3FixSelect( pFix, pExpr.x.pSelect ) != 0 )
return 1;
}
else
{
if ( sqlite3FixExprList( pFix, pExpr.x.pList ) != 0 )
return 1;
}
if ( sqlite3FixExpr( pFix, pExpr.pRight ) != 0 )
{
return 1;
}
pExpr = pExpr.pLeft;
}
return 0;
}
static int sqlite3FixExprList(
DbFixer pFix, /* Context of the fixation */
ExprList pList /* The expression to be fixed to one database */
)
{
int i;
ExprList_item pItem;
if ( pList == null )
return 0;
for ( i = 0; i < pList.nExpr; i++ )//, pItem++ )
{
pItem = pList.a[i];
if ( sqlite3FixExpr( pFix, pItem.pExpr ) != 0 )
{
return 1;
}
}
return 0;
}
#endif
#if !SQLITE_OMIT_TRIGGER
static int sqlite3FixTriggerStep(
DbFixer pFix, /* Context of the fixation */
TriggerStep pStep /* The trigger step be fixed to one database */
)
{
while ( pStep != null )
{
if ( sqlite3FixSelect( pFix, pStep.pSelect ) != 0 )
{
return 1;
}
if ( sqlite3FixExpr( pFix, pStep.pWhere ) != 0 )
{
return 1;
}
if ( sqlite3FixExprList( pFix, pStep.pExprList ) != 0 )
{
return 1;
}
pStep = pStep.pNext;
}
return 0;
}
#endif
}
}
|
Java
|
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
package com.spectralogic.ds3client.commands.parsers;
import com.spectralogic.ds3client.commands.parsers.interfaces.AbstractResponseParser;
import com.spectralogic.ds3client.commands.parsers.utils.ResponseParserUtils;
import com.spectralogic.ds3client.commands.spectrads3.ModifyUserSpectraS3Response;
import com.spectralogic.ds3client.models.SpectraUser;
import com.spectralogic.ds3client.networking.WebResponse;
import com.spectralogic.ds3client.serializer.XmlOutput;
import java.io.IOException;
import java.io.InputStream;
public class ModifyUserSpectraS3ResponseParser extends AbstractResponseParser<ModifyUserSpectraS3Response> {
private final int[] expectedStatusCodes = new int[]{200};
@Override
public ModifyUserSpectraS3Response parseXmlResponse(final WebResponse response) throws IOException {
final int statusCode = response.getStatusCode();
if (ResponseParserUtils.validateStatusCode(statusCode, expectedStatusCodes)) {
switch (statusCode) {
case 200:
try (final InputStream inputStream = response.getResponseStream()) {
final SpectraUser result = XmlOutput.fromXml(inputStream, SpectraUser.class);
return new ModifyUserSpectraS3Response(result, this.getChecksum(), this.getChecksumType());
}
default:
assert false: "validateStatusCode should have made it impossible to reach this line";
}
}
throw ResponseParserUtils.createFailedRequest(response, expectedStatusCodes);
}
}
|
Java
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.m.MessagePopover.
sap.ui.define(["jquery.sap.global", "./ResponsivePopover", "./Button", "./Toolbar", "./ToolbarSpacer", "./Bar", "./List",
"./StandardListItem", "./library", "sap/ui/core/Control", "./PlacementType", "sap/ui/core/IconPool",
"sap/ui/core/HTML", "./Text", "sap/ui/core/Icon", "./SegmentedButton", "./Page", "./NavContainer",
"./semantic/SemanticPage", "./Popover", "./MessagePopoverItem", "jquery.sap.dom"],
function (jQuery, ResponsivePopover, Button, Toolbar, ToolbarSpacer, Bar, List,
StandardListItem, library, Control, PlacementType, IconPool,
HTML, Text, Icon, SegmentedButton, Page, NavContainer, SemanticPage, Popover, MessagePopoverItem) {
"use strict";
/**
* Constructor for a new MessagePopover
*
* @param {string} [sId] ID for the new control, generated automatically if no id is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* A MessagePopover is a Popover containing a summarized list with messages.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.36.11
*
* @constructor
* @public
* @since 1.28
* @alias sap.m.MessagePopover
* @ui5-metamodel This control also will be described in the legacy UI5 design-time metamodel
*/
var MessagePopover = Control.extend("sap.m.MessagePopover", /** @lends sap.m.MessagePopover.prototype */ {
metadata: {
library: "sap.m",
properties: {
/**
* Callback function for resolving a promise after description has been asynchronously loaded inside this function
* @callback sap.m.MessagePopover~asyncDescriptionHandler
* @param {object} config A single parameter object
* @param {MessagePopoverItem} config.item Reference to respective MessagePopoverItem instance
* @param {object} config.promise Object grouping a promise's reject and resolve methods
* @param {function} config.promise.resolve Method to resolve promise
* @param {function} config.promise.reject Method to reject promise
*/
asyncDescriptionHandler: {type: "any", group: "Behavior", defaultValue: null},
/**
* Callback function for resolving a promise after a link has been asynchronously validated inside this function
* @callback sap.m.MessagePopover~asyncURLHandler
* @param {object} config A single parameter object
* @param {string} config.url URL to validate
* @param {string|Int} config.id ID of the validation job
* @param {object} config.promise Object grouping a promise's reject and resolve methods
* @param {function} config.promise.resolve Method to resolve promise
* @param {function} config.promise.reject Method to reject promise
*/
asyncURLHandler: {type: "any", group: "Behavior", defaultValue: null},
/**
* Determines the position, where the control will appear on the screen. Possible values are: sap.m.VerticalPlacementType.Top, sap.m.VerticalPlacementType.Bottom and sap.m.VerticalPlacementType.Vertical.
* The default value is sap.m.VerticalPlacementType.Vertical. Setting this property while the control is open, will not cause any re-rendering and changing of the position. Changes will only be applied with the next interaction.
*/
placement: {type: "sap.m.VerticalPlacementType", group: "Behavior", defaultValue: "Vertical"},
/**
* Sets the initial state of the control - expanded or collapsed. By default the control opens as expanded
*/
initiallyExpanded: {type: "boolean", group: "Behavior", defaultValue: true}
},
defaultAggregation: "items",
aggregations: {
/**
* A list with message items
*/
items: {type: "sap.m.MessagePopoverItem", multiple: true, singularName: "item"}
},
events: {
/**
* This event will be fired after the popover is opened
*/
afterOpen: {
parameters: {
/**
* This refers to the control which opens the popover
*/
openBy: {type: "sap.ui.core.Control"}
}
},
/**
* This event will be fired after the popover is closed
*/
afterClose: {
parameters: {
/**
* Refers to the control which opens the popover
*/
openBy: {type: "sap.ui.core.Control"}
}
},
/**
* This event will be fired before the popover is opened
*/
beforeOpen: {
parameters: {
/**
* Refers to the control which opens the popover
*/
openBy: {type: "sap.ui.core.Control"}
}
},
/**
* This event will be fired before the popover is closed
*/
beforeClose: {
parameters: {
/**
* Refers to the control which opens the popover
* See sap.ui.core.MessageType enum values for types
*/
openBy: {type: "sap.ui.core.Control"}
}
},
/**
* This event will be fired when description is shown
*/
itemSelect: {
parameters: {
/**
* Refers to the message popover item that is being presented
*/
item: {type: "sap.m.MessagePopoverItem"},
/**
* Refers to the type of messages being shown
* See sap.ui.core.MessageType values for types
*/
messageTypeFilter: {type: "sap.ui.core.MessageType"}
}
},
/**
* This event will be fired when one of the lists is shown when (not) filtered by type
*/
listSelect: {
parameters: {
/**
* This parameter refers to the type of messages being shown.
*/
messageTypeFilter: {type: "sap.ui.core.MessageType"}
}
},
/**
* This event will be fired when the long text description data from a remote URL is loaded
*/
longtextLoaded: {},
/**
* This event will be fired when a validation of a URL from long text description is ready
*/
urlValidated: {}
}
}
});
var CSS_CLASS = "sapMMsgPopover",
ICONS = {
back: IconPool.getIconURI("nav-back"),
close: IconPool.getIconURI("decline"),
information: IconPool.getIconURI("message-information"),
warning: IconPool.getIconURI("message-warning"),
error: IconPool.getIconURI("message-error"),
success: IconPool.getIconURI("message-success")
},
LIST_TYPES = ["all", "error", "warning", "success", "information"],
// Property names array
ASYNC_HANDLER_NAMES = ["asyncDescriptionHandler", "asyncURLHandler"],
// Private class variable used for static method below that sets default async handlers
DEFAULT_ASYNC_HANDLERS = {
asyncDescriptionHandler: function (config) {
var sLongTextUrl = config.item.getLongtextUrl();
if (sLongTextUrl) {
jQuery.ajax({
type: "GET",
url: sLongTextUrl,
success: function (data) {
config.item.setDescription(data);
config.promise.resolve();
},
error: function() {
var sError = "A request has failed for long text data. URL: " + sLongTextUrl;
jQuery.sap.log.error(sError);
config.promise.reject(sError);
}
});
}
}
};
/**
* Setter for default description and URL validation callbacks across all instances of MessagePopover
* @static
* @protected
* @param {object} mDefaultHandlers An object setting default callbacks
* @param {function} mDefaultHandlers.asyncDescriptionHandler
* @param {function} mDefaultHandlers.asyncURLHandler
*/
MessagePopover.setDefaultHandlers = function (mDefaultHandlers) {
ASYNC_HANDLER_NAMES.forEach(function (sFuncName) {
if (mDefaultHandlers.hasOwnProperty(sFuncName)) {
DEFAULT_ASYNC_HANDLERS[sFuncName] = mDefaultHandlers[sFuncName];
}
});
};
/**
* Initializes the control
*
* @override
* @private
*/
MessagePopover.prototype.init = function () {
var that = this;
var oPopupControl;
this._oResourceBundle = sap.ui.getCore().getLibraryResourceBundle("sap.m");
this._oPopover = new ResponsivePopover(this.getId() + "-messagePopover", {
showHeader: false,
contentWidth: "440px",
placement: this.getPlacement(),
showCloseButton: false,
modal: false,
afterOpen: function (oEvent) {
that.fireAfterOpen({openBy: oEvent.getParameter("openBy")});
},
afterClose: function (oEvent) {
that._navContainer.backToTop();
that.fireAfterClose({openBy: oEvent.getParameter("openBy")});
},
beforeOpen: function (oEvent) {
that.fireBeforeOpen({openBy: oEvent.getParameter("openBy")});
},
beforeClose: function (oEvent) {
that.fireBeforeClose({openBy: oEvent.getParameter("openBy")});
}
}).addStyleClass(CSS_CLASS);
this._createNavigationPages();
this._createLists();
oPopupControl = this._oPopover.getAggregation("_popup");
oPopupControl.oPopup.setAutoClose(false);
oPopupControl.addEventDelegate({
onBeforeRendering: this.onBeforeRenderingPopover,
onkeypress: this._onkeypress
}, this);
if (sap.ui.Device.system.phone) {
this._oPopover.setBeginButton(new Button({
text: this._oResourceBundle.getText("MESSAGEPOPOVER_CLOSE"),
press: this.close.bind(this)
}));
}
// Check for default async handlers and set them appropriately
ASYNC_HANDLER_NAMES.forEach(function (sFuncName) {
if (DEFAULT_ASYNC_HANDLERS.hasOwnProperty(sFuncName)) {
that.setProperty(sFuncName, DEFAULT_ASYNC_HANDLERS[sFuncName]);
}
});
};
/**
* Called when the control is destroyed
*
* @private
*/
MessagePopover.prototype.exit = function () {
this._oResourceBundle = null;
this._oListHeader = null;
this._oDetailsHeader = null;
this._oSegmentedButton = null;
this._oBackButton = null;
this._navContainer = null;
this._listPage = null;
this._detailsPage = null;
this._sCurrentList = null;
if (this._oLists) {
this._destroyLists();
}
// Destroys ResponsivePopover control that is used by MessagePopover
// This will walk through all aggregations in the Popover and destroy them (in our case this is NavContainer)
// Next this will walk through all aggregations in the NavContainer, etc.
if (this._oPopover) {
this._oPopover.destroy();
this._oPopover = null;
}
};
/**
* Required adaptations before rendering MessagePopover
*
* @private
*/
MessagePopover.prototype.onBeforeRenderingPopover = function () {
// Bind automatically to the MessageModel if no items are bound
if (!this.getBindingInfo("items")) {
this._makeAutomaticBinding();
}
// Update lists only if 'items' aggregation is changed
if (this._bItemsChanged) {
this._clearLists();
this._fillLists(this.getItems());
this._clearSegmentedButton();
this._fillSegmentedButton();
this._bItemsChanged = false;
}
this._setInitialFocus();
};
/**
* Makes automatic binding to the Message Model with default template
*
* @private
*/
MessagePopover.prototype._makeAutomaticBinding = function () {
this.setModel(sap.ui.getCore().getMessageManager().getMessageModel(), "message");
this.bindAggregation("items",
{
path: "message>/",
template: new MessagePopoverItem({
type: "{message>type}",
title: "{message>title}",
description: "{message>description}",
longtextUrl: "{message>longtextUrl}"
})
}
);
};
/**
* Handles keyup event
*
* @param {jQuery.Event} oEvent - keyup event object
* @private
*/
MessagePopover.prototype._onkeypress = function (oEvent) {
if (oEvent.shiftKey && oEvent.keyCode == jQuery.sap.KeyCodes.ENTER) {
this._fnHandleBackPress();
}
};
/**
* Returns header of the MessagePopover's ListPage
*
* @returns {sap.m.Toolbar} ListPage header
* @private
*/
MessagePopover.prototype._getListHeader = function () {
return this._oListHeader || this._createListHeader();
};
/**
* Returns header of the MessagePopover's ListPage
*
* @returns {sap.m.Toolbar} DetailsPage header
* @private
*/
MessagePopover.prototype._getDetailsHeader = function () {
return this._oDetailsHeader || this._createDetailsHeader();
};
/**
* Creates header of MessagePopover's ListPage
*
* @returns {sap.m.Toolbar} ListPage header
* @private
*/
MessagePopover.prototype._createListHeader = function () {
var sCloseBtnDescr = this._oResourceBundle.getText("MESSAGEPOPOVER_CLOSE");
var sCloseBtnDescrId = this.getId() + "-CloseBtnDescr";
var oCloseBtnARIAHiddenDescr = new HTML(sCloseBtnDescrId, {
content: "<span id=\"" + sCloseBtnDescrId + "\" style=\"display: none;\">" + sCloseBtnDescr + "</span>"
});
var sHeadingDescr = this._oResourceBundle.getText("MESSAGEPOPOVER_ARIA_HEADING");
var sHeadingDescrId = this.getId() + "-HeadingDescr";
var oHeadingARIAHiddenDescr = new HTML(sHeadingDescrId, {
content: "<span id=\"" + sHeadingDescrId + "\" style=\"display: none;\" role=\"heading\">" + sHeadingDescr + "</span>"
});
this._oPopover.addAssociation("ariaDescribedBy", sHeadingDescrId, true);
var oCloseBtn = new Button({
icon: ICONS["close"],
visible: !sap.ui.Device.system.phone,
ariaLabelledBy: oCloseBtnARIAHiddenDescr,
tooltip: sCloseBtnDescr,
press: this.close.bind(this)
}).addStyleClass(CSS_CLASS + "CloseBtn");
this._oSegmentedButton = new SegmentedButton(this.getId() + "-segmented", {}).addStyleClass("sapMSegmentedButtonNoAutoWidth");
this._oListHeader = new Toolbar({
content: [this._oSegmentedButton, new ToolbarSpacer(), oCloseBtn, oCloseBtnARIAHiddenDescr, oHeadingARIAHiddenDescr]
});
return this._oListHeader;
};
/**
* Creates header of MessagePopover's ListPage
*
* @returns {sap.m.Toolbar} DetailsPage header
* @private
*/
MessagePopover.prototype._createDetailsHeader = function () {
var sCloseBtnDescr = this._oResourceBundle.getText("MESSAGEPOPOVER_CLOSE");
var sCloseBtnDescrId = this.getId() + "-CloseBtnDetDescr";
var oCloseBtnARIAHiddenDescr = new HTML(sCloseBtnDescrId, {
content: "<span id=\"" + sCloseBtnDescrId + "\" style=\"display: none;\">" + sCloseBtnDescr + "</span>"
});
var sBackBtnDescr = this._oResourceBundle.getText("MESSAGEPOPOVER_ARIA_BACK_BUTTON");
var sBackBtnDescrId = this.getId() + "-BackBtnDetDescr";
var oBackBtnARIAHiddenDescr = new HTML(sBackBtnDescrId, {
content: "<span id=\"" + sBackBtnDescrId + "\" style=\"display: none;\">" + sBackBtnDescr + "</span>"
});
var oCloseBtn = new Button({
icon: ICONS["close"],
visible: !sap.ui.Device.system.phone,
ariaLabelledBy: oCloseBtnARIAHiddenDescr,
tooltip: sCloseBtnDescr,
press: this.close.bind(this)
}).addStyleClass(CSS_CLASS + "CloseBtn");
this._oBackButton = new Button({
icon: ICONS["back"],
press: this._fnHandleBackPress.bind(this),
ariaLabelledBy: oBackBtnARIAHiddenDescr,
tooltip: sBackBtnDescr
});
this._oDetailsHeader = new Toolbar({
content: [this._oBackButton, new ToolbarSpacer(), oCloseBtn, oCloseBtnARIAHiddenDescr, oBackBtnARIAHiddenDescr]
});
return this._oDetailsHeader;
};
/**
* Creates navigation pages
*
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
* @private
*/
MessagePopover.prototype._createNavigationPages = function () {
// Create two main pages
this._listPage = new Page(this.getId() + "listPage", {
customHeader: this._getListHeader()
});
this._detailsPage = new Page(this.getId() + "-detailsPage", {
customHeader: this._getDetailsHeader()
});
// TODO: check if this is the best location for this
// Disable clicks on disabled and/or pending links
this._detailsPage.addEventDelegate({
onclick: function(oEvent) {
var target = oEvent.target;
if (target.nodeName.toUpperCase() === 'A' &&
(target.className.indexOf('sapMMsgPopoverItemDisabledLink') !== -1 ||
target.className.indexOf('sapMMsgPopoverItemPendingLink') !== -1)) {
oEvent.preventDefault();
}
}
});
// Initialize nav container with two main pages
this._navContainer = new NavContainer(this.getId() + "-navContainer", {
initialPage: this.getId() + "listPage",
pages: [this._listPage, this._detailsPage],
navigate: this._navigate.bind(this),
afterNavigate: this._afterNavigate.bind(this)
});
// Assign nav container to content of _oPopover
this._oPopover.addContent(this._navContainer);
return this;
};
/**
* Creates Lists of the MessagePopover
*
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
* @private
*/
MessagePopover.prototype._createLists = function () {
this._oLists = {};
LIST_TYPES.forEach(function (sListName) {
this._oLists[sListName] = new List({
itemPress: this._fnHandleItemPress.bind(this),
visible: false
});
// no re-rendering
this._listPage.addAggregation("content", this._oLists[sListName], true);
}, this);
return this;
};
/**
* Destroy items in the MessagePopover's Lists
*
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
* @private
*/
MessagePopover.prototype._clearLists = function () {
LIST_TYPES.forEach(function (sListName) {
if (this._oLists[sListName]) {
this._oLists[sListName].destroyAggregation("items", true);
}
}, this);
return this;
};
/**
* Destroys internal Lists of the MessagePopover
*
* @private
*/
MessagePopover.prototype._destroyLists = function () {
LIST_TYPES.forEach(function (sListName) {
this._oLists[sListName] = null;
}, this);
this._oLists = null;
};
/**
* Fill the list with items
*
* @param {array} aItems An array with items type of sap.ui.core.Item.
* @private
*/
MessagePopover.prototype._fillLists = function (aItems) {
aItems.forEach(function (oMessagePopoverItem) {
var oListItem = this._mapItemToListItem(oMessagePopoverItem),
oCloneListItem = this._mapItemToListItem(oMessagePopoverItem);
// add the mapped item to the List
this._oLists["all"].addAggregation("items", oListItem, true);
this._oLists[oMessagePopoverItem.getType().toLowerCase()].addAggregation("items", oCloneListItem, true);
}, this);
};
/**
* Map a MessagePopoverItem to StandardListItem
*
* @param {sap.m.MessagePopoverItem} oMessagePopoverItem Base information to generate the list items
* @returns {sap.m.StandardListItem | null} oListItem List item which will be displayed
* @private
*/
MessagePopover.prototype._mapItemToListItem = function (oMessagePopoverItem) {
if (!oMessagePopoverItem) {
return null;
}
var sType = oMessagePopoverItem.getType(),
oListItem = new StandardListItem({
title: oMessagePopoverItem.getTitle(),
icon: this._mapIcon(sType),
type: sap.m.ListType.Navigation
}).addStyleClass(CSS_CLASS + "Item").addStyleClass(CSS_CLASS + "Item" + sType);
oListItem._oMessagePopoverItem = oMessagePopoverItem;
return oListItem;
};
/**
* Map an MessageType to the Icon URL.
*
* @param {sap.ui.core.ValueState} sIcon Type of Error
* @returns {string | null} Icon string
* @private
*/
MessagePopover.prototype._mapIcon = function (sIcon) {
if (!sIcon) {
return null;
}
return ICONS[sIcon.toLowerCase()];
};
/**
* Destroy the buttons in the SegmentedButton
*
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
* @private
*/
MessagePopover.prototype._clearSegmentedButton = function () {
if (this._oSegmentedButton) {
this._oSegmentedButton.destroyAggregation("buttons", true);
}
return this;
};
/**
* Fill SegmentedButton with needed Buttons for filtering
*
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
* @private
*/
MessagePopover.prototype._fillSegmentedButton = function () {
var that = this;
var pressClosure = function (sListName) {
return function () {
that._fnFilterList(sListName);
};
};
LIST_TYPES.forEach(function (sListName) {
var oList = this._oLists[sListName],
iCount = oList.getItems().length,
oButton;
if (iCount > 0) {
oButton = new Button(this.getId() + "-" + sListName, {
text: sListName == "all" ? this._oResourceBundle.getText("MESSAGEPOPOVER_ALL") : iCount,
icon: ICONS[sListName],
press: pressClosure(sListName)
}).addStyleClass(CSS_CLASS + "Btn" + sListName.charAt(0).toUpperCase() + sListName.slice(1));
this._oSegmentedButton.addButton(oButton, true);
}
}, this);
return this;
};
/**
* Sets icon in details page
* @param {sap.m.MessagePopoverItem} oMessagePopoverItem
* @param {sap.m.StandardListItem} oListItem
* @private
*/
MessagePopover.prototype._setIcon = function (oMessagePopoverItem, oListItem) {
this._previousIconTypeClass = CSS_CLASS + "DescIcon" + oMessagePopoverItem.getType();
this._oMessageIcon = new Icon({
src: oListItem.getIcon()
})
.addStyleClass(CSS_CLASS + "DescIcon")
.addStyleClass(this._previousIconTypeClass);
this._detailsPage.addContent(this._oMessageIcon);
};
/**
* Sets title part of details page
* @param {sap.m.MessagePopoverItem} oMessagePopoverItem
* @private
*/
MessagePopover.prototype._setTitle = function (oMessagePopoverItem) {
this._oMessageTitleText = new Text(this.getId() + 'MessageTitleText', {
text: oMessagePopoverItem.getTitle()
}).addStyleClass('sapMMsgPopoverTitleText');
this._detailsPage.addAggregation("content", this._oMessageTitleText);
};
/**
* Sets description text part of details page
* When markup description is used it is sanitized within it's container's setter method (MessagePopoverItem)
* @param {sap.m.MessagePopoverItem} oMessagePopoverItem
* @private
*/
MessagePopover.prototype._setDescription = function (oMessagePopoverItem) {
if (oMessagePopoverItem.getMarkupDescription()) {
// description is sanitized in MessagePopoverItem.setDescription()
this._oMessageDescriptionText = new HTML(this.getId() + 'MarkupDescription', {
content: "<div class='markupDescription'>" + oMessagePopoverItem.getDescription() + "</div>"
});
} else {
this._oMessageDescriptionText = new Text(this.getId() + 'MessageDescriptionText', {
text: oMessagePopoverItem.getDescription()
}).addStyleClass('sapMMsgPopoverDescriptionText');
}
this._detailsPage.addContent(this._oMessageDescriptionText);
};
MessagePopover.prototype._iNextValidationTaskId = 0;
MessagePopover.prototype._validateURL = function (sUrl) {
if (jQuery.sap.validateUrl(sUrl)) {
return sUrl;
}
jQuery.sap.log.warning("You have entered invalid URL");
return '';
};
MessagePopover.prototype._queueValidation = function (href) {
var fnAsyncURLHandler = this.getAsyncURLHandler();
var iValidationTaskId = ++this._iNextValidationTaskId;
var oPromiseArgument = {};
var oPromise = new window.Promise(function(resolve, reject) {
oPromiseArgument.resolve = resolve;
oPromiseArgument.reject = reject;
var config = {
url: href,
id: iValidationTaskId,
promise: oPromiseArgument
};
fnAsyncURLHandler(config);
});
oPromise.id = iValidationTaskId;
return oPromise;
};
MessagePopover.prototype._getTagPolicy = function () {
var that = this,
i;
/*global html*/
var defaultTagPolicy = html.makeTagPolicy(this._validateURL());
return function customTagPolicy(tagName, attrs) {
var href,
validateLink = false;
if (tagName.toUpperCase() === "A") {
for (i = 0; i < attrs.length;) {
// if there is href the link should be validated, href's value is on position(i+1)
if (attrs[i] === "href") {
validateLink = true;
href = attrs[i + 1];
attrs.splice(0, 2);
continue;
}
i += 2;
}
}
// let the default sanitizer do its work
// it won't see the href attribute
attrs = defaultTagPolicy(tagName, attrs);
// if we detected a link before, we modify the <A> tag
// and keep the link in a dataset attribute
if (validateLink && typeof that.getAsyncURLHandler() === "function") {
attrs = attrs || [];
var done = false;
// first check if there is a class attribute and enrich it with 'sapMMsgPopoverItemDisabledLink'
for (i = 0; i < attrs.length; i += 2) {
if (attrs[i] === "class") {
attrs[i + 1] += "sapMMsgPopoverItemDisabledLink sapMMsgPopoverItemPendingLink";
done = true;
break;
}
}
// check for existing id
var indexOfId = attrs.indexOf("id");
if (indexOfId > -1) {
// we start backwards
attrs.splice(indexOfId + 1, 1);
attrs.splice(indexOfId, 1);
}
// if no class attribute was found, add one
if (!done) {
attrs.unshift("sapMMsgPopoverItemDisabledLink sapMMsgPopoverItemPendingLink");
attrs.unshift("class");
}
var oValidation = that._queueValidation(href);
// add other attributes
attrs.push("href");
// the link is deactivated via class names later read by event delegate on the description page
attrs.push(href);
// let the page open in another window, so state is preserved
attrs.push("target");
attrs.push("_blank");
// use id here as data attributes are not passing through caja
attrs.push("id");
attrs.push("sap-ui-" + that.getId() + "-link-under-validation-" + oValidation.id);
oValidation
.then(function (result) {
// Update link in output
var $link = jQuery.sap.byId("sap-ui-" + that.getId() + "-link-under-validation-" + result.id);
if (result.allowed) {
jQuery.sap.log.info("Allow link " + href);
} else {
jQuery.sap.log.info("Disallow link " + href);
}
// Adapt the link style
$link.removeClass('sapMMsgPopoverItemPendingLink');
$link.toggleClass('sapMMsgPopoverItemDisabledLink', !result.allowed);
that.fireUrlValidated();
})
.catch(function () {
jQuery.sap.log.warning("Async URL validation could not be performed.");
});
}
return attrs;
};
};
/**
* Perform description sanitization based on Caja HTML sanitizer
* @param {sap.m.MessagePopoverItem} oMessagePopoverItem
* @private
*/
MessagePopover.prototype._sanitizeDescription = function (oMessagePopoverItem) {
jQuery.sap.require("jquery.sap.encoder");
jQuery.sap.require("sap.ui.thirdparty.caja-html-sanitizer");
var tagPolicy = this._getTagPolicy();
/*global html*/
var sanitized = html.sanitizeWithPolicy(oMessagePopoverItem.getDescription(), tagPolicy);
oMessagePopoverItem.setDescription(sanitized);
this._setDescription(oMessagePopoverItem);
};
/**
* Handles click of the ListItems
*
* @param {jQuery.Event} oEvent ListItem click event object
* @private
*/
MessagePopover.prototype._fnHandleItemPress = function (oEvent) {
var oListItem = oEvent.getParameter("listItem"),
oMessagePopoverItem = oListItem._oMessagePopoverItem;
var asyncDescHandler = this.getAsyncDescriptionHandler();
var loadAndNavigateToDetailsPage = function (suppressNavigate) {
this._setTitle(oMessagePopoverItem);
this._sanitizeDescription(oMessagePopoverItem);
this._setIcon(oMessagePopoverItem, oListItem);
this.fireLongtextLoaded();
if (!suppressNavigate) {
this._navContainer.to(this._detailsPage);
}
}.bind(this);
this._previousIconTypeClass = this._previousIconTypeClass || '';
this.fireItemSelect({
item: oMessagePopoverItem,
messageTypeFilter: this._getCurrentMessageTypeFilter()
});
this._detailsPage.destroyContent();
if (typeof asyncDescHandler === "function" && !!oMessagePopoverItem.getLongtextUrl()) {
// Set markupDescription to true as markup description should be processed as markup
oMessagePopoverItem.setMarkupDescription(true);
var oPromiseArgument = {};
var oPromise = new window.Promise(function (resolve, reject) {
oPromiseArgument.resolve = resolve;
oPromiseArgument.reject = reject;
});
var proceed = function () {
this._detailsPage.setBusy(false);
loadAndNavigateToDetailsPage(true);
}.bind(this);
oPromise
.then(function () {
proceed();
})
.catch(function () {
jQuery.sap.log.warning("Async description loading could not be performed.");
proceed();
});
this._navContainer.to(this._detailsPage);
this._detailsPage.setBusy(true);
asyncDescHandler({
promise: oPromiseArgument,
item: oMessagePopoverItem
});
} else {
loadAndNavigateToDetailsPage();
}
this._listPage.$().attr("aria-hidden", "true");
};
/**
* Handles click of the BackButton
*
* @private
*/
MessagePopover.prototype._fnHandleBackPress = function () {
this._listPage.$().removeAttr("aria-hidden");
this._navContainer.back();
};
/**
* Handles click of the SegmentedButton
*
* @param {string} sCurrentListName ListName to be shown
* @private
*/
MessagePopover.prototype._fnFilterList = function (sCurrentListName) {
LIST_TYPES.forEach(function (sListIterName) {
if (sListIterName != sCurrentListName && this._oLists[sListIterName].getVisible()) {
// Hide Lists if they are visible and their name is not the same as current list name
this._oLists[sListIterName].setVisible(false);
}
}, this);
this._sCurrentList = sCurrentListName;
this._oLists[sCurrentListName].setVisible(true);
this._expandMsgPopover();
this.fireListSelect({messageTypeFilter: this._getCurrentMessageTypeFilter()});
};
/**
* Returns current selected List name
*
* @returns {string} Current list name
* @private
*/
MessagePopover.prototype._getCurrentMessageTypeFilter = function () {
return this._sCurrentList == "all" ? "" : this._sCurrentList;
};
/**
* Handles navigate event of the NavContainer
*
* @private
*/
MessagePopover.prototype._navigate = function () {
if (this._isListPage()) {
this._oRestoreFocus = jQuery(document.activeElement);
}
};
/**
* Handles navigate event of the NavContainer
*
* @private
*/
MessagePopover.prototype._afterNavigate = function () {
// Just wait for the next tick to apply the focus
jQuery.sap.delayedCall(0, this, this._restoreFocus);
};
/**
* Checks whether the current page is ListPage
*
* @returns {boolean} Whether the current page is ListPage
* @private
*/
MessagePopover.prototype._isListPage = function () {
return (this._navContainer.getCurrentPage() == this._listPage);
};
/**
* Sets initial focus of the control
*
* @private
*/
MessagePopover.prototype._setInitialFocus = function () {
if (this._isListPage()) {
// if current page is the list page - set initial focus to the list.
// otherwise use default functionality built-in the popover
this._oPopover.setInitialFocus(this._oLists[this._sCurrentList]);
}
};
/**
* Restores the focus after navigation
*
* @private
*/
MessagePopover.prototype._restoreFocus = function () {
if (this._isListPage()) {
var oRestoreFocus = this._oRestoreFocus && this._oRestoreFocus.control(0);
if (oRestoreFocus) {
oRestoreFocus.focus();
}
} else {
this._oBackButton.focus();
}
};
/**
* Restores the state defined by the initiallyExpanded property of the MessagePopover
* @private
*/
MessagePopover.prototype._restoreExpansionDefaults = function () {
if (this.getInitiallyExpanded()) {
this._fnFilterList("all");
this._oSegmentedButton.setSelectedButton(null);
} else {
this._collapseMsgPopover();
}
};
/**
* Expands the MessagePopover so that the width and height are equal
* @private
*/
MessagePopover.prototype._expandMsgPopover = function () {
this._oPopover
.setContentHeight(this._oPopover.getContentWidth())
.removeStyleClass(CSS_CLASS + "-init");
};
/**
* Sets the height of the MessagePopover to auto so that only the header with
* the SegmentedButton is visible
* @private
*/
MessagePopover.prototype._collapseMsgPopover = function () {
LIST_TYPES.forEach(function (sListName) {
this._oLists[sListName].setVisible(false);
}, this);
this._oPopover
.addStyleClass(CSS_CLASS + "-init")
.setContentHeight("auto");
this._oSegmentedButton.setSelectedButton("none");
};
/**
* Opens the MessagePopover
*
* @param {sap.ui.core.Control} oControl Control which opens the MessagePopover
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
* @public
* @ui5-metamodel
*/
MessagePopover.prototype.openBy = function (oControl) {
var oResponsivePopoverControl = this._oPopover.getAggregation("_popup"),
oParent = oControl.getParent();
// If MessagePopover is opened from an instance of sap.m.Toolbar and is instance of sap.m.Popover remove the Arrow
if (oResponsivePopoverControl instanceof Popover) {
if ((oParent instanceof Toolbar || oParent instanceof Bar || oParent instanceof SemanticPage)) {
oResponsivePopoverControl.setShowArrow(false);
} else {
oResponsivePopoverControl.setShowArrow(true);
}
}
if (this._oPopover) {
this._restoreExpansionDefaults();
this._oPopover.openBy(oControl);
}
return this;
};
/**
* Closes the MessagePopover
*
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
* @public
*/
MessagePopover.prototype.close = function () {
if (this._oPopover) {
this._oPopover.close();
}
return this;
};
/**
* The method checks if the MessagePopover is open. It returns true when the MessagePopover is currently open
* (this includes opening and closing animations), otherwise it returns false
*
* @public
* @returns {boolean} Whether the MessagePopover is open
*/
MessagePopover.prototype.isOpen = function () {
return this._oPopover.isOpen();
};
/**
* This method toggles between open and closed state of the MessagePopover instance.
* oControl parameter is mandatory in the same way as in 'openBy' method
*
* @param {sap.ui.core.Control} oControl Control which opens the MessagePopover
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
* @public
*/
MessagePopover.prototype.toggle = function (oControl) {
if (this.isOpen()) {
this.close();
} else {
this.openBy(oControl);
}
return this;
};
/**
* The method sets the placement position of the MessagePopover. Only accepted Values are:
* sap.m.PlacementType.Top, sap.m.PlacementType.Bottom and sap.m.PlacementType.Vertical
*
* @param {sap.m.PlacementType} sPlacement Placement type
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
*/
MessagePopover.prototype.setPlacement = function (sPlacement) {
this.setProperty("placement", sPlacement, true);
this._oPopover.setPlacement(sPlacement);
return this;
};
MessagePopover.prototype.getDomRef = function (sSuffix) {
return this._oPopover && this._oPopover.getAggregation("_popup").getDomRef(sSuffix);
};
["addStyleClass", "removeStyleClass", "toggleStyleClass", "hasStyleClass", "getBusyIndicatorDelay",
"setBusyIndicatorDelay", "getVisible", "setVisible", "getBusy", "setBusy"].forEach(function(sName){
MessagePopover.prototype[sName] = function() {
if (this._oPopover && this._oPopover[sName]) {
var oPopover = this._oPopover;
var res = oPopover[sName].apply(oPopover, arguments);
return res === oPopover ? this : res;
}
};
});
// The following inherited methods of this control are extended because this control uses ResponsivePopover for rendering
["setModel", "bindAggregation", "setAggregation", "insertAggregation", "addAggregation",
"removeAggregation", "removeAllAggregation", "destroyAggregation"].forEach(function (sFuncName) {
// First, they are saved for later reference
MessagePopover.prototype["_" + sFuncName + "Old"] = MessagePopover.prototype[sFuncName];
// Once they are called
MessagePopover.prototype[sFuncName] = function () {
// We immediately call the saved method first
var result = MessagePopover.prototype["_" + sFuncName + "Old"].apply(this, arguments);
// Then there is additional logic
// Mark items aggregation as changed and invalidate popover to trigger rendering
// See 'MessagePopover.prototype.onBeforeRenderingPopover'
this._bItemsChanged = true;
// If Popover dependency has already been instantiated ...
if (this._oPopover) {
// ... invalidate it
this._oPopover.invalidate();
}
// If the called method is 'removeAggregation' or 'removeAllAggregation' ...
if (["removeAggregation", "removeAllAggregation"].indexOf(sFuncName) !== -1) {
// ... return the result of the operation
return result;
}
return this;
};
});
return MessagePopover;
}, /* bExport= */ true);
|
Java
|
using BdlIBMS.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BdlIBMS.Repositories
{
public interface IUserRepository : IRepository<string, User>
{
User FindByUserNameAndPassword(string userName, string password);
}
}
|
Java
|
<div class="table-overflow overflow">
<table class="efor-table-logs mdl-data-table mdl-shadow--2dp">
<thead>
<tr>
<th class="mdl-data-table__cell--non-numeric">Nombre</th>
<th class="mdl-data-table__cell--non-numeric" width="280px">Email</th>
<th class="mdl-data-table__cell--non-numeric">Apellido</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td class="text-a-left" data-title="Nombre">{[{user.first_name}]}</td>
<td class="text-a-left" data-title="email">
<a ng-href="{[{user.email}]}" class="text-overflow">{[{user.email}]}</a>
</td>
<td class="text-a-left" data-title="Apellido">
{[{user.last_name}]}
<button id="menu-lower-right-{[{$index}]}" class="button-to-right mdl-button mdl-js-button mdl-button--icon">
<i class="material-icons">more_vert</i>
</button>
<ul class="efor-menu efor-menu__small mdl-menu mdl-menu--bottom-right mdl-js-menu mdl-js-ripple-effect" for="menu-lower-right-{[{$index}]}">
<li class="mdl-menu__item" ng-click="openDelete(user)">
<i class="material-icons">delete</i>
{[{'user_delete_title' | translate}]}
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
|
Java
|
package com.github.particlesystem.modifiers;
import com.github.particlesystem.Particle;
public interface ParticleModifier {
/**
* modifies the specific value of a particle given the current miliseconds
*
* @param particle
* @param miliseconds
*/
void apply(Particle particle, long miliseconds);
}
|
Java
|
package com.ftfl.icare;
import java.util.List;
import com.ftfl.icare.adapter.CustomAppointmentAdapter;
import com.ftfl.icare.adapter.CustomDoctorAdapter;
import com.ftfl.icare.helper.AppointmentDataSource;
import com.ftfl.icare.helper.DoctorProfileDataSource;
import com.ftfl.icare.model.Appointment;
import com.ftfl.icare.model.DoctorProfile;
import com.ftfl.icare.util.FragmentHome;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentAppointmentList extends Fragment {
TextView mId_tv = null;
AppointmentDataSource mAppointmentDataSource;
Appointment mAppointment;
FragmentManager mFrgManager;
Fragment mFragment;
Context mContext;
ListView mLvProfileList;
List<Appointment> mDoctorProfileList;
String mId;
Bundle mArgs = new Bundle();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_doctor_list, container,
false);
mContext = container.getContext();
mAppointmentDataSource = new AppointmentDataSource(getActivity());
mDoctorProfileList = mAppointmentDataSource.appointmentList();
CustomAppointmentAdapter arrayAdapter = new CustomAppointmentAdapter(
getActivity(), mDoctorProfileList);
mLvProfileList = (ListView) view.findViewById(R.id.lvDoctorList);
mLvProfileList.setAdapter(arrayAdapter);
mLvProfileList
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final int pos = position;
new AlertDialog.Builder(mContext)
.setTitle("Delete entry")
.setMessage(
"Are you sure you want to delete this entry?")
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
mAppointmentDataSource = new AppointmentDataSource(
getActivity());
if (mAppointmentDataSource.deleteData(Integer
.parseInt(mDoctorProfileList
.get(pos)
.getId())) == true) {
Toast toast = Toast
.makeText(
getActivity(),
"Successfully Deleted.",
Toast.LENGTH_LONG);
toast.show();
mFragment = new FragmentHome();
mFrgManager = getFragmentManager();
mFrgManager
.beginTransaction()
.replace(
R.id.content_frame,
mFragment)
.commit();
setTitle("Home");
} else {
Toast toast = Toast
.makeText(
getActivity(),
"Error, Couldn't inserted data to database",
Toast.LENGTH_LONG);
toast.show();
}
}
})
.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
return view;
}
public void setTitle(CharSequence title) {
getActivity().getActionBar().setTitle(title);
}
}
|
Java
|
---
title: IDEA
date: 2017-05-27 10:50:00
tags: idea
categories: tools
---
## [下载](https://confluence.jetbrains.com/display/IDEADEV/IDEA+14.1+EAP)
- [Windows](https://download.jetbrains.com/idea/ideaIU-14.1.7.zip)
- [OS X](https://download.jetbrains.com/idea/ideaIU-14.1.7.dmg)
- [Linux](https://download.jetbrains.com/idea/ideaIU-14.1.7.tar.gz)
## 安装
1. 将IntelliJ免安装版解压到指定(如 D:\Portable\IntelliJ)目录
2. 修改`${idea.home}/bin/idea.properties`
``` properties
# idea.config.path=${user.home}/.IntelliJIdea/config
idea.config.path=${idea.home}/config
# idea.system.path=${user.home}/.IntelliJIdea/system
idea.system.path=${idea.home}/system
```
3. 修改`${idea.home}/bin/idea(64).exe.vmoptions`追加`-Dfile.encoding=UTF-8`
4. 其它配置
``` py
# 显示行号
File > Settings > Editor > General > Appearance > Show line numbers
# 代码字体设置
File > Settings > Editor > Colors & Fonts > Font
# 快捷键设置
File > Settings > Keymap > Keymaps > Eclipse
File > Settings > Keymap > Main menu > Code > Completion > Cyclic Expand Word > Alt+. & Basic > Alt+/
File > Settings > Editor > General > Code Completion > Case sensitive completion=None
# 类方法不自动折叠
File > Settings > Editor > General > Code Folding > One-line methods=false
File > Settings > Editor > Code Style > Java > Imports > Class count to use import with ‘*’=99
# 编码设置
File > Settings > Editor > File Encodings > IDE Encoding&Project Encoding&Default encoding > UTF-8
# 隐藏项目配置文件
File > Settings > Editor > File Types > Ignore files and folders > *.idea;*.iml
```
## 安装Plugin
- [JRebel](http://dl.zeroturnaround.com/idea/)
http://dl.zeroturnaround.com/idea/jr-ide-intellij-7.0.9_13-17.zip
> *说明:安装插件时将包含lib目录的插件文件夹拷贝到${idea.home}/plugins目录即可。*
|
Java
|
package com.ymsino.water.service.manager.manager;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by the JAX-WS RI. JAX-WS RI 2.1.3-hudson-390- Generated source version: 2.0
*
*/
@WebService(name = "ManagerService", targetNamespace = "http://api.service.manager.esb.ymsino.com/")
public interface ManagerService {
/**
* 登录(密码为明文密码,只有状态为开通的管理员才能登录)
*
* @param mangerId
* @param password
* @return returns com.ymsino.water.service.manager.manager.ManagerReturn
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "login", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.Login")
@ResponseWrapper(localName = "loginResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.LoginResponse")
public ManagerReturn login(@WebParam(name = "mangerId", targetNamespace = "") String mangerId, @WebParam(name = "password", targetNamespace = "") String password);
/**
* 保存管理员
*
* @param managerSaveParam
* @return returns java.lang.Boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "save", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.Save")
@ResponseWrapper(localName = "saveResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.SaveResponse")
public Boolean save(@WebParam(name = "managerSaveParam", targetNamespace = "") ManagerSaveParam managerSaveParam);
/**
* 根据查询参数获取管理员分页列表
*
* @param queryParam
* @param startRow
* @param pageSize
* @return returns java.util.List<com.ymsino.water.service.manager.manager.ManagerReturn>
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getListpager", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetListpager")
@ResponseWrapper(localName = "getListpagerResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetListpagerResponse")
public List<ManagerReturn> getListpager(@WebParam(name = "queryParam", targetNamespace = "") QueryParam queryParam, @WebParam(name = "startRow", targetNamespace = "") Integer startRow, @WebParam(name = "pageSize", targetNamespace = "") Integer pageSize);
/**
* 停用帐号(审核不通过)
*
* @param mangerId
* @return returns java.lang.Boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "closeStatus", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.CloseStatus")
@ResponseWrapper(localName = "closeStatusResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.CloseStatusResponse")
public Boolean closeStatus(@WebParam(name = "mangerId", targetNamespace = "") String mangerId);
/**
* 修改管理员
*
* @param managerModifyParam
* @return returns java.lang.Boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "modify", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.Modify")
@ResponseWrapper(localName = "modifyResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.ModifyResponse")
public Boolean modify(@WebParam(name = "managerModifyParam", targetNamespace = "") ManagerModifyParam managerModifyParam);
/**
* 根据查询参数获取管理员记录数
*
* @param queryParam
* @return returns java.lang.Integer
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getCount", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetCount")
@ResponseWrapper(localName = "getCountResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetCountResponse")
public Integer getCount(@WebParam(name = "queryParam", targetNamespace = "") QueryParam queryParam);
/**
* 启用帐号(审核通过)
*
* @param managerId
* @return returns java.lang.Boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "openStatus", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.OpenStatus")
@ResponseWrapper(localName = "openStatusResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.OpenStatusResponse")
public Boolean openStatus(@WebParam(name = "managerId", targetNamespace = "") String managerId);
/**
* 根据管理员id获取管理员实体
*
* @param mangerId
* @return returns com.ymsino.water.service.manager.manager.ManagerReturn
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getByManagerId", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetByManagerId")
@ResponseWrapper(localName = "getByManagerIdResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetByManagerIdResponse")
public ManagerReturn getByManagerId(@WebParam(name = "mangerId", targetNamespace = "") String mangerId);
}
|
Java
|
# -*- coding: utf-8 -*-
import allure
from selenium.webdriver.common.by import By
from .base import BasePage
from .elements import SimpleInput, SimpleText
from .blocks.nav import NavBlock
class BrowseMoviePageLocators(object):
"""Локаторы страницы просмотра информации о фильме"""
TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2')
COUNTRY_LOCATOR = (By.NAME, 'country')
DIRECTOR_LOCATOR = (By.NAME, 'director')
WRITER_LOCATOR = (By.NAME, 'writer')
PRODUCER_LOCATOR = (By.NAME, 'producer')
EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]')
REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]')
class BrowseMoviePage(BasePage):
"""Страница просмотра информации о фильме"""
def __init__(self, driver):
super(BrowseMoviePage, self).__init__(driver)
self.nav = NavBlock(driver)
title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR)
director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR)
writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR)
producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR)
@allure.step('Нажмем на кноку "Edit"')
def click_edit_button(self):
"""
:rtype: EditMoviePage
"""
self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR)
return EditMoviePage(self._driver)
@allure.step('Нажмем на кноку "Remove"')
def click_remove_button(self):
"""
:rtype: HomePage
"""
self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR)
self.alert_accept()
from .home import HomePage
return HomePage(self._driver)
class AddMoviePageLocators(object):
"""Локаторы страницы создания описания фильма"""
TITLE_INPUT_LOCATOR = (By.NAME, 'name')
TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error')
ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka')
YEAR_INPUT_LOCATOR = (By.NAME, 'year')
YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error')
DURATION_INPUT_LOCATOR = (By.NAME, 'duration')
TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer')
FORMAT_INPUT_LOCATOR = (By.NAME, 'format')
COUNTRY_INPUT_LOCATOR = (By.NAME, 'country')
DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director')
WRITER_INPUT_LOCATOR = (By.NAME, 'writer')
PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer')
SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]')
class AddMoviePage(BasePage):
"""Страница создания описания фильма"""
def __init__(self, driver):
super(AddMoviePage, self).__init__(driver)
self.nav = NavBlock(driver)
title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма')
also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма')
year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год')
duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность')
trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера')
format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат')
country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну')
director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора')
writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста')
producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера')
@allure.step('Нажмем на кноку "Save"')
def click_save_button(self):
"""
:rtype: BrowseMoviePage
"""
self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR)
return BrowseMoviePage(self._driver)
def title_field_is_required_present(self):
"""
:rtype: bool
"""
return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR)
def year_field_is_required_present(self):
"""
:rtype: bool
"""
return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR)
class EditMoviePageLocators(object):
"""Локаторы для страницы редактирования описания фильма"""
REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]')
class EditMoviePage(AddMoviePage):
"""Страница редактирования описания фильма"""
@allure.step('Нажмем на кноку "Remove"')
def click_remove_button(self):
"""
:rtype: HomePage
"""
self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR)
self.alert_accept()
from .home import HomePage
return HomePage(self._driver)
|
Java
|
Contextual Image Delivery
=============================
This is an optional module for the SDL Digital Experience Accelerator Java web application. It contains an implementation
of interface `MediaHelper` that uses Tridion Contextual Image Delivery (CID) to resize images on the server side.
Note that in order to use Tridion CID, you need a license. If you do not have a license for CID or if you are not sure,
then contact SDL if you want to use CID.
You can also choose to not use CID. The web application will then use a different implementation of `MediaHelper` to
resize images.
In the `dxa-common-api` there is a Spring factory bean `MediaHelperFactory` that automatically chooses the
implementation of `MediaHelper` to use. It does this by checking if the CID-specific implementation is available in the
classpath. If it is, it will use the CID-specific implementation, otherwise it will use the default implementation.
## Enabling or disabling the use of CID
When you activate the Maven profile `cid`, this module and its dependencies will be included in the project. This means
you can compile the web application with support for CID by compiling the project with:
mvn clean package -P cid
If you do not want to use CID, simply leave off `-P cid`.
Note that if you do use CID, you will have to edit the configuration file `cd_ambient_conf` in
`dxa-webapp\src\main\resources` to enable the CID Ambient Data Framework cartridge.
|
Java
|
//
// DZYSquareCell.h
// budejie
//
// Created by dzy on 16/1/7.
// Copyright © 2016年 董震宇. All rights reserved.
//
#import <UIKit/UIKit.h>
@class DZYSquareModel;
@interface DZYSquareCell : UICollectionViewCell
/** 方块模型 */
@property (nonatomic, strong) DZYSquareModel *squareModel;
@end
|
Java
|
package app.yweather.com.yweather.util;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* 解析JSON工具类
*/
public class Utility {
//解析服务器返回的JSON数据,并将解析出的数据存储到本地。
public static void handleWeatherResponse(Context context, String response){
try{
JSONArray jsonObjs = new JSONObject(response).getJSONArray("results");
JSONObject locationJsonObj = ((JSONObject)jsonObjs.opt(0)).getJSONObject("location");
String id = locationJsonObj.getString("id");
String name = locationJsonObj.getString("name");
JSONObject nowJsonObj = ((JSONObject)jsonObjs.opt(0)).getJSONObject("now");
String text = nowJsonObj.getString("text");
String temperature = nowJsonObj.getString("temperature");
String wind = nowJsonObj.getString("wind_direction");
String lastUpdateTime = ((JSONObject) jsonObjs.opt(0)).getString("last_update");
lastUpdateTime = lastUpdateTime.substring(lastUpdateTime.indexOf("+") + 1,lastUpdateTime.length());
LogUtil.e("Utility", "name:" + name + ",text:"+ text + "wind:" + wind + ",lastUpdateTime:" + lastUpdateTime);
saveWeatherInfo(context,name,id,temperature,text,lastUpdateTime);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 将服务器返回的天气信息存储到SharedPreferences文件中
* context : Context对象
* cityName : 城市名称
* cityId : 城市id
* temperature: 温度
* text :天气现象文字说明,如多云
* lastUpdateTime : 数据更新时间
* 2016-07-16T13:10:00+08:00
*/
@TargetApi(Build.VERSION_CODES.N) //指定使用的系统版本
public static void saveWeatherInfo(Context context, String cityName, String cityId, String temperature,
String text, String lastUpdateTime){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日", Locale.CANADA);
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putBoolean("city_selected",true);
editor.putString("city_name",cityName);
editor.putString("city_id",cityId);
editor.putString("temperature",temperature);
editor.putString("text",text);
editor.putString("last_update_time",lastUpdateTime);
editor.putString("current_date",sdf.format(new Date()));
editor.commit();
}
}
|
Java
|
package pl.touk.nussknacker.engine.flink.util.timestamp
import com.github.ghik.silencer.silent
import org.apache.flink.streaming.api.functions.AssignerWithPeriodicWatermarks
import org.apache.flink.streaming.api.watermark.Watermark
import scala.annotation.nowarn
/**
* It is a copy-paste of BoundedOutOfOrdernessTimestampExtractor but taking timestamp from previousElementTimestamp
* See https://ci.apache.org/projects/flink/flink-docs-stable/dev/connectors/kafka.html#using-kafka-timestamps-and-flink-event-time-in-kafka-010
*/
@silent("deprecated")
@nowarn("cat=deprecation")
class BoundedOutOfOrderPreviousElementAssigner[T](maxOutOfOrdernessMillis: Long)
extends AssignerWithPeriodicWatermarks[T] with Serializable {
private var currentMaxTimestamp = Long.MinValue + maxOutOfOrdernessMillis
private var lastEmittedWatermark = Long.MinValue
override def extractTimestamp(element: T, previousElementTimestamp: Long): Long = {
if (previousElementTimestamp > currentMaxTimestamp)
currentMaxTimestamp = previousElementTimestamp
previousElementTimestamp
}
override def getCurrentWatermark: Watermark = {
val potentialWM = currentMaxTimestamp - maxOutOfOrdernessMillis
if (potentialWM >= lastEmittedWatermark)
lastEmittedWatermark = potentialWM
new Watermark(lastEmittedWatermark)
}
}
|
Java
|
/*
* Copyright (C) 2017 grandcentrix GmbH
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.grandcentrix.thirtyinch;
import android.content.res.Configuration;
import android.os.Bundle;
import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import java.util.concurrent.Executor;
import net.grandcentrix.thirtyinch.internal.DelegatedTiActivity;
import net.grandcentrix.thirtyinch.internal.InterceptableViewBinder;
import net.grandcentrix.thirtyinch.internal.PresenterAccessor;
import net.grandcentrix.thirtyinch.internal.PresenterSavior;
import net.grandcentrix.thirtyinch.internal.TiActivityDelegate;
import net.grandcentrix.thirtyinch.internal.TiLoggingTagProvider;
import net.grandcentrix.thirtyinch.internal.TiPresenterProvider;
import net.grandcentrix.thirtyinch.internal.TiViewProvider;
import net.grandcentrix.thirtyinch.internal.UiThreadExecutor;
import net.grandcentrix.thirtyinch.util.AnnotationUtil;
/**
* An Activity which has a {@link TiPresenter} to build the Model View Presenter architecture on
* Android.
*
* <p>
* The {@link TiPresenter} will be created in {@link #providePresenter()} called in
* {@link #onCreate(Bundle)}. Depending on the {@link TiConfiguration} passed into the
* {@link TiPresenter#TiPresenter(TiConfiguration)} constructor the {@link TiPresenter} survives
* orientation changes (default).
* </p>
* <p>
* The {@link TiPresenter} requires a interface to communicate with the View. Normally the Activity
* implements the View interface (which must extend {@link TiView}) and is returned by default
* from {@link #provideView()}.
* </p>
*
* <p>
* Example:
* <code>
* <pre>
* public class MyActivity extends TiActivity<MyPresenter, MyView> implements MyView {
*
* @Override
* public MyPresenter providePresenter() {
* return new MyPresenter();
* }
* }
*
* public class MyPresenter extends TiPresenter<MyView> {
*
* @Override
* protected void onCreate() {
* super.onCreate();
* }
* }
*
* public interface MyView extends TiView {
*
* // void showItems(List<Item> items);
*
* // Observable<Item> onItemClicked();
* }
* </pre>
* </code>
* </p>
*
* @param <V> the View type, must implement {@link TiView}
* @param <P> the Presenter type, must extend {@link TiPresenter}
*/
public abstract class TiActivity<P extends TiPresenter<V>, V extends TiView>
extends AppCompatActivity
implements TiPresenterProvider<P>, TiViewProvider<V>, DelegatedTiActivity,
TiLoggingTagProvider, InterceptableViewBinder<V>, PresenterAccessor<P, V> {
private final String TAG = this.getClass().getSimpleName()
+ ":" + TiActivity.class.getSimpleName()
+ "@" + Integer.toHexString(this.hashCode());
private final TiActivityDelegate<P, V> mDelegate
= new TiActivityDelegate<>(this, this, this, this, PresenterSavior.getInstance());
private final UiThreadExecutor mUiThreadExecutor = new UiThreadExecutor();
@CallSuper
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDelegate.onCreate_afterSuper(savedInstanceState);
}
@CallSuper
@Override
protected void onStart() {
super.onStart();
mDelegate.onStart_afterSuper();
}
@CallSuper
@Override
protected void onStop() {
mDelegate.onStop_beforeSuper();
super.onStop();
mDelegate.onStop_afterSuper();
}
@CallSuper
@Override
protected void onSaveInstanceState(@NonNull final Bundle outState) {
super.onSaveInstanceState(outState);
mDelegate.onSaveInstanceState_afterSuper(outState);
}
@CallSuper
@Override
protected void onDestroy() {
super.onDestroy();
mDelegate.onDestroy_afterSuper();
}
@NonNull
@Override
public final Removable addBindViewInterceptor(@NonNull final BindViewInterceptor interceptor) {
return mDelegate.addBindViewInterceptor(interceptor);
}
@Override
public final Object getHostingContainer() {
return this;
}
@Nullable
@Override
public final V getInterceptedViewOf(@NonNull final BindViewInterceptor interceptor) {
return mDelegate.getInterceptedViewOf(interceptor);
}
@NonNull
@Override
public final List<BindViewInterceptor> getInterceptors(
@NonNull final Filter<BindViewInterceptor> predicate) {
return mDelegate.getInterceptors(predicate);
}
@Override
public String getLoggingTag() {
return TAG;
}
/**
* is {@code null} before {@link #onCreate(Bundle)}
*/
@Override
public final P getPresenter() {
return mDelegate.getPresenter();
}
@Override
public final Executor getUiThreadExecutor() {
return mUiThreadExecutor;
}
/**
* Invalidates the cache of the latest bound view. Forces the next binding of the view to run
* through all the interceptors (again).
*/
@Override
public final void invalidateView() {
mDelegate.invalidateView();
}
@Override
public final boolean isActivityFinishing() {
return isFinishing();
}
@CallSuper
@Override
public void onConfigurationChanged(@NonNull final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDelegate.onConfigurationChanged_afterSuper(newConfig);
}
@SuppressWarnings("unchecked")
@NonNull
@Override
public V provideView() {
final Class<?> foundViewInterface = AnnotationUtil
.getInterfaceOfClassExtendingGivenInterface(this.getClass(), TiView.class);
if (foundViewInterface == null) {
throw new IllegalArgumentException(
"This Activity doesn't implement a TiView interface. "
+ "This is the default behaviour. Override provideView() to explicitly change this.");
} else {
if (foundViewInterface.getSimpleName().equals("TiView")) {
throw new IllegalArgumentException(
"extending TiView doesn't make sense, it's an empty interface."
+ " This is the default behaviour. Override provideView() to explicitly change this.");
} else {
// assume that the activity itself is the view and implements the TiView interface
return (V) this;
}
}
}
@Override
public String toString() {
String presenter = mDelegate.getPresenter() == null ? "null" :
mDelegate.getPresenter().getClass().getSimpleName()
+ "@" + Integer.toHexString(mDelegate.getPresenter().hashCode());
return getClass().getSimpleName()
+ ":" + TiActivity.class.getSimpleName()
+ "@" + Integer.toHexString(hashCode())
+ "{presenter = " + presenter + "}";
}
}
|
Java
|
/*jslint browser: true*/
/*global $, jQuery, alert*/
(function ($) {
"use strict";
$(document).ready(function () {
$("input[name=dob]").datepicker({
dateFormat: 'yy-mm-dd',
inline: true,
showOtherMonths: true
});
});
$(document).ready(function () {
$("input[name='rep_password']").focusout(function () {
var p1 = $('input[name="password"]').val(), p2 = $('input[name="rep_password"]').val();
if (p1 !== p2) {
$('#passDM').show(300);
} else if (p1 === "") {
$('#passDM').show(300);
} else {
$('#passDM').hide(300);
}
});
});
$(document).ready(function () {
$("input[name=password]").focusin(function () {
$('#passDM').hide(300);
});
$("input[name=rep_password]").focusin(function () {
$('#passDM').hide(300);
});
});
}(jQuery));
|
Java
|
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V. licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
//
// Code generated from specification version 7.7.0: DO NOT EDIT
package esapi
import (
"context"
"io"
"net/http"
"strings"
)
func newAutoscalingPutAutoscalingPolicyFunc(t Transport) AutoscalingPutAutoscalingPolicy {
return func(name string, body io.Reader, o ...func(*AutoscalingPutAutoscalingPolicyRequest)) (*Response, error) {
var r = AutoscalingPutAutoscalingPolicyRequest{Name: name, Body: body}
for _, f := range o {
f(&r)
}
return r.Do(r.ctx, t)
}
}
// ----- API Definition -------------------------------------------------------
// AutoscalingPutAutoscalingPolicy -
//
// This API is experimental.
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/current/autoscaling-put-autoscaling-policy.html.
//
type AutoscalingPutAutoscalingPolicy func(name string, body io.Reader, o ...func(*AutoscalingPutAutoscalingPolicyRequest)) (*Response, error)
// AutoscalingPutAutoscalingPolicyRequest configures the Autoscaling Put Autoscaling Policy API request.
//
type AutoscalingPutAutoscalingPolicyRequest struct {
Body io.Reader
Name string
Pretty bool
Human bool
ErrorTrace bool
FilterPath []string
Header http.Header
ctx context.Context
}
// Do executes the request and returns response or error.
//
func (r AutoscalingPutAutoscalingPolicyRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
var (
method string
path strings.Builder
params map[string]string
)
method = "PUT"
path.Grow(1 + len("_autoscaling") + 1 + len("policy") + 1 + len(r.Name))
path.WriteString("/")
path.WriteString("_autoscaling")
path.WriteString("/")
path.WriteString("policy")
path.WriteString("/")
path.WriteString(r.Name)
params = make(map[string]string)
if r.Pretty {
params["pretty"] = "true"
}
if r.Human {
params["human"] = "true"
}
if r.ErrorTrace {
params["error_trace"] = "true"
}
if len(r.FilterPath) > 0 {
params["filter_path"] = strings.Join(r.FilterPath, ",")
}
req, err := newRequest(method, path.String(), r.Body)
if err != nil {
return nil, err
}
if len(params) > 0 {
q := req.URL.Query()
for k, v := range params {
q.Set(k, v)
}
req.URL.RawQuery = q.Encode()
}
if r.Body != nil {
req.Header[headerContentType] = headerContentTypeJSON
}
if len(r.Header) > 0 {
if len(req.Header) == 0 {
req.Header = r.Header
} else {
for k, vv := range r.Header {
for _, v := range vv {
req.Header.Add(k, v)
}
}
}
}
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := transport.Perform(req)
if err != nil {
return nil, err
}
response := Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
return &response, nil
}
// WithContext sets the request context.
//
func (f AutoscalingPutAutoscalingPolicy) WithContext(v context.Context) func(*AutoscalingPutAutoscalingPolicyRequest) {
return func(r *AutoscalingPutAutoscalingPolicyRequest) {
r.ctx = v
}
}
// WithPretty makes the response body pretty-printed.
//
func (f AutoscalingPutAutoscalingPolicy) WithPretty() func(*AutoscalingPutAutoscalingPolicyRequest) {
return func(r *AutoscalingPutAutoscalingPolicyRequest) {
r.Pretty = true
}
}
// WithHuman makes statistical values human-readable.
//
func (f AutoscalingPutAutoscalingPolicy) WithHuman() func(*AutoscalingPutAutoscalingPolicyRequest) {
return func(r *AutoscalingPutAutoscalingPolicyRequest) {
r.Human = true
}
}
// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f AutoscalingPutAutoscalingPolicy) WithErrorTrace() func(*AutoscalingPutAutoscalingPolicyRequest) {
return func(r *AutoscalingPutAutoscalingPolicyRequest) {
r.ErrorTrace = true
}
}
// WithFilterPath filters the properties of the response body.
//
func (f AutoscalingPutAutoscalingPolicy) WithFilterPath(v ...string) func(*AutoscalingPutAutoscalingPolicyRequest) {
return func(r *AutoscalingPutAutoscalingPolicyRequest) {
r.FilterPath = v
}
}
// WithHeader adds the headers to the HTTP request.
//
func (f AutoscalingPutAutoscalingPolicy) WithHeader(h map[string]string) func(*AutoscalingPutAutoscalingPolicyRequest) {
return func(r *AutoscalingPutAutoscalingPolicyRequest) {
if r.Header == nil {
r.Header = make(http.Header)
}
for k, v := range h {
r.Header.Add(k, v)
}
}
}
// WithOpaqueID adds the X-Opaque-Id header to the HTTP request.
//
func (f AutoscalingPutAutoscalingPolicy) WithOpaqueID(s string) func(*AutoscalingPutAutoscalingPolicyRequest) {
return func(r *AutoscalingPutAutoscalingPolicyRequest) {
if r.Header == nil {
r.Header = make(http.Header)
}
r.Header.Set("X-Opaque-Id", s)
}
}
|
Java
|
"""
Copyright 2015-2018 IBM
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Licensed Materials - Property of IBM
© Copyright IBM Corp. 2015-2018
"""
import asyncio
from confluent_kafka import Producer
class ProducerTask(object):
def __init__(self, conf, topic_name):
self.topic_name = topic_name
self.producer = Producer(conf)
self.counter = 0
self.running = True
def stop(self):
self.running = False
def on_delivery(self, err, msg):
if err:
print('Delivery report: Failed sending message {0}'.format(msg.value()))
print(err)
# We could retry sending the message
else:
print('Message produced, offset: {0}'.format(msg.offset()))
@asyncio.coroutine
def run(self):
print('The producer has started')
while self.running:
message = 'This is a test message #{0}'.format(self.counter)
key = 'key'
sleep = 2 # Short sleep for flow control
try:
self.producer.produce(self.topic_name, message, key, -1, self.on_delivery)
self.producer.poll(0)
self.counter += 1
except Exception as err:
print('Failed sending message {0}'.format(message))
print(err)
sleep = 5 # Longer sleep before retrying
yield from asyncio.sleep(sleep)
self.producer.flush()
|
Java
|
/*
* Copyright 2012 International Business Machines Corp.
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ibm.jbatch.jsl.util;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
public class JSLValidationEventHandler implements ValidationEventHandler {
private boolean eventOccurred = false;
public boolean handleEvent(ValidationEvent event) {
System.out.println("\nMESSAGE: " + event.getMessage());
System.out.println("\nSEVERITY: " + event.getSeverity());
System.out.println("\nLINKED EXC: " + event.getLinkedException());
System.out.println("\nLOCATOR INFO:\n------------");
System.out.println("\n COLUMN NUMBER: " + event.getLocator().getColumnNumber());
System.out.println("\n LINE NUMBER: " + event.getLocator().getLineNumber());
System.out.println("\n OFFSET: " + event.getLocator().getOffset());
System.out.println("\n CLASS: " + event.getLocator().getClass());
System.out.println("\n NODE: " + event.getLocator().getNode());
System.out.println("\n OBJECT: " + event.getLocator().getObject());
System.out.println("\n URL: " + event.getLocator().getURL());
eventOccurred = true;
// Allow more parsing feedback
return true;
}
public boolean eventOccurred() {
return eventOccurred;
}
}
|
Java
|
---
layout: post
title: Underperformance of Lenovo ThinkBook Intel i7-8565U with Windows 10 pro
date: 2021-07-07
type: post
published: true
status: publish
categories: [travel]
tags:
author:
login: MiguelGamboa
email:
display_name: Miguel Gamboa
---
The stack Lenovo-Intel-Win10 is a completely rubbish for remote software developer work. Other guys with the same CPU and Windows 10 on different brand laptops have no breaks of performance as I am experiencing in my laptop.
Simply put, every time I am working with Zoom or Skype my CPU stays limited to 0.39GHz! After a while it returns to normality, as you can observe in next screen shots during and after a CPU break.
<img src="/assets/lenovo-i7-CPU-0.39ghz.png" width="300px">
<img src="/assets/lenovo-i7-CPU-4.02ghz.png" width="300px">
|
Java
|
# -*- coding: utf-8 -*-
import unittest
import pykintone
from pykintone.model import kintoneModel
import tests.envs as envs
class TestAppModelSimple(kintoneModel):
def __init__(self):
super(TestAppModelSimple, self).__init__()
self.my_key = ""
self.stringField = ""
class TestComment(unittest.TestCase):
def test_comment(self):
app = pykintone.load(envs.FILE_PATH).app()
model = TestAppModelSimple()
model.my_key = "comment_test"
model.stringField = "comment_test_now"
result = app.create(model)
self.assertTrue(result.ok) # confirm create the record to test comment
_record_id = result.record_id
# create comment
r_created = app.comment(_record_id).create("コメントのテスト")
self.assertTrue(r_created.ok)
# it requires Administrator user is registered in kintone
r_created_m = app.comment(_record_id).create("メンションのテスト", [("Administrator", "USER")])
self.assertTrue(r_created_m.ok)
# select comment
r_selected = app.comment(_record_id).select(True, 0, 10)
self.assertTrue(r_selected.ok)
self.assertTrue(2, len(r_selected.raw_comments))
comments = r_selected.comments()
self.assertTrue(1, len(comments[-1].mentions))
# delete comment
for c in comments:
r_deleted = app.comment(_record_id).delete(c.comment_id)
self.assertTrue(r_deleted.ok)
r_selected = app.comment(_record_id).select()
self.assertEqual(0, len(r_selected.raw_comments))
# done test
app.delete(_record_id)
|
Java
|
package com.iclockwork.percy.wechat4j;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* HelloWorldTest
*
* @author: fengwang
* @date: 2016/3/9 13:40
* @version: 1.0
* @since: JDK 1.7
*/
public class HelloWorldTest {
/**
* helloworld
*/
private HelloWorld helloworld;
@BeforeMethod
public void setUp() throws Exception {
helloworld = new HelloWorld();
}
@AfterMethod
public void tearDown() throws Exception {
}
@Test
public void testHello() throws Exception {
helloworld.hello();
}
}
|
Java
|
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// buildifier defines a Prow plugin that runs buildifier over modified BUILD,
// WORKSPACE, and skylark (.bzl) files in pull requests.
package buildifier
import (
"bytes"
"fmt"
"io/ioutil"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"github.com/bazelbuild/buildtools/build"
"github.com/sirupsen/logrus"
"k8s.io/test-infra/prow/genfiles"
"k8s.io/test-infra/prow/git"
"k8s.io/test-infra/prow/github"
"k8s.io/test-infra/prow/pluginhelp"
"k8s.io/test-infra/prow/plugins"
)
const (
pluginName = "buildifier"
maxComments = 20
)
var buildifyRe = regexp.MustCompile(`(?mi)^/buildif(y|ier)\s*$`)
func init() {
plugins.RegisterGenericCommentHandler(pluginName, handleGenericComment, nil)
}
func helpProvider(config *plugins.Configuration, enabledRepos []string) (*pluginhelp.PluginHelp, error) {
// The Config field is omitted because this plugin is not configurable.
pluginHelp := &pluginhelp.PluginHelp{
Description: "The buildifier plugin runs buildifier on changes made to Bazel files in a PR. It then creates a new review on the pull request and leaves warnings at the appropriate lines of code.",
}
pluginHelp.AddCommand(pluginhelp.Command{
Usage: "/buildif(y|ier)",
Featured: false,
Description: "Runs buildifier on changes made to Bazel files in a PR",
WhoCanUse: "Anyone can trigger this command on a PR.",
Examples: []string{"/buildify", "/buildifier"},
})
return pluginHelp, nil
}
type githubClient interface {
GetFile(org, repo, filepath, commit string) ([]byte, error)
GetPullRequest(org, repo string, number int) (*github.PullRequest, error)
GetPullRequestChanges(org, repo string, number int) ([]github.PullRequestChange, error)
CreateReview(org, repo string, number int, r github.DraftReview) error
ListPullRequestComments(org, repo string, number int) ([]github.ReviewComment, error)
}
func handleGenericComment(pc plugins.Agent, e github.GenericCommentEvent) error {
return handle(pc.GitHubClient, pc.GitClient, pc.Logger, &e)
}
// modifiedBazelFiles returns a map from filename to patch string for all Bazel files
// that are modified in the PR.
func modifiedBazelFiles(ghc githubClient, org, repo string, number int, sha string) (map[string]string, error) {
changes, err := ghc.GetPullRequestChanges(org, repo, number)
if err != nil {
return nil, err
}
gfg, err := genfiles.NewGroup(ghc, org, repo, sha)
if err != nil {
return nil, err
}
modifiedFiles := make(map[string]string)
for _, change := range changes {
switch {
case gfg.Match(change.Filename):
continue
case change.Status == github.PullRequestFileRemoved || change.Status == github.PullRequestFileRenamed:
continue
// This also happens to match BUILD.bazel.
case strings.Contains(change.Filename, "BUILD"):
break
case strings.Contains(change.Filename, "WORKSPACE"):
break
case filepath.Ext(change.Filename) != ".bzl":
continue
}
modifiedFiles[change.Filename] = change.Patch
}
return modifiedFiles, nil
}
func uniqProblems(problems []string) []string {
sort.Strings(problems)
var uniq []string
last := ""
for _, s := range problems {
if s != last {
last = s
uniq = append(uniq, s)
}
}
return uniq
}
// problemsInFiles runs buildifier on the files. It returns a map from the file to
// a list of problems with that file.
func problemsInFiles(r *git.Repo, files map[string]string) (map[string][]string, error) {
problems := make(map[string][]string)
for f := range files {
src, err := ioutil.ReadFile(filepath.Join(r.Dir, f))
if err != nil {
return nil, err
}
// This is modeled after the logic from buildifier:
// https://github.com/bazelbuild/buildtools/blob/8818289/buildifier/buildifier.go#L261
content, err := build.Parse(f, src)
if err != nil {
return nil, fmt.Errorf("parsing as Bazel file %v", err)
}
beforeRewrite := build.Format(content)
var info build.RewriteInfo
build.Rewrite(content, &info)
ndata := build.Format(content)
if !bytes.Equal(src, ndata) && !bytes.Equal(src, beforeRewrite) {
// TODO(mattmoor): This always seems to be empty?
problems[f] = uniqProblems(info.Log)
}
}
return problems, nil
}
func handle(ghc githubClient, gc *git.Client, log *logrus.Entry, e *github.GenericCommentEvent) error {
// Only handle open PRs and new requests.
if e.IssueState != "open" || !e.IsPR || e.Action != github.GenericCommentActionCreated {
return nil
}
if !buildifyRe.MatchString(e.Body) {
return nil
}
org := e.Repo.Owner.Login
repo := e.Repo.Name
pr, err := ghc.GetPullRequest(org, repo, e.Number)
if err != nil {
return err
}
// List modified files.
modifiedFiles, err := modifiedBazelFiles(ghc, org, repo, pr.Number, pr.Head.SHA)
if err != nil {
return err
}
if len(modifiedFiles) == 0 {
return nil
}
log.Infof("Will buildify %d modified Bazel files.", len(modifiedFiles))
// Clone the repo, checkout the PR.
startClone := time.Now()
r, err := gc.Clone(e.Repo.FullName)
if err != nil {
return err
}
defer func() {
if err := r.Clean(); err != nil {
log.WithError(err).Error("Error cleaning up repo.")
}
}()
if err := r.CheckoutPullRequest(e.Number); err != nil {
return err
}
finishClone := time.Now()
log.WithField("duration", time.Since(startClone)).Info("Cloned and checked out PR.")
// Compute buildifier errors.
problems, err := problemsInFiles(r, modifiedFiles)
if err != nil {
return err
}
log.WithField("duration", time.Since(finishClone)).Info("Buildified.")
// Make the list of comments.
var comments []github.DraftReviewComment
for f := range problems {
comments = append(comments, github.DraftReviewComment{
Path: f,
// TODO(mattmoor): Include the messages if they are ever non-empty.
Body: strings.Join([]string{
"This Bazel file needs formatting, run:",
"```shell",
fmt.Sprintf("buildifier -mode=fix %q", f),
"```"}, "\n"),
Position: 1,
})
}
// Trim down the number of comments if necessary.
totalProblems := len(problems)
// Make the review body.
s := "s"
if totalProblems == 1 {
s = ""
}
response := fmt.Sprintf("%d warning%s.", totalProblems, s)
return ghc.CreateReview(org, repo, e.Number, github.DraftReview{
Body: plugins.FormatResponseRaw(e.Body, e.HTMLURL, e.User.Login, response),
Action: github.Comment,
Comments: comments,
})
}
|
Java
|
#!/bin/bash
# Copyright 2016 Nitor Creations Oy
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
if [ "$_ARGCOMPLETE" ]; then
# Handle command completion executions
unset _ARGCOMPLETE
source $(n-include autocomplete-helpers.sh)
case $COMP_CWORD in
2)
if [ "$COMP_INDEX" = "$COMP_CWORD" ]; then
DRY="-d "
fi
compgen -W "$DRY-h $(get_stack_dirs)" -- $COMP_CUR
;;
3)
compgen -W "$(get_serverless $COMP_PREV)" -- $COMP_CUR
;;
*)
exit 1
;;
esac
exit 0
fi
usage() {
echo "usage: ndt deploy-serverless [-d] [-h] component serverless-name" >&2
echo "" >&2
echo "Exports ndt parameters into component/serverless-name/variables.yml, runs npm i in the" >&2
echo "serverless project and runs sls deploy -s \$paramEnvId for the same" >&2
echo "" >&2
echo "positional arguments:" >&2
echo " component the component directory where the serverless directory is" >&2
echo " serverless-name the name of the serverless directory that has the template" >&2
echo " For example for lambda/serverless-sender/template.yaml" >&2
echo " you would give sender" >&2
echo "" >&2
echo "optional arguments:" >&2
echo " -d, --dryrun dry-run - do only parameter expansion and template pre-processing and npm i" >&2
echo " -h, --help show this help message and exit" >&2
if "$@"; then
echo "" >&2
echo "$@" >&2
fi
exit 1
}
if [ "$1" = "--help" -o "$1" = "-h" ]; then
usage
fi
if [ "$1" = "-d" -o "$1" = "--dryrun" ]; then
DRYRUN=1
shift
fi
die () {
echo "$1" >&2
usage
}
set -xe
component="$1" ; shift
[ "${component}" ] || die "You must give the component name as argument"
serverless="$1"; shift
[ "${serverless}" ] || die "You must give the serverless name as argument"
TSTAMP=$(date +%Y%m%d%H%M%S)
if [ -z "$BUILD_NUMBER" ]; then
BUILD_NUMBER=$TSTAMP
else
BUILD_NUMBER=$(printf "%04d\n" $BUILD_NUMBER)
fi
eval "$(ndt load-parameters "$component" -l "$serverless" -e -r)"
#If assume-deploy-role.sh is on the path, run it to assume the appropriate role for deployment
if [ -n "$DEPLOY_ROLE_ARN" ] && [ -z "$AWS_SESSION_TOKEN" ]; then
eval $(ndt assume-role $DEPLOY_ROLE_ARN)
elif which assume-deploy-role.sh > /dev/null && [ -z "$AWS_SESSION_TOKEN" ]; then
eval $(assume-deploy-role.sh)
fi
ndt load-parameters "$component" -l "$serverless" -y -r > "$component/serverless-$ORIG_SERVERLESS_NAME/variables.yml"
ndt yaml-to-yaml "$component/serverless-$ORIG_SERVERLESS_NAME/template.yaml" > "$component/serverless-$ORIG_SERVERLESS_NAME/serverless.yml"
cd "$component/serverless-$ORIG_SERVERLESS_NAME"
if [ -x "./pre_deploy.sh" ]; then
"./pre_deploy.sh"
fi
if [ -z "$SKIP_NPM" -o "$SKIP_NPM" = "n" ]; then
npm i
fi
if [ -n "$DRYRUN" ]; then
exit 0
fi
sls deploy -s $paramEnvId
|
Java
|
package com.scicrop.se.commons.utils;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
public class LogHelper {
private LogHelper(){}
private static LogHelper INSTANCE = null;
public static LogHelper getInstance(){
if(INSTANCE == null) INSTANCE = new LogHelper();
return INSTANCE;
}
public void setLogger(String logNamePattern, String logFolder){
String logPath = logFolder + Constants.APP_NAME+"_"+logNamePattern+".log";
Logger rootLogger = Logger.getRootLogger();
rootLogger.setLevel(Level.INFO);
PatternLayout layout = new PatternLayout("%d{ISO8601} [%t] %-5p %c %x - %m%n");
rootLogger.addAppender(new ConsoleAppender(layout));
try {
RollingFileAppender fileAppender = new RollingFileAppender(layout, logPath);
rootLogger.addAppender(fileAppender);
} catch (IOException e) {
System.err.println("Failed to find/access "+logPath+" !");
System.exit(1);
}
}
public void handleVerboseLog(boolean isVerbose, boolean isLog, Log log, char type, String data){
if(isLog){
logData(data, type, log);
}
if(isVerbose){
verbose(data, type);
}
}
public void logData(String data, char type, Log log){
switch (type) {
case 'i':
log.info(data);
break;
case 'w':
log.warn(data);
break;
case 'e':
log.error(data);
break;
default:
log.info(data);
break;
}
}
public void verbose(String data, char type){
switch (type) {
case 'e':
System.err.println(data);
break;
default:
System.out.println(data);
break;
}
}
}
|
Java
|
function Add-VSWAFv2RuleGroupCountAction {
<#
.SYNOPSIS
Adds an AWS::WAFv2::RuleGroup.CountAction resource property to the template.
.DESCRIPTION
Adds an AWS::WAFv2::RuleGroup.CountAction resource property to the template.
.LINK
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafv2-rulegroup-countaction.html
.FUNCTIONALITY
Vaporshell
#>
[OutputType('Vaporshell.Resource.WAFv2.RuleGroup.CountAction')]
[cmdletbinding()]
Param
(
)
Begin {
$obj = [PSCustomObject]@{}
$commonParams = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable')
}
Process {
foreach ($key in $PSBoundParameters.Keys | Where-Object {$commonParams -notcontains $_}) {
switch ($key) {
Default {
$obj | Add-Member -MemberType NoteProperty -Name $key -Value $PSBoundParameters.$key
}
}
}
}
End {
$obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.WAFv2.RuleGroup.CountAction'
Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$($obj | ConvertTo-Json -Depth 5)`n"
}
}
|
Java
|
// Copyright 2015 Thomas Trapp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef HTMLEXT_FILE_H_INCLUDED
#define HTMLEXT_FILE_H_INCLUDED
#include <string>
#include <stdexcept>
namespace htmlext {
/// Custom exception type for file errors.
class FileError : public std::runtime_error
{
public:
explicit FileError(const std::string& msg) noexcept;
};
/// Read file at path to buffer. Throws FileError on failure.
/// Can read regular files as well as named pipes.
std::string ReadFileOrThrow(const std::string& path);
} // namespace htmlext
#endif // HTMLEXT_FILE_H_INCLUDED
|
Java
|
# -*- coding: utf-8 -*-
'''
The Salt Key backend API and interface used by the CLI. The Key class can be
used to manage salt keys directly without interfacing with the CLI.
'''
# Import python libs
from __future__ import absolute_import, print_function
import os
import copy
import json
import stat
import shutil
import fnmatch
import hashlib
import logging
# Import salt libs
import salt.crypt
import salt.utils
import salt.exceptions
import salt.utils.event
import salt.daemons.masterapi
from salt.utils import kinds
from salt.utils.event import tagify
# Import third party libs
# pylint: disable=import-error,no-name-in-module,redefined-builtin
import salt.ext.six as six
from salt.ext.six.moves import input
# pylint: enable=import-error,no-name-in-module,redefined-builtin
try:
import msgpack
except ImportError:
pass
log = logging.getLogger(__name__)
def get_key(opts):
if opts['transport'] in ('zeromq', 'tcp'):
return Key(opts)
else:
return RaetKey(opts)
class KeyCLI(object):
'''
Manage key CLI operations
'''
def __init__(self, opts):
self.opts = opts
if self.opts['transport'] in ('zeromq', 'tcp'):
self.key = Key(opts)
else:
self.key = RaetKey(opts)
def list_status(self, status):
'''
Print out the keys under a named status
:param str status: A string indicating which set of keys to return
'''
keys = self.key.list_keys()
if status.startswith('acc'):
salt.output.display_output(
{self.key.ACC: keys[self.key.ACC]},
'key',
self.opts
)
elif status.startswith(('pre', 'un')):
salt.output.display_output(
{self.key.PEND: keys[self.key.PEND]},
'key',
self.opts
)
elif status.startswith('rej'):
salt.output.display_output(
{self.key.REJ: keys[self.key.REJ]},
'key',
self.opts
)
elif status.startswith('den'):
if self.key.DEN:
salt.output.display_output(
{self.key.DEN: keys[self.key.DEN]},
'key',
self.opts
)
elif status.startswith('all'):
self.list_all()
def list_all(self):
'''
Print out all keys
'''
salt.output.display_output(
self.key.list_keys(),
'key',
self.opts)
def accept(self, match, include_rejected=False):
'''
Accept the keys matched
:param str match: A string to match against. i.e. 'web*'
:param bool include_rejected: Whether or not to accept a matched key that was formerly rejected
'''
def _print_accepted(matches, after_match):
if self.key.ACC in after_match:
accepted = sorted(
set(after_match[self.key.ACC]).difference(
set(matches.get(self.key.ACC, []))
)
)
for key in accepted:
print('Key for minion {0} accepted.'.format(key))
matches = self.key.name_match(match)
keys = {}
if self.key.PEND in matches:
keys[self.key.PEND] = matches[self.key.PEND]
if include_rejected and bool(matches.get(self.key.REJ)):
keys[self.key.REJ] = matches[self.key.REJ]
if not keys:
msg = (
'The key glob {0!r} does not match any unaccepted {1}keys.'
.format(match, 'or rejected ' if include_rejected else '')
)
print(msg)
raise salt.exceptions.SaltSystemExit(code=1)
if not self.opts.get('yes', False):
print('The following keys are going to be accepted:')
salt.output.display_output(
keys,
'key',
self.opts)
try:
veri = input('Proceed? [n/Y] ')
except KeyboardInterrupt:
raise SystemExit("\nExiting on CTRL-c")
if not veri or veri.lower().startswith('y'):
_print_accepted(
matches,
self.key.accept(
match_dict=keys,
include_rejected=include_rejected
)
)
else:
print('The following keys are going to be accepted:')
salt.output.display_output(
keys,
'key',
self.opts)
_print_accepted(
matches,
self.key.accept(
match_dict=keys,
include_rejected=include_rejected
)
)
def accept_all(self, include_rejected=False):
'''
Accept all keys
:param bool include_rejected: Whether or not to accept a matched key that was formerly rejected
'''
self.accept('*', include_rejected=include_rejected)
def delete(self, match):
'''
Delete the matched keys
:param str match: A string to match against. i.e. 'web*'
'''
def _print_deleted(matches, after_match):
deleted = []
for keydir in (self.key.ACC, self.key.PEND, self.key.REJ):
deleted.extend(list(
set(matches.get(keydir, [])).difference(
set(after_match.get(keydir, []))
)
))
for key in sorted(deleted):
print('Key for minion {0} deleted.'.format(key))
matches = self.key.name_match(match)
if not matches:
print(
'The key glob {0!r} does not match any accepted, unaccepted '
'or rejected keys.'.format(match)
)
raise salt.exceptions.SaltSystemExit(code=1)
if not self.opts.get('yes', False):
print('The following keys are going to be deleted:')
salt.output.display_output(
matches,
'key',
self.opts)
try:
veri = input('Proceed? [N/y] ')
except KeyboardInterrupt:
raise SystemExit("\nExiting on CTRL-c")
if veri.lower().startswith('y'):
_print_deleted(
matches,
self.key.delete_key(match_dict=matches)
)
else:
print('Deleting the following keys:')
salt.output.display_output(
matches,
'key',
self.opts)
_print_deleted(
matches,
self.key.delete_key(match_dict=matches)
)
def delete_all(self):
'''
Delete all keys
'''
self.delete('*')
def reject(self, match, include_accepted=False):
'''
Reject the matched keys
:param str match: A string to match against. i.e. 'web*'
:param bool include_accepted: Whether or not to accept a matched key that was formerly accepted
'''
def _print_rejected(matches, after_match):
if self.key.REJ in after_match:
rejected = sorted(
set(after_match[self.key.REJ]).difference(
set(matches.get(self.key.REJ, []))
)
)
for key in rejected:
print('Key for minion {0} rejected.'.format(key))
matches = self.key.name_match(match)
keys = {}
if self.key.PEND in matches:
keys[self.key.PEND] = matches[self.key.PEND]
if include_accepted and bool(matches.get(self.key.ACC)):
keys[self.key.ACC] = matches[self.key.ACC]
if not keys:
msg = 'The key glob {0!r} does not match any {1} keys.'.format(
match,
'accepted or unaccepted' if include_accepted else 'unaccepted'
)
print(msg)
return
if not self.opts.get('yes', False):
print('The following keys are going to be rejected:')
salt.output.display_output(
keys,
'key',
self.opts)
veri = input('Proceed? [n/Y] ')
if veri.lower().startswith('n'):
return
_print_rejected(
matches,
self.key.reject(
match_dict=matches,
include_accepted=include_accepted
)
)
def reject_all(self, include_accepted=False):
'''
Reject all keys
:param bool include_accepted: Whether or not to accept a matched key that was formerly accepted
'''
self.reject('*', include_accepted=include_accepted)
def print_key(self, match):
'''
Print out a single key
:param str match: A string to match against. i.e. 'web*'
'''
matches = self.key.key_str(match)
salt.output.display_output(
matches,
'key',
self.opts)
def print_all(self):
'''
Print out all managed keys
'''
self.print_key('*')
def finger(self, match):
'''
Print out the fingerprints for the matched keys
:param str match: A string to match against. i.e. 'web*'
'''
matches = self.key.finger(match)
salt.output.display_output(
matches,
'key',
self.opts)
def finger_all(self):
'''
Print out all fingerprints
'''
matches = self.key.finger('*')
salt.output.display_output(
matches,
'key',
self.opts)
def prep_signature(self):
'''
Searches for usable keys to create the
master public-key signature
'''
self.privkey = None
self.pubkey = None
# check given pub-key
if self.opts['pub']:
if not os.path.isfile(self.opts['pub']):
print('Public-key {0} does not exist'.format(self.opts['pub']))
return
self.pubkey = self.opts['pub']
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
self.pubkey = mpub
# check given priv-key
if self.opts['priv']:
if not os.path.isfile(self.opts['priv']):
print('Private-key {0} does not exist'.format(self.opts['priv']))
return
self.privkey = self.opts['priv']
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
self.privkey = mpriv
if not self.privkey:
if self.opts['auto_create']:
print('Generating new signing key-pair {0}.* in {1}'
''.format(self.opts['master_sign_key_name'],
self.opts['pki_dir']))
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
self.opts['keysize'],
self.opts.get('user'))
self.privkey = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
print('No usable private-key found')
return
if not self.pubkey:
print('No usable public-key found')
return
print('Using public-key {0}'.format(self.pubkey))
print('Using private-key {0}'.format(self.privkey))
if self.opts['signature_path']:
if not os.path.isdir(self.opts['signature_path']):
print('target directory {0} does not exist'
''.format(self.opts['signature_path']))
else:
self.opts['signature_path'] = self.opts['pki_dir']
sign_path = self.opts['signature_path'] + '/' + self.opts['master_pubkey_signature']
self.key.gen_signature(self.privkey,
self.pubkey,
sign_path)
def run(self):
'''
Run the logic for saltkey
'''
if self.opts['gen_keys']:
self.key.gen_keys()
return
elif self.opts['gen_signature']:
self.prep_signature()
return
if self.opts['list']:
self.list_status(self.opts['list'])
elif self.opts['list_all']:
self.list_all()
elif self.opts['print']:
self.print_key(self.opts['print'])
elif self.opts['print_all']:
self.print_all()
elif self.opts['accept']:
self.accept(
self.opts['accept'],
include_rejected=self.opts['include_all']
)
elif self.opts['accept_all']:
self.accept_all(include_rejected=self.opts['include_all'])
elif self.opts['reject']:
self.reject(
self.opts['reject'],
include_accepted=self.opts['include_all']
)
elif self.opts['reject_all']:
self.reject_all(include_accepted=self.opts['include_all'])
elif self.opts['delete']:
self.delete(self.opts['delete'])
elif self.opts['delete_all']:
self.delete_all()
elif self.opts['finger']:
self.finger(self.opts['finger'])
elif self.opts['finger_all']:
self.finger_all()
else:
self.list_all()
class MultiKeyCLI(KeyCLI):
'''
Manage multiple key backends from the CLI
'''
def __init__(self, opts):
opts['__multi_key'] = True
super(MultiKeyCLI, self).__init__(opts)
# Remove the key attribute set in KeyCLI.__init__
delattr(self, 'key')
zopts = copy.copy(opts)
ropts = copy.copy(opts)
self.keys = {}
zopts['transport'] = 'zeromq'
self.keys['ZMQ Keys'] = KeyCLI(zopts)
ropts['transport'] = 'raet'
self.keys['RAET Keys'] = KeyCLI(ropts)
def _call_all(self, fun, *args):
'''
Call the given function on all backend keys
'''
for kback in self.keys:
print(kback)
getattr(self.keys[kback], fun)(*args)
def list_status(self, status):
self._call_all('list_status', status)
def list_all(self):
self._call_all('list_all')
def accept(self, match, include_rejected=False):
self._call_all('accept', match, include_rejected)
def accept_all(self, include_rejected=False):
self._call_all('accept_all', include_rejected)
def delete(self, match):
self._call_all('delete', match)
def delete_all(self):
self._call_all('delete_all')
def reject(self, match, include_accepted=False):
self._call_all('reject', match, include_accepted)
def reject_all(self, include_accepted=False):
self._call_all('reject_all', include_accepted)
def print_key(self, match):
self._call_all('print_key', match)
def print_all(self):
self._call_all('print_all')
def finger(self, match):
self._call_all('finger', match)
def finger_all(self):
self._call_all('finger_all')
def prep_signature(self):
self._call_all('prep_signature')
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in kinds.APPL_KINDS:
emsg = ("Invalid application kind = '{0}'.".format(kind))
log.error(emsg + '\n')
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def gen_keys(self):
'''
Generate minion RSA public keypair
'''
salt.crypt.gen_keys(
self.opts['gen_keys_dir'],
self.opts['gen_keys'],
self.opts['keysize'])
return
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if not os.path.isdir(m_cache):
return
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False) or not preserve_minions:
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
shutil.rmtree(os.path.join(m_cache, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, str):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.isorted(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.isorted(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.isorted(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = []
# We have to differentiate between RaetKey._check_minions_directories
# and Zeromq-Keys. Raet-Keys only have three states while ZeroMQ-keys
# havd an additional 'denied' state.
if self.opts['transport'] in ('zeromq', 'tcp'):
key_dirs = self._check_minions_directories()
else:
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.isorted(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(fn_)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.isorted(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.isorted(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.isorted(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den'):
ret[os.path.basename(den)] = []
for fn_ in salt.utils.isorted(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.isorted(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.fopen(path, 'r') as fp_:
ret[status][key] = fp_.read()
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.isorted(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.fopen(path, 'r') as fp_:
ret[status][key] = fp_.read()
return ret
def accept(self, match=None, match_dict=None, include_rejected=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload, tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload, tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self, match=None, match_dict=None, preserve_minions=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload, tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache(preserve_minions=matches.get('minions', []))
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload, tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload, tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload, tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match):
'''
Return the fingerprint for a specified key
'''
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.pem_finger(path, sum_type=self.opts['hash_type'])
return ret
def finger_all(self):
'''
Return fingerprins for all keys
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.pem_finger(path, sum_type=self.opts['hash_type'])
return ret
class RaetKey(Key):
'''
Manage keys from the raet backend
'''
ACC = 'accepted'
PEND = 'pending'
REJ = 'rejected'
DEN = None
def __init__(self, opts):
Key.__init__(self, opts)
self.auto_key = salt.daemons.masterapi.AutoKey(self.opts)
self.serial = salt.payload.Serial(self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
accepted = os.path.join(self.opts['pki_dir'], self.ACC)
pre = os.path.join(self.opts['pki_dir'], self.PEND)
rejected = os.path.join(self.opts['pki_dir'], self.REJ)
return accepted, pre, rejected
def check_minion_cache(self, preserve_minions=False):
'''
Check the minion cache to make sure that old minion data is cleared
'''
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
m_cache = os.path.join(self.opts['cachedir'], 'minions')
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions:
shutil.rmtree(os.path.join(m_cache, minion))
kind = self.opts.get('__role', '') # application kind
if kind not in kinds.APPL_KINDS:
emsg = ("Invalid application kind = '{0}'.".format(kind))
log.error(emsg + '\n')
raise ValueError(emsg)
role = self.opts.get('id', '')
if not role:
emsg = ("Invalid id.")
log.error(emsg + "\n")
raise ValueError(emsg)
name = "{0}_{1}".format(role, kind)
road_cache = os.path.join(self.opts['cachedir'],
'raet',
name,
'remote')
if os.path.isdir(road_cache):
for road in os.listdir(road_cache):
root, ext = os.path.splitext(road)
if ext not in ['.json', '.msgpack']:
continue
prefix, sep, name = root.partition('.')
if not name or prefix != 'estate':
continue
path = os.path.join(road_cache, road)
with salt.utils.fopen(path, 'rb') as fp_:
if ext == '.json':
data = json.load(fp_)
elif ext == '.msgpack':
data = msgpack.load(fp_)
if data['role'] not in minions:
os.remove(path)
def gen_keys(self):
'''
Use libnacl to generate and safely save a private key
'''
import libnacl.public
d_key = libnacl.dual.DualSecret()
path = '{0}.key'.format(os.path.join(
self.opts['gen_keys_dir'],
self.opts['gen_keys']))
d_key.save(path, 'msgpack')
def check_master(self):
'''
Log if the master is not running
NOT YET IMPLEMENTED
'''
return True
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
fn_ = os.path.join(self.opts['pki_dir'], 'local.key')
if os.path.isfile(fn_):
ret['local'].append(fn_)
return ret
def status(self, minion_id, pub, verify):
'''
Accepts the minion id, device id, curve public and verify keys.
If the key is not present, put it in pending and return "pending",
If the key has been accepted return "accepted"
if the key should be rejected, return "rejected"
'''
acc, pre, rej = self._check_minions_directories() # pylint: disable=W0632
acc_path = os.path.join(acc, minion_id)
pre_path = os.path.join(pre, minion_id)
rej_path = os.path.join(rej, minion_id)
# open mode is turned on, force accept the key
keydata = {
'minion_id': minion_id,
'pub': pub,
'verify': verify}
if self.opts['open_mode']: # always accept and overwrite
with salt.utils.fopen(acc_path, 'w+b') as fp_:
fp_.write(self.serial.dumps(keydata))
return self.ACC
if os.path.isfile(rej_path):
log.debug("Rejection Reason: Keys already rejected.\n")
return self.REJ
elif os.path.isfile(acc_path):
# The minion id has been accepted, verify the key strings
with salt.utils.fopen(acc_path, 'rb') as fp_:
keydata = self.serial.loads(fp_.read())
if keydata['pub'] == pub and keydata['verify'] == verify:
return self.ACC
else:
log.debug("Rejection Reason: Keys not match prior accepted.\n")
return self.REJ
elif os.path.isfile(pre_path):
auto_reject = self.auto_key.check_autoreject(minion_id)
auto_sign = self.auto_key.check_autosign(minion_id)
with salt.utils.fopen(pre_path, 'rb') as fp_:
keydata = self.serial.loads(fp_.read())
if keydata['pub'] == pub and keydata['verify'] == verify:
if auto_reject:
self.reject(minion_id)
log.debug("Rejection Reason: Auto reject pended.\n")
return self.REJ
elif auto_sign:
self.accept(minion_id)
return self.ACC
return self.PEND
else:
log.debug("Rejection Reason: Keys not match prior pended.\n")
return self.REJ
# This is a new key, evaluate auto accept/reject files and place
# accordingly
auto_reject = self.auto_key.check_autoreject(minion_id)
auto_sign = self.auto_key.check_autosign(minion_id)
if self.opts['auto_accept']:
w_path = acc_path
ret = self.ACC
elif auto_sign:
w_path = acc_path
ret = self.ACC
elif auto_reject:
w_path = rej_path
log.debug("Rejection Reason: Auto reject new.\n")
ret = self.REJ
else:
w_path = pre_path
ret = self.PEND
with salt.utils.fopen(w_path, 'w+b') as fp_:
fp_.write(self.serial.dumps(keydata))
return ret
def _get_key_str(self, minion_id, status):
'''
Return the key string in the form of:
pub: <pub>
verify: <verify>
'''
path = os.path.join(self.opts['pki_dir'], status, minion_id)
with salt.utils.fopen(path, 'r') as fp_:
keydata = self.serial.loads(fp_.read())
return 'pub: {0}\nverify: {1}'.format(
keydata['pub'],
keydata['verify'])
def _get_key_finger(self, path):
'''
Return a sha256 kingerprint for the key
'''
with salt.utils.fopen(path, 'r') as fp_:
keydata = self.serial.loads(fp_.read())
key = 'pub: {0}\nverify: {1}'.format(
keydata['pub'],
keydata['verify'])
return hashlib.sha256(key).hexdigest()
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.isorted(keys):
ret[status][key] = self._get_key_str(key, status)
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.isorted(keys):
ret[status][key] = self._get_key_str(key, status)
return ret
def accept(self, match=None, match_dict=None, include_rejected=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self, match=None, match_dict=None, preserve_minions=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
except (OSError, IOError):
pass
self.check_minion_cache(preserve_minions=matches.get('minions', []))
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
except (IOError, OSError):
pass
self.check_minion_cache()
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
except (IOError, OSError):
pass
self.check_minion_cache()
return self.list_keys()
def finger(self, match):
'''
Return the fingerprint for a specified key
'''
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = self._get_key_finger(path)
return ret
def finger_all(self):
'''
Return fingerprints for all keys
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = self._get_key_finger(path)
return ret
def read_all_remote(self):
'''
Return a dict of all remote key data
'''
data = {}
for status, mids in six.iteritems(self.list_keys()):
for mid in mids:
keydata = self.read_remote(mid, status)
if keydata:
keydata['acceptance'] = status
data[mid] = keydata
return data
def read_remote(self, minion_id, status=ACC):
'''
Read in a remote key of status
'''
path = os.path.join(self.opts['pki_dir'], status, minion_id)
if not os.path.isfile(path):
return {}
with salt.utils.fopen(path, 'rb') as fp_:
return self.serial.loads(fp_.read())
def read_local(self):
'''
Read in the local private keys, return an empy dict if the keys do not
exist
'''
path = os.path.join(self.opts['pki_dir'], 'local.key')
if not os.path.isfile(path):
return {}
with salt.utils.fopen(path, 'rb') as fp_:
return self.serial.loads(fp_.read())
def write_local(self, priv, sign):
'''
Write the private key and the signing key to a file on disk
'''
keydata = {'priv': priv,
'sign': sign}
path = os.path.join(self.opts['pki_dir'], 'local.key')
c_umask = os.umask(191)
if os.path.exists(path):
#mode = os.stat(path).st_mode
os.chmod(path, stat.S_IWUSR | stat.S_IRUSR)
with salt.utils.fopen(path, 'w+') as fp_:
fp_.write(self.serial.dumps(keydata))
os.chmod(path, stat.S_IRUSR)
os.umask(c_umask)
def delete_local(self):
'''
Delete the local private key file
'''
path = os.path.join(self.opts['pki_dir'], 'local.key')
if os.path.isfile(path):
os.remove(path)
def delete_pki_dir(self):
'''
Delete the private key directory
'''
path = self.opts['pki_dir']
if os.path.exists(path):
shutil.rmtree(path)
|
Java
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'chapter4-components',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
contentSecurityPolicy: {
'default-src': "'none'",
'script-src': "'self' 'unsafe-inline' 'unsafe-eval' *",
'font-src': "'self' *",
'connect-src': "'self' *",
'img-src': "'self' *",
'style-src': "'self' 'unsafe-inline' *",
'frame-src': "*"
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
Java
|
require_relative '../lib/rails_stub'
require_relative 'lib/pb_core_ingester'
require_relative '../lib/has_logger'
require 'rake'
require_relative '../app/models/collection'
require_relative '../app/models/exhibit'
class Exception
def short
message + "\n" + backtrace[0..2].join("\n")
end
end
class ParamsError < StandardError
end
class Ingest
include HasLogger
def const_init(name)
const_name = name.upcase.tr('-', '_')
flag_name = "--#{name}"
begin
# to avoid "warning: already initialized constant" in tests.
Ingest.const_get(const_name)
rescue NameError
Ingest.const_set(const_name, flag_name)
end
end
def initialize(argv)
orig_argv = argv.dup
%w(files dirs grep-files grep-dirs).each do |name|
const_init(name)
end
%w(batch-commit stdout-log).each do |name|
flag_name = const_init(name)
variable_name = "@is_#{name.tr('-', '_')}"
instance_variable_set(variable_name, argv.include?(flag_name))
argv.delete(flag_name)
end
# The code above sets fields which log_init needs,
# but it also modifies argv in place, so we need the dup.
log_init!(orig_argv)
mode = argv.shift
args = argv
@flags = { is_just_reindex: @is_just_reindex }
begin
case mode
when DIRS
fail ParamsError.new if args.empty? || args.map { |dir| !File.directory?(dir) }.any?
target_dirs = args
when FILES
fail ParamsError.new if args.empty?
@files = args
when GREP_DIRS
fail ParamsError.new if args.empty?
@regex = argv.shift
fail ParamsError.new if args.empty? || args.map { |dir| !File.directory?(dir) }.any?
target_dirs = args
when GREP_FILES
fail ParamsError.new if args.empty?
@regex = argv.shift
fail ParamsError.new if args.empty?
@files = args
else
fail ParamsError.new
end
rescue ParamsError
abort usage_message
end
@files ||= target_dirs.map do |target_dir|
Dir.entries(target_dir)
.reject { |file_name| ['.', '..'].include?(file_name) }
.map { |file_name| "#{target_dir}/#{file_name}" }
end.flatten.sort
end
def log_init!(argv)
# Specify a log file unless we are logging to stdout
unless @is_stdout_log
self.logger = Logger.new(log_file_name)
# Print to stdout where the logfile is
puts "logging to #{log_file_name}"
end
logger.formatter = proc do |severity, datetime, _progname, msg|
"#{severity} [#{datetime.strftime('%Y-%m-%d %H:%M:%S')}]: #{msg}\n"
end
# Log how the script was invoked
logger.info("START: Process ##{Process.pid}: #{__FILE__} #{argv.join(' ')}")
end
def usage_message
<<-EOF.gsub(/^ {4}/, '')
USAGE: #{File.basename(__FILE__)}
[#{BATCH_COMMIT}] [#{STDOUT_LOG}]
#{FILES} FILE ... |
#{DIRS} DIR ... |
#{GREP_FILES} REGEX FILE ... |
#{GREP_DIRS} REGEX DIR ...
boolean flags:
#{BATCH_COMMIT}: Optionally, make just one commit at the end, rather than
one commit per file.
#{STDOUT_LOG}: Optionally, log to stdout, rather than a log file.
mutually exclusive modes:
#{DIRS}: Clean and ingest the given directories.
#{FILES}: Clean and ingest the given files (either xml or zip).
#{GREP_DIRS} and #{GREP_FILES}: Same as above, except a regex is also provided.
Only PBCore which matches the regexp is ingested.
EOF
end
def process
ingester = PBCoreIngester.new(regex: @regex)
# set the PBCoreIngester's logger to the same as this object's logger
ingester.logger = logger
@files.each do |path|
begin
success_count_before = ingester.success_count
error_count_before = ingester.errors.values.flatten.count
ingester.ingest(path: path, is_batch_commit: @is_batch_commit)
success_count_after = ingester.success_count
error_count_after = ingester.errors.values.flatten.count
logger.info("Processed '#{path}' #{'but not committed' if @is_batch_commit}")
logger.info("success: #{success_count_after - success_count_before}; " \
"error: #{error_count_after - error_count_before}")
end
end
if @is_batch_commit
logger.info('Starting one big commit...')
ingester.commit
logger.info('Finished one big commit.')
end
# TODO: Investigate whether optimization is worth it. Requires a lot of disk and time.
# puts 'Ingest complete; Begin optimization...'
# ingester.optimize
errors = ingester.errors.sort # So related errors are together
error_count = errors.map { |pair| pair[1] }.flatten.count
success_count = ingester.success_count
total_count = error_count + success_count
logger.info('SUMMARY: DETAIL')
errors.each do |type, list|
logger.warn("#{list.count} #{type} errors:\n#{list.join("\n")}")
end
logger.info('SUMMARY: STATS')
logger.info('(Look just above for details on each error.)')
errors.each do |type, list|
logger.warn("#{list.count} (#{percent(list.count, total_count)}%) #{type}")
end
logger.info("#{success_count} (#{percent(success_count, total_count)}%) succeeded")
logger.info('DONE')
end
def percent(part, whole)
(100.0 * part / whole).round(1)
end
def log_file_name
@log_file_name ||= "#{Rails.root}/log/ingest.#{Time.now.strftime('%Y-%m-%d_%H%M%S')}.log"
end
end
Ingest.new(ARGV).process if __FILE__ == $PROGRAM_NAME
|
Java
|
Python 机器学习的必备技巧
======
> 尝试使用 Python 掌握机器学习、人工智能和深度学习。

想要入门机器学习并不难。除了<ruby>大规模网络公开课<rt>Massive Open Online Courses</rt></ruby>(MOOCs)之外,还有很多其它优秀的免费资源。下面我分享一些我觉得比较有用的方法。
1. 阅览一些关于这方面的视频、文章或者书籍,例如 [The Master Algorithm: How the Quest for the Ultimate Learning Machine Will Remake Our World][29],你肯定会喜欢这些[关于机器学习的互动页面][30]。
2. 对于“机器学习”、“人工智能”、“深度学习”、“数据科学”、“计算机视觉”和“机器人技术”这一堆新名词,你需要知道它们之前的区别。你可以阅览这些领域的专家们的演讲,例如[数据科学家 Brandon Rohrer 的这个视频][1]。
3. 明确你自己的学习目标,并选择合适的 [Coursera 课程][3],或者参加高校的网络公开课。例如[华盛顿大学的课程][4]就很不错。
4. 关注优秀的博客:例如 [KDnuggets][32] 的博客、[Mark Meloon][33] 的博客、[Brandon Rohrer][34] 的博客、[Open AI][35] 的博客,这些都值得推荐。
5. 如果你对在线课程有很大兴趣,后文中会有如何[正确选择 MOOC 课程][31]的指导。
6. 最重要的是,培养自己对这些技术的兴趣。加入一些优秀的社交论坛,专注于阅读和了解,将这些技术的背景知识和发展方向理解透彻,并积极思考在日常生活和工作中如何应用机器学习或数据科学的原理。例如建立一个简单的回归模型来预测下一次午餐的成本,又或者是从电力公司的网站上下载历史电费数据,在 Excel 中进行简单的时序分析以发现某种规律。在你对这些技术产生了浓厚兴趣之后,可以观看以下这个视频。
<https://www.youtube.com/embed/IpGxLWOIZy4>
### Python 是机器学习和人工智能方面的最佳语言吗?
除非你是一名专业的研究一些复杂算法纯理论证明的研究人员,否则,对于一个机器学习的入门者来说,需要熟悉至少一种高级编程语言一家相关的专业知识。因为大多数情况下都是需要考虑如何将机器学习算法应用于解决实际问题,而这需要有一定的编程能力作为基础。
哪一种语言是数据科学的最佳语言?这个讨论一直没有停息过。对于这方面,你可以提起精神来看一下 FreeCodeCamp 上这一篇关于[数据科学语言][6]的文章,又或者是 KDnuggets 关于 [Python 和 R][7] 之间的深入探讨。
目前人们普遍认为 Python 在开发、部署、维护各方面的效率都是比较高的。与 Java、C 和 C++ 这些较为传统的语言相比,Python 的语法更为简单和高级。而且 Python 拥有活跃的社区群体、广泛的开源文化、数百个专用于机器学习的优质代码库,以及来自业界巨头(包括Google、Dropbox、Airbnb 等)的强大技术支持。
### 基础 Python 库
如果你打算使用 Python 实施机器学习,你必须掌握一些 Python 包和库的使用方法。
#### NumPy
NumPy 的完整名称是 [Numerical Python][8],它是 Python 生态里高性能科学计算和数据分析都需要用到的基础包,几乎所有高级工具(例如 [Pandas][9] 和 [scikit-learn][10])都依赖于它。[TensorFlow][11] 使用了 NumPy 数组作为基础构建块以支持 Tensor 对象和深度学习的图形流。很多 NumPy 操作的速度都非常快,因为它们都是通过 C 实现的。高性能对于数据科学和现代机器学习来说是一个非常宝贵的优势。

#### Pandas
Pandas 是 Python 生态中用于进行通用数据分析的最受欢迎的库。Pandas 基于 NumPy 数组构建,在保证了可观的执行速度的同时,还提供了许多数据工程方面的功能,包括:
* 对多种不同数据格式的读写操作
* 选择数据子集
* 跨行列计算
* 查找并补充缺失的数据
* 将操作应用于数据中的独立组
* 按照多种格式转换数据
* 组合多个数据集
* 高级时间序列功能
* 通过 Matplotlib 和 Seaborn 进行可视化

#### Matplotlib 和 Seaborn
数据可视化和数据分析是数据科学家的必备技能,毕竟仅凭一堆枯燥的数据是无法有效地将背后蕴含的信息向受众传达的。这两项技能对于机器学习来说同样重要,因为首先要对数据集进行一个探索性分析,才能更准确地选择合适的机器学习算法。
[Matplotlib][12] 是应用最广泛的 2D Python 可视化库。它包含海量的命令和接口,可以让你根据数据生成高质量的图表。要学习使用 Matplotlib,可以参考这篇详尽的[文章][13]。

[Seaborn][14] 也是一个强大的用于统计和绘图的可视化库。它在 Matplotlib 的基础上提供样式灵活的 API、用于统计和绘图的常见高级函数,还可以和 Pandas 提供的功能相结合。要学习使用 Seaborn,可以参考这篇优秀的[教程][15]。

#### Scikit-learn
Scikit-learn 是机器学习方面通用的重要 Python 包。它实现了多种[分类][16]、[回归][17]和[聚类][18]算法,包括[支持向量机][19]、[随机森林][20]、[梯度增强][21]、[k-means 算法][22]和 [DBSCAN 算法][23],可以与 Python 的数值库 NumPy 和科学计算库 [SciPy][24] 结合使用。它通过兼容的接口提供了有监督和无监督的学习算法。Scikit-learn 的强壮性让它可以稳定运行在生产环境中,同时它在易用性、代码质量、团队协作、文档和性能等各个方面都有良好的表现。可以参考这篇基于 Scikit-learn 的[机器学习入门][25],或者这篇基于 Scikit-learn 的[简单机器学习用例演示][26]。
本文使用 [CC BY-SA 4.0][28] 许可,在 [Heartbeat][27] 上首发。
--------------------------------------------------------------------------------
via: https://opensource.com/article/18/10/machine-learning-python-essential-hacks-and-tricks
作者:[Tirthajyoti Sarkar][a]
选题:[lujun9972][b]
译者:[HankChow](https://github.com/HankChow)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/tirthajyoti
[b]: https://github.com/lujun9972
[1]: https://www.youtube.com/watch?v=tKa0zDDDaQk
[2]: https://www.youtube.com/watch?v=Ura_ioOcpQI
[3]: https://www.coursera.org/learn/machine-learning
[4]: https://www.coursera.org/specializations/machine-learning
[5]: https://towardsdatascience.com/how-to-choose-effective-moocs-for-machine-learning-and-data-science-8681700ed83f
[6]: https://medium.freecodecamp.org/which-languages-should-you-learn-for-data-science-e806ba55a81f
[7]: https://www.kdnuggets.com/2017/09/python-vs-r-data-science-machine-learning.html
[8]: http://numpy.org/
[9]: https://pandas.pydata.org/
[10]: http://scikit-learn.org/
[11]: https://www.tensorflow.org/
[12]: https://matplotlib.org/
[13]: https://realpython.com/python-matplotlib-guide/
[14]: https://seaborn.pydata.org/
[15]: https://www.datacamp.com/community/tutorials/seaborn-python-tutorial
[16]: https://en.wikipedia.org/wiki/Statistical_classification
[17]: https://en.wikipedia.org/wiki/Regression_analysis
[18]: https://en.wikipedia.org/wiki/Cluster_analysis
[19]: https://en.wikipedia.org/wiki/Support_vector_machine
[20]: https://en.wikipedia.org/wiki/Random_forests
[21]: https://en.wikipedia.org/wiki/Gradient_boosting
[22]: https://en.wikipedia.org/wiki/K-means_clustering
[23]: https://en.wikipedia.org/wiki/DBSCAN
[24]: https://en.wikipedia.org/wiki/SciPy
[25]: http://scikit-learn.org/stable/tutorial/basic/tutorial.html
[26]: https://towardsdatascience.com/machine-learning-with-python-easy-and-robust-method-to-fit-nonlinear-data-19e8a1ddbd49
[27]: https://heartbeat.fritz.ai/some-essential-hacks-and-tricks-for-machine-learning-with-python-5478bc6593f2
[28]: https://creativecommons.org/licenses/by-sa/4.0/
[29]: https://www.goodreads.com/book/show/24612233-the-master-algorithm
[30]: http://www.r2d3.us/visual-intro-to-machine-learning-part-1/
[31]: https://towardsdatascience.com/how-to-choose-effective-moocs-for-machine-learning-and-data-science-8681700ed83f
[32]: https://www.kdnuggets.com/
[33]: http://www.markmeloon.com/
[34]: https://brohrer.github.io/blog.html
[35]: https://blog.openai.com/
|
Java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import javax.mail.Address;
/**
* Term that compares two addresses.
*
* @version $Rev: 920714 $ $Date: 2010-03-09 07:55:49 +0100 (Di, 09. Mär 2010) $
*/
public abstract class AddressTerm extends SearchTerm {
private static final long serialVersionUID = 2005405551929769980L;
/**
* The address.
*/
protected Address address;
/**
* Constructor taking the address for this term.
* @param address the address
*/
protected AddressTerm(Address address) {
this.address = address;
}
/**
* Return the address of this term.
*
* @return the addre4ss
*/
public Address getAddress() {
return address;
}
/**
* Match to the supplied address.
*
* @param address the address to match with
* @return true if the addresses match
*/
protected boolean match(Address address) {
return this.address.equals(address);
}
public boolean equals(Object other) {
if (this == other) return true;
if (other instanceof AddressTerm == false) return false;
return address.equals(((AddressTerm) other).address);
}
public int hashCode() {
return address.hashCode();
}
}
|
Java
|
// ==UserScript==
// @name tabtweet
// @namespace http://chiptheglasses.com
// @description add a classic RT button to tweets
// @include http://*twitter.com*
// ==/UserScript==
// contains jQuery 1.4.1; It is patched.
/*!
* jQuery JavaScript Library v1.4.1
* http://jquery.com/
*
* Copyright 2010, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2010, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Mon Jan 25 19:43:33 2010 -0500
*/
(function(z,v){function la(){if(!c.isReady){try{r.documentElement.doScroll("left")}catch(a){setTimeout(la,1);return}c.ready()}}function Ma(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,i){var j=a.length;if(typeof b==="object"){for(var n in b)X(a,n,b[n],f,e,d);return a}if(d!==v){f=!i&&f&&c.isFunction(d);for(n=0;n<j;n++)e(a[n],b,f?d.call(a[n],n,e(a[n],b)):d,i);return a}return j?
e(a[0],b):null}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function ma(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function na(a){var b,d=[],f=[],e=arguments,i,j,n,o,m,s,x=c.extend({},c.data(this,"events").live);if(!(a.button&&a.type==="click")){for(o in x){j=x[o];if(j.live===a.type||j.altLive&&c.inArray(a.type,j.altLive)>-1){i=j.data;i.beforeFilter&&i.beforeFilter[a.type]&&!i.beforeFilter[a.type](a)||f.push(j.selector)}else delete x[o]}i=c(a.target).closest(f,
a.currentTarget);m=0;for(s=i.length;m<s;m++)for(o in x){j=x[o];n=i[m].elem;f=null;if(i[m].selector===j.selector){if(j.live==="mouseenter"||j.live==="mouseleave")f=c(a.relatedTarget).closest(j.selector)[0];if(!f||f!==n)d.push({elem:n,fn:j})}}m=0;for(s=d.length;m<s;m++){i=d[m];a.currentTarget=i.elem;a.data=i.fn.data;if(i.fn.apply(i.elem,e)===false){b=false;break}}return b}}function oa(a,b){return"live."+(a?a+".":"")+b.replace(/\./g,"`").replace(/ /g,"&")}function pa(a){return!a||!a.parentNode||a.parentNode.nodeType===
11}function qa(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var i in f)for(var j in f[i])c.event.add(this,i,f[i][j],f[i][j].data)}}})}function ra(a,b,d){var f,e,i;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&a[0].indexOf("<option")<0&&(c.support.checkClone||!sa.test(a[0]))){e=true;if(i=c.fragments[a[0]])if(i!==1)f=i}if(!f){b=b&&b[0]?b[0].ownerDocument||b[0]:r;f=b.createDocumentFragment();
c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=i?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(ta.concat.apply([],ta.slice(0,b)),function(){d[this]=a});return d}function ua(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Na=z.jQuery,Oa=z.$,r=z.document,S,Pa=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Qa=/^.[^:#\[\.,]*$/,Ra=/\S/,Sa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Ta=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,O=navigator.userAgent,
va=false,P=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,Q=Array.prototype.slice,wa=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(typeof a==="string")if((d=Pa.exec(a))&&(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:r;if(a=Ta.exec(a))if(c.isPlainObject(b)){a=[r.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=ra([d[1]],
[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}}else{if(b=r.getElementById(d[2])){if(b.id!==d[2])return S.find(a);this.length=1;this[0]=b}this.context=r;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=r;a=r.getElementsByTagName(a)}else return!b||b.jquery?(b||S).find(a):c(b).find(a);else if(c.isFunction(a))return S.ready(a);if(a.selector!==v){this.selector=a.selector;this.context=a.context}return c.isArray(a)?this.setArray(a):c.makeArray(a,
this)},selector:"",jquery:"1.4.1",length:0,size:function(){return this.length},toArray:function(){return Q.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){a=c(a||null);a.prevObject=this;a.context=this.context;if(b==="find")a.selector=this.selector+(this.selector?" ":"")+d;else if(b)a.selector=this.selector+"."+b+"("+d+")";return a},setArray:function(a){this.length=0;ba.apply(this,a);return this},each:function(a,b){return c.each(this,
a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(r,c);else P&&P.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(Q.apply(this,arguments),"slice",Q.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this,function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};
c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,i,j,n;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(i in e){j=a[i];n=e[i];if(a!==n)if(f&&n&&(c.isPlainObject(n)||c.isArray(n))){j=j&&(c.isPlainObject(j)||c.isArray(j))?j:c.isArray(n)?[]:{};a[i]=c.extend(f,j,n)}else if(n!==v)a[i]=n}return a};c.extend({noConflict:function(a){z.$=
Oa;if(a)z.jQuery=Na;return c},isReady:false,ready:function(){if(!c.isReady){if(!r.body)return setTimeout(c.ready,13);c.isReady=true;if(P){for(var a,b=0;a=P[b++];)a.call(r,c);P=null}c.fn.triggerHandler&&c(r).triggerHandler("ready")}},bindReady:function(){if(!va){va=true;if(r.readyState==="complete")return c.ready();if(r.addEventListener){r.addEventListener("DOMContentLoaded",L,false);z.addEventListener("load",c.ready,false)}else if(r.attachEvent){r.attachEvent("onreadystatechange",L);z.attachEvent("onload",
c.ready);var a=false;try{a=z.frameElement==null}catch(b){}r.documentElement.doScroll&&a&&la()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype,"isPrototypeOf"))return false;var b;for(b in a);return b===v||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;
return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return z.JSON&&z.JSON.parse?z.JSON.parse(a):(new Function("return "+a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Ra.test(a)){var b=r.getElementsByTagName("head")[0]||
r.documentElement,d=r.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(r.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,i=a.length,j=i===v||c.isFunction(a);if(d)if(j)for(f in a){if(b.apply(a[f],d)===false)break}else for(;e<i;){if(b.apply(a[e++],d)===false)break}else if(j)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=
a[0];e<i&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Sa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]===a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==
v;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,i=a.length;e<i;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,i=0,j=a.length;i<j;i++){e=b(a[i],i,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=v}else if(b&&!c.isFunction(b)){d=b;b=v}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},
uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});O=c.uaMatch(O);if(O.browser){c.browser[O.browser]=true;c.browser.version=O.version}if(c.browser.webkit)c.browser.safari=true;if(wa)c.inArray=function(a,b){return wa.call(b,a)};S=c(r);if(r.addEventListener)L=function(){r.removeEventListener("DOMContentLoaded",
L,false);c.ready()};else if(r.attachEvent)L=function(){if(r.readyState==="complete"){r.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=r.documentElement,b=r.createElement("script"),d=r.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var e=d.getElementsByTagName("*"),i=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!i)){c.support=
{leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(i.getAttribute("style")),hrefNormalized:i.getAttribute("href")==="/a",opacity:/^0.55$/.test(i.style.opacity),cssFloat:!!i.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:r.createElement("select").appendChild(r.createElement("option")).selected,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};
b.type="text/javascript";try{b.appendChild(r.createTextNode("window."+f+"=1;"))}catch(j){}a.insertBefore(b,a.firstChild);if(z[f]){c.support.scriptEval=true;delete z[f]}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function n(){c.support.noCloneEvent=false;d.detachEvent("onclick",n)});d.cloneNode(true).fireEvent("onclick")}d=r.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=r.createDocumentFragment();a.appendChild(d.firstChild);
c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var n=r.createElement("div");n.style.width=n.style.paddingLeft="1px";r.body.appendChild(n);c.boxModel=c.support.boxModel=n.offsetWidth===2;r.body.removeChild(n).style.display="none"});a=function(n){var o=r.createElement("div");n="on"+n;var m=true;if(!m){o.setAttribute(n,"return;");m=typeof o[n]==="function"}return m};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=i=null}})();c.props=
{"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ua=0,xa={},Va={};c.extend({cache:{},expando:G,noData:{embed:true,object:true,applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==z?xa:a;var f=a[G],e=c.cache;if(!b&&!f)return null;f||(f=++Ua);if(typeof b==="object"){a[G]=f;e=e[f]=c.extend(true,
{},b)}else e=e[f]?e[f]:typeof d==="undefined"?Va:(e[f]={});if(d!==v){a[G]=f;e[b]=d}return typeof b==="string"?e[b]:e}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==z?xa:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{try{delete a[G]}catch(i){a.removeAttribute&&a.removeAttribute(G)}delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,
a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===v){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===v&&this.length)f=c.data(this[0],a);return f===v&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this,a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);
return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===v)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||
a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var ya=/[\n\t]/g,ca=/\s+/,Wa=/\r/g,Xa=/href|src|style/,Ya=/(button|input)/i,Za=/(button|input|object|select|textarea)/i,$a=/^(a|area)$/i,za=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(o){var m=
c(this);m.addClass(a.call(this,o,m.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className)for(var i=" "+e.className+" ",j=0,n=b.length;j<n;j++){if(i.indexOf(" "+b[j]+" ")<0)e.className+=" "+b[j]}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(o){var m=c(this);m.removeClass(a.call(this,o,m.attr("class")))});if(a&&typeof a==="string"||a===v)for(var b=(a||"").split(ca),
d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var i=(" "+e.className+" ").replace(ya," "),j=0,n=b.length;j<n;j++)i=i.replace(" "+b[j]+" "," ");e.className=i.substring(1,i.length-1)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var i=c(this);i.toggleClass(a.call(this,e,i.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,i=0,j=c(this),n=b,o=
a.split(ca);e=o[i++];){n=f?n:!j.hasClass(e);j[n?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(ya," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===v){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||
{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var i=b?d:0;for(d=b?d+1:e.length;i<d;i++){var j=e[i];if(j.selected){a=c(j).val();if(b)return a;f.push(a)}}return f}if(za.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Wa,"")}return v}var n=c.isFunction(a);return this.each(function(o){var m=c(this),s=a;if(this.nodeType===1){if(n)s=a.call(this,o,m.val());
if(typeof s==="number")s+="";if(c.isArray(s)&&za.test(this.type))this.checked=c.inArray(m.val(),s)>=0;else if(c.nodeName(this,"select")){var x=c.makeArray(s);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),x)>=0});if(!x.length)this.selectedIndex=-1}else this.value=s}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return v;if(f&&b in c.attrFn)return c(a)[b](d);
f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==v;b=f&&c.props[b]||b;if(a.nodeType===1){var i=Xa.test(b);if(b in a&&f&&!i){if(e){b==="type"&&Ya.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:Za.test(a.nodeName)||$a.test(a.nodeName)&&a.href?0:v;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=
""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&i?a.getAttribute(b,2):a.getAttribute(b);return a===null?v:a}return c.style(a,b,d)}});var ab=function(a){return a.replace(/[^\w\s\.\|`]/g,function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==z&&!a.frameElement)a=z;if(!d.guid)d.guid=c.guid++;if(f!==v){d=c.proxy(d);d.data=f}var e=c.data(a,"events")||c.data(a,"events",{}),i=c.data(a,"handle"),j;if(!i){j=
function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(j.elem,arguments):v};i=c.data(a,"handle",j)}if(i){i.elem=a;b=b.split(/\s+/);for(var n,o=0;n=b[o++];){var m=n.split(".");n=m.shift();if(o>1){d=c.proxy(d);if(f!==v)d.data=f}d.type=m.slice(0).sort().join(".");var s=e[n],x=this.special[n]||{};if(!s){s=e[n]={};if(!x.setup||x.setup.call(a,f,m,d)===false)if(a.addEventListener)a.addEventListener(n,i,false);else a.attachEvent&&a.attachEvent("on"+n,i)}if(x.add)if((m=x.add.call(a,
d,f,m,s))&&c.isFunction(m)){m.guid=m.guid||d.guid;m.data=m.data||d.data;m.type=m.type||d.type;d=m}s[d.guid]=d;this.global[n]=true}a=null}}},global:{},remove:function(a,b,d){if(!(a.nodeType===3||a.nodeType===8)){var f=c.data(a,"events"),e,i,j;if(f){if(b===v||typeof b==="string"&&b.charAt(0)===".")for(i in f)this.remove(a,i+(b||""));else{if(b.type){d=b.handler;b=b.type}b=b.split(/\s+/);for(var n=0;i=b[n++];){var o=i.split(".");i=o.shift();var m=!o.length,s=c.map(o.slice(0).sort(),ab);s=new RegExp("(^|\\.)"+
s.join("\\.(?:.*\\.)?")+"(\\.|$)");var x=this.special[i]||{};if(f[i]){if(d){j=f[i][d.guid];delete f[i][d.guid]}else for(var A in f[i])if(m||s.test(f[i][A].type))delete f[i][A];x.remove&&x.remove.call(a,o,j);for(e in f[i])break;if(!e){if(!x.teardown||x.teardown.call(a,o)===false)if(a.removeEventListener)a.removeEventListener(i,c.data(a,"handle"),false);else a.detachEvent&&a.detachEvent("on"+i,c.data(a,"handle"));e=null;delete f[i]}}}}for(e in f)break;if(!e){if(A=c.data(a,"handle"))A.elem=null;c.removeData(a,
"events");c.removeData(a,"handle")}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type=e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();this.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return v;a.result=v;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,
b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(i){}if(!a.isPropagationStopped()&&f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){d=a.target;var j;if(!(c.nodeName(d,"a")&&e==="click")&&!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()])){try{if(d[e]){if(j=d["on"+e])d["on"+e]=null;this.triggered=true;d[e]()}}catch(n){}if(j)d["on"+e]=j;this.triggered=false}}},handle:function(a){var b,
d;a=arguments[0]=c.event.fix(a||z.event);a.currentTarget=this;d=a.type.split(".");a.type=d.shift();b=!d.length&&!a.exclusive;var f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)");d=(c.data(this,"events")||{})[a.type];for(var e in d){var i=d[e];if(b||f.test(i.type)){a.handler=i;a.data=i.data;i=i.apply(this,arguments);if(i!==v){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||r;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=r.documentElement;d=r.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==v)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a,b){c.extend(a,b||{});a.guid+=b.selector+b.live;b.liveProxy=a;c.event.add(this,b.live,na,b)},remove:function(a){if(a.length){var b=
0,d=new RegExp("(^|\\.)"+a[0]+"(\\.|$)");c.each(c.data(this,"events").live||{},function(){d.test(this.type)&&b++});b<1&&c.event.remove(this,a[0],na)}},special:{}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};
c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y,isImmediatePropagationStopped:Y};var Aa=function(a){for(var b=
a.relatedTarget;b&&b!==this;)try{b=b.parentNode}catch(d){break}if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}},Ba=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ba:Aa,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ba:Aa)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(a,b,d){if(this.nodeName.toLowerCase()!==
"form"){c.event.add(this,"click.specialSubmit."+d.guid,function(f){var e=f.target,i=e.type;if((i==="submit"||i==="image")&&c(e).closest("form").length)return ma("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit."+d.guid,function(f){var e=f.target,i=e.type;if((i==="text"||i==="password")&&c(e).closest("form").length&&f.keyCode===13)return ma("submit",this,arguments)})}else return false},remove:function(a,b){c.event.remove(this,"click.specialSubmit"+(b?"."+b.guid:""));c.event.remove(this,
"keypress.specialSubmit"+(b?"."+b.guid:""))}};if(!c.support.changeBubbles){var da=/textarea|input|select/i;function Ca(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d}function ea(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Ca(d);if(a.type!=="focusout"||
d.type!=="radio")c.data(d,"_change_data",e);if(!(f===v||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}}c.event.special.change={filters:{focusout:ea,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return ea.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return ea.call(this,a)},beforeactivate:function(a){a=
a.target;a.nodeName.toLowerCase()==="input"&&a.type==="radio"&&c.data(a,"_change_data",Ca(a))}},setup:function(a,b,d){for(var f in T)c.event.add(this,f+".specialChange."+d.guid,T[f]);return da.test(this.nodeName)},remove:function(a,b){for(var d in T)c.event.remove(this,d+".specialChange"+(b?"."+b.guid:""),T[d]);return da.test(this.nodeName)}};var T=c.event.special.change.filters}r.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,
f)}c.event.special[b]={setup:function(){this.addEventListener(a,d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var i in d)this[b](i,f,d[i],e);return this}if(c.isFunction(f)){e=f;f=v}var j=b==="one"?c.proxy(e,function(n){c(this).unbind(n,j);return e.apply(this,arguments)}):e;return d==="unload"&&b!=="one"?this.one(d,f,e):this.each(function(){c.event.add(this,d,j,f)})}});c.fn.extend({unbind:function(a,
b){if(typeof a==="object"&&!a.preventDefault){for(var d in a)this.unbind(d,a[d]);return this}return this.each(function(){c.event.remove(this,a,b)})},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}},toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+
a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e){var i,j=0;if(c.isFunction(f)){e=f;f=v}for(d=(d||"").split(/\s+/);(i=d[j++])!=null;){i=i==="focus"?"focusin":i==="blur"?"focusout":i==="hover"?d.push("mouseleave")&&"mouseenter":i;b==="live"?c(this.context).bind(oa(i,this.selector),{data:f,selector:this.selector,
live:i},e):c(this.context).unbind(oa(i,this.selector),e?{guid:e.guid+this.selector+i}:null)}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});z.attachEvent&&!z.addEventListener&&z.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});
(function(){function a(g){for(var h="",k,l=0;g[l];l++){k=g[l];if(k.nodeType===3||k.nodeType===4)h+=k.nodeValue;else if(k.nodeType!==8)h+=a(k.childNodes)}return h}function b(g,h,k,l,q,p){q=0;for(var u=l.length;q<u;q++){var t=l[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===k){y=l[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=k;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}l[q]=y}}}function d(g,h,k,l,q,p){q=0;for(var u=l.length;q<u;q++){var t=l[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===
k){y=l[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=k;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(o.filter(h,[t]).length>0){y=t;break}}t=t[g]}l[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,i=Object.prototype.toString,j=false,n=true;[0,0].sort(function(){n=false;return 0});var o=function(g,h,k,l){k=k||[];var q=h=h||r;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||
typeof g!=="string")return k;for(var p=[],u,t,y,R,H=true,M=w(h),I=g;(f.exec(""),u=f.exec(I))!==null;){I=u[3];p.push(u[1]);if(u[2]){R=u[3];break}}if(p.length>1&&s.exec(g))if(p.length===2&&m.relative[p[0]])t=fa(p[0]+p[1],h);else for(t=m.relative[p[0]]?[h]:o(p.shift(),h);p.length;){g=p.shift();if(m.relative[g])g+=p.shift();t=fa(g,t)}else{if(!l&&p.length>1&&h.nodeType===9&&!M&&m.match.ID.test(p[0])&&!m.match.ID.test(p[p.length-1])){u=o.find(p.shift(),h,M);h=u.expr?o.filter(u.expr,u.set)[0]:u.set[0]}if(h){u=
l?{expr:p.pop(),set:A(l)}:o.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=u.expr?o.filter(u.expr,u.set):u.set;if(p.length>0)y=A(t);else H=false;for(;p.length;){var D=p.pop();u=D;if(m.relative[D])u=p.pop();else D="";if(u==null)u=h;m.relative[D](y,u,M)}}else y=[]}y||(y=t);y||o.error(D||g);if(i.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))k.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&
y[g].nodeType===1&&k.push(t[g]);else k.push.apply(k,y);else A(y,k);if(R){o(R,q,k,l);o.uniqueSort(k)}return k};o.uniqueSort=function(g){if(C){j=n;g.sort(C);if(j)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};o.matches=function(g,h){return o(g,null,null,h)};o.find=function(g,h,k){var l,q;if(!g)return[];for(var p=0,u=m.order.length;p<u;p++){var t=m.order[p];if(q=m.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");l=m.find[t](q,
h,k);if(l!=null){g=g.replace(m.match[t],"");break}}}}l||(l=h.getElementsByTagName("*"));return{set:l,expr:g}};o.filter=function(g,h,k,l){for(var q=g,p=[],u=h,t,y,R=h&&h[0]&&w(h[0]);g&&h.length;){for(var H in m.filter)if((t=m.leftMatch[H].exec(g))!=null&&t[2]){var M=m.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length-1)!=="\\"){if(u===p)p=[];if(m.preFilter[H])if(t=m.preFilter[H](t,u,k,p,l,R)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=u[U])!=null;U++)if(D){I=M(D,t,U,u);var Da=
l^!!I;if(k&&I!=null)if(Da)y=true;else u[U]=false;else if(Da){p.push(D);y=true}}if(I!==v){k||(u=p);g=g.replace(m.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)o.error(g);else break;q=g}return u};o.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var m=o.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},relative:{"+":function(g,h){var k=typeof h==="string",l=k&&!/\W/.test(h);k=k&&!l;if(l)h=h.toLowerCase();l=0;for(var q=g.length,
p;l<q;l++)if(p=g[l]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[l]=k||p&&p.nodeName.toLowerCase()===h?p||false:p===h}k&&o.filter(h,g,true)},">":function(g,h){var k=typeof h==="string";if(k&&!/\W/.test(h)){h=h.toLowerCase();for(var l=0,q=g.length;l<q;l++){var p=g[l];if(p){k=p.parentNode;g[l]=k.nodeName.toLowerCase()===h?k:false}}}else{l=0;for(q=g.length;l<q;l++)if(p=g[l])g[l]=k?p.parentNode:p.parentNode===h;k&&o.filter(h,g,true)}},"":function(g,h,k){var l=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=
h=h.toLowerCase();q=b}q("parentNode",h,l,g,p,k)},"~":function(g,h,k){var l=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,l,g,p,k)}},find:{ID:function(g,h,k){if(typeof h.getElementById!=="undefined"&&!k)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var k=[];h=h.getElementsByName(g[1]);for(var l=0,q=h.length;l<q;l++)h[l].getAttribute("name")===g[1]&&k.push(h[l]);return k.length===0?null:k}},
TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,k,l,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var u;(u=h[p])!=null;p++)if(u)if(q^(u.className&&(" "+u.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))k||l.push(u);else if(k)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&
"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,k,l,q,p){h=g[1].replace(/\\/g,"");if(!p&&m.attrMap[h])g[1]=m.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,k,l,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=o(g[3],null,null,h);else{g=o.filter(g[3],h,k,true^q);k||l.push.apply(l,g);return false}else if(m.match.POS.test(g[0])||m.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);
return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,k){return!!o(k[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===
g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},setFilters:{first:function(g,h){return h===0},last:function(g,h,k,l){return h===l.length-1},even:function(g,h){return h%2===
0},odd:function(g,h){return h%2===1},lt:function(g,h,k){return h<k[3]-0},gt:function(g,h,k){return h>k[3]-0},nth:function(g,h,k){return k[3]-0===h},eq:function(g,h,k){return k[3]-0===h}},filter:{PSEUDO:function(g,h,k,l){var q=h[1],p=m.filters[q];if(p)return p(g,k,h,l);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h=h[3];k=0;for(l=h.length;k<l;k++)if(h[k]===g)return false;return true}else o.error("Syntax error, unrecognized expression: "+
q)},CHILD:function(g,h){var k=h[1],l=g;switch(k){case "only":case "first":for(;l=l.previousSibling;)if(l.nodeType===1)return false;if(k==="first")return true;l=g;case "last":for(;l=l.nextSibling;)if(l.nodeType===1)return false;return true;case "nth":k=h[2];var q=h[3];if(k===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var u=0;for(l=p.firstChild;l;l=l.nextSibling)if(l.nodeType===1)l.nodeIndex=++u;p.sizcache=h}g=g.nodeIndex-q;return k===0?g===0:g%k===0&&g/k>=
0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var k=h[1];g=m.attrHandle[k]?m.attrHandle[k](g):g[k]!=null?g[k]:g.getAttribute(k);k=g+"";var l=h[2];h=h[4];return g==null?l==="!=":l==="="?k===h:l==="*="?k.indexOf(h)>=0:l==="~="?(" "+k+" ").indexOf(h)>=0:!h?k&&g!==false:l==="!="?k!==h:l==="^="?
k.indexOf(h)===0:l==="$="?k.substr(k.length-h.length)===h:l==="|="?k===h||k.substr(0,h.length+1)===h+"-":false},POS:function(g,h,k,l){var q=m.setFilters[h[2]];if(q)return q(g,k,h,l)}}},s=m.match.POS;for(var x in m.match){m.match[x]=new RegExp(m.match[x].source+/(?![^\[]*\])(?![^\(]*\))/.source);m.leftMatch[x]=new RegExp(/(^(?:.|\r|\n)*?)/.source+m.match[x].source.replace(/\\(\d+)/g,function(g,h){return"\\"+(h-0+1)}))}var A=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};
try{Array.prototype.slice.call(r.documentElement.childNodes,0)}catch(B){A=function(g,h){h=h||[];if(i.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var k=0,l=g.length;k<l;k++)h.push(g[k]);else for(k=0;g[k];k++)h.push(g[k]);return h}}var C;if(r.documentElement.compareDocumentPosition)C=function(g,h){if(!g.compareDocumentPosition||!h.compareDocumentPosition){if(g==h)j=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===
h?0:1;if(g===0)j=true;return g};else if("sourceIndex"in r.documentElement)C=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)j=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)j=true;return g};else if(r.createRange)C=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)j=true;return g.ownerDocument?-1:1}var k=g.ownerDocument.createRange(),l=h.ownerDocument.createRange();k.setStart(g,0);k.setEnd(g,0);l.setStart(h,0);l.setEnd(h,0);g=k.compareBoundaryPoints(Range.START_TO_END,
l);if(g===0)j=true;return g};(function(){var g=r.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var k=r.documentElement;k.insertBefore(g,k.firstChild);if(r.getElementById(h)){m.find.ID=function(l,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(l[1]))?q.id===l[1]||typeof q.getAttributeNode!=="undefined"&&q.getAttributeNode("id").nodeValue===l[1]?[q]:v:[]};m.filter.ID=function(l,q){var p=typeof l.getAttributeNode!=="undefined"&&l.getAttributeNode("id");
return l.nodeType===1&&p&&p.nodeValue===q}}k.removeChild(g);k=g=null})();(function(){var g=r.createElement("div");g.appendChild(r.createComment(""));if(g.getElementsByTagName("*").length>0)m.find.TAG=function(h,k){k=k.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var l=0;k[l];l++)k[l].nodeType===1&&h.push(k[l]);k=h}return k};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")m.attrHandle.href=function(h){return h.getAttribute("href",
2)};g=null})();r.querySelectorAll&&function(){var g=o,h=r.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){o=function(l,q,p,u){q=q||r;if(!u&&q.nodeType===9&&!w(q))try{return A(q.querySelectorAll(l),p)}catch(t){}return g(l,q,p,u)};for(var k in g)o[k]=g[k];h=null}}();(function(){var g=r.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===
0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){m.order.splice(1,0,"CLASS");m.find.CLASS=function(h,k,l){if(typeof k.getElementsByClassName!=="undefined"&&!l)return k.getElementsByClassName(h[1])};g=null}}})();var E=r.compareDocumentPosition?function(g,h){return g.compareDocumentPosition(h)&16}:function(g,h){return g!==h&&(g.contains?g.contains(h):true)},w=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},fa=function(g,h){var k=[],
l="",q;for(h=h.nodeType?[h]:h;q=m.match.PSEUDO.exec(g);){l+=q[0];g=g.replace(m.match.PSEUDO,"")}g=m.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)o(g,h[q],k);return o.filter(l,k)};c.find=o;c.expr=o.selectors;c.expr[":"]=c.expr.filters;c.unique=o.uniqueSort;c.getText=a;c.isXMLDoc=w;c.contains=E})();var bb=/Until$/,cb=/^(?:parents|prevUntil|prevAll)/,db=/,/;Q=Array.prototype.slice;var Ea=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,i){return!!b.call(e,i,e)===d});else if(b.nodeType)return c.grep(a,
function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Qa.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length;c.find(a,this[f],b);if(f>0)for(var i=d;i<b.length;i++)for(var j=0;j<d;j++)if(b[j]===b[i]){b.splice(i--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=
0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ea(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ea(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,i={},j;if(f&&a.length){e=0;for(var n=a.length;e<n;e++){j=a[e];i[j]||(i[j]=c.expr.match.POS.test(j)?c(j,b||this.context):j)}for(;f&&f.ownerDocument&&f!==b;){for(j in i){e=i[j];if(e.jquery?e.index(f)>
-1:c(f).is(e)){d.push({selector:j,elem:f});delete i[j]}}f=f.parentNode}}return d}var o=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(m,s){for(;s&&s.ownerDocument&&s!==b;){if(o?o.index(s)>-1:c(s).is(a))return s;s=s.parentNode}return null})},index:function(a){if(!a||typeof a==="string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),
a);return this.pushStack(pa(a[0])||pa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},
nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);bb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):
e;if((this.length>1||db.test(f))&&cb.test(a))e=e.reverse();return this.pushStack(e,a,Q.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===v||a.nodeType!==1||!c(a).is(d));){a.nodeType===1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==
b&&d.push(a);return d}});var Fa=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ga=/(<([\w:]+)[^>]*?)\/>/g,eb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,Ha=/<([\w:]+)/,fb=/<tbody/i,gb=/<|&\w+;/,sa=/checked\s*(?:[^=]|=\s*.checked.)/i,Ia=function(a,b,d){return eb.test(d)?a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],
col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==v)return this.empty().append((this[0]&&this[0].ownerDocument||r).createTextNode(a));return c.getText(this)},
wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?
d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,
false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&
!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Fa,"").replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){qa(this,b);qa(this.find("*"),b.find("*"))}return b},html:function(a){if(a===v)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Fa,""):null;else if(typeof a==="string"&&!/<script/i.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(Ha.exec(a)||
["",""])[1].toLowerCase()]){a=a.replace(Ga,Ia);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var i=c(this),j=i.html();i.empty().append(function(){return a.call(this,e,j)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,
b,f))});else a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(s){return c.nodeName(s,"table")?s.getElementsByTagName("tbody")[0]||s.appendChild(s.ownerDocument.createElement("tbody")):s}var e,i,j=a[0],n=[];if(!c.support.checkClone&&arguments.length===3&&typeof j===
"string"&&sa.test(j))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(j))return this.each(function(s){var x=c(this);a[0]=j.call(this,s,b?x.html():v);x.domManip(a,b,d)});if(this[0]){e=a[0]&&a[0].parentNode&&a[0].parentNode.nodeType===11?{fragment:a[0].parentNode}:ra(a,this,n);if(i=e.fragment.firstChild){b=b&&c.nodeName(i,"tr");for(var o=0,m=this.length;o<m;o++)d.call(b?f(this[o],i):this[o],e.cacheable||this.length>1||o>0?e.fragment.cloneNode(true):e.fragment)}n&&c.each(n,
Ma)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);for(var e=0,i=d.length;e<i;e++){var j=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),j);f=f.concat(j)}return this.pushStack(f,a,d.selector)}});c.each({remove:function(a,b){if(!a||c.filter(a,[this]).length){if(!b&&this.nodeType===1){c.cleanData(this.getElementsByTagName("*"));c.cleanData([this])}this.parentNode&&
this.parentNode.removeChild(this)}},empty:function(){for(this.nodeType===1&&c.cleanData(this.getElementsByTagName("*"));this.firstChild;)this.removeChild(this.firstChild)}},function(a,b){c.fn[a]=function(){return this.each(b,arguments)}});c.extend({clean:function(a,b,d,f){b=b||r;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||r;var e=[];c.each(a,function(i,j){if(typeof j==="number")j+="";if(j){if(typeof j==="string"&&!gb.test(j))j=b.createTextNode(j);else if(typeof j===
"string"){j=j.replace(Ga,Ia);var n=(Ha.exec(j)||["",""])[1].toLowerCase(),o=F[n]||F._default,m=o[0];i=b.createElement("div");for(i.innerHTML=o[1]+j+o[2];m--;)i=i.lastChild;if(!c.support.tbody){m=fb.test(j);n=n==="table"&&!m?i.firstChild&&i.firstChild.childNodes:o[1]==="<table>"&&!m?i.childNodes:[];for(o=n.length-1;o>=0;--o)c.nodeName(n[o],"tbody")&&!n[o].childNodes.length&&n[o].parentNode.removeChild(n[o])}!c.support.leadingWhitespace&&V.test(j)&&i.insertBefore(b.createTextNode(V.exec(j)[0]),i.firstChild);
j=c.makeArray(i.childNodes)}if(j.nodeType)e.push(j);else e=c.merge(e,j)}});if(d)for(a=0;e[a];a++)if(f&&c.nodeName(e[a],"script")&&(!e[a].type||e[a].type.toLowerCase()==="text/javascript"))f.push(e[a].parentNode?e[a].parentNode.removeChild(e[a]):e[a]);else{e[a].nodeType===1&&e.splice.apply(e,[a+1,0].concat(c.makeArray(e[a].getElementsByTagName("script"))));d.appendChild(e[a])}return e},cleanData:function(a){for(var b=0,d;(d=a[b])!=null;b++){c.event.remove(d);c.removeData(d)}}});var hb=/z-?index|font-?weight|opacity|zoom|line-?height/i,
Ja=/alpha\([^)]*\)/,Ka=/opacity=([^)]*)/,ga=/float/i,ha=/-([a-z])/ig,ib=/([A-Z])/g,jb=/^-?\d+(?:px)?$/i,kb=/^-?\d/,lb={position:"absolute",visibility:"hidden",display:"block"},mb=["Left","Right"],nb=["Top","Bottom"],ob=r.defaultView&&r.defaultView.getComputedStyle,La=c.support.cssFloat?"cssFloat":"styleFloat",ia=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===v)return c.curCSS(d,f);if(typeof e==="number"&&!hb.test(f))e+="px";c.style(d,f,e)})};
c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return v;if((b==="width"||b==="height")&&parseFloat(d)<0)d=v;var f=a.style||a,e=d!==v;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter=Ja.test(a)?a.replace(Ja,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Ka.exec(f.filter)[1])/100+"":""}if(ga.test(b))b=La;b=b.replace(ha,ia);if(e)f[b]=d;return f[b]},css:function(a,
b,d,f){if(b==="width"||b==="height"){var e,i=b==="width"?mb:nb;function j(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(i,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a,"border"+this+"Width",true))||0})}a.offsetWidth!==0?j():c.swap(a,lb,j);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&
a.currentStyle){f=Ka.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ga.test(b))b=La;if(!d&&e&&e[b])f=e[b];else if(ob){if(ga.test(b))b="float";b=b.replace(ib,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f=a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ha,ia);f=a.currentStyle[b]||a.currentStyle[d];if(!jb.test(f)&&kb.test(f)){b=e.left;var i=a.runtimeStyle.left;a.runtimeStyle.left=
a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=i}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var pb=
J(),qb=/<script(.|\s)*?\/script>/gi,rb=/select|textarea/i,sb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ja=/\?/,tb=/(\?|&)_=.*?(&|$)/,ub=/^(\w+:)?\/\/([^\/?#]+)/,vb=/%20/g;c.fn.extend({_load:c.fn.load,load:function(a,b,d){if(typeof a!=="string")return this._load(a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=
c.param(b,c.ajaxSettings.traditional);f="POST"}var i=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(j,n){if(n==="success"||n==="notmodified")i.html(e?c("<div />").append(j.responseText.replace(qb,"")).find(e):j.responseText);d&&i.each(d,[j.responseText,n,j])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&
(this.checked||rb.test(this.nodeName)||sb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,
b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:z.XMLHttpRequest&&(z.location.protocol!=="file:"||!z.ActiveXObject)?function(){return new z.XMLHttpRequest}:
function(){try{return new z.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&&e.success.call(o,n,j,w);e.global&&f("ajaxSuccess",[w,e])}function d(){e.complete&&e.complete.call(o,w,j);e.global&&f("ajaxComplete",[w,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}
function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),i,j,n,o=a&&a.context||e,m=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(m==="GET")N.test(e.url)||(e.url+=(ja.test(e.url)?"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||
N.test(e.url))){i=e.jsonpCallback||"jsonp"+pb++;if(e.data)e.data=(e.data+"").replace(N,"="+i+"$1");e.url=e.url.replace(N,"="+i+"$1");e.dataType="script";z[i]=z[i]||function(q){n=q;b();d();z[i]=v;try{delete z[i]}catch(p){}A&&A.removeChild(B)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===false&&m==="GET"){var s=J(),x=e.url.replace(tb,"$1_="+s+"$2");e.url=x+(x===e.url?(ja.test(e.url)?"&":"?")+"_="+s:"")}if(e.data&&m==="GET")e.url+=(ja.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&
c.event.trigger("ajaxStart");s=(s=ub.exec(e.url))&&(s[1]&&s[1]!==location.protocol||s[2]!==location.host);if(e.dataType==="script"&&m==="GET"&&s){var A=r.getElementsByTagName("head")[0]||r.documentElement,B=r.createElement("script");B.src=e.url;if(e.scriptCharset)B.charset=e.scriptCharset;if(!i){var C=false;B.onload=B.onreadystatechange=function(){if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){C=true;b();d();B.onload=B.onreadystatechange=null;A&&B.parentNode&&
A.removeChild(B)}}}A.insertBefore(B,A.firstChild);return v}var E=false,w=e.xhr();if(w){e.username?w.open(m,e.url,e.async,e.username,e.password):w.open(m,e.url,e.async);try{if(e.data||a&&a.contentType)w.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[e.url]);c.etag[e.url]&&w.setRequestHeader("If-None-Match",c.etag[e.url])}s||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept",
e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(fa){}if(e.beforeSend&&e.beforeSend.call(o,w,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");w.abort();return false}e.global&&f("ajaxSend",[w,e]);var g=w.onreadystatechange=function(q){if(!w||w.readyState===0||q==="abort"){E||d();E=true;if(w)w.onreadystatechange=c.noop}else if(!E&&w&&(w.readyState===4||q==="timeout")){E=true;w.onreadystatechange=c.noop;j=q==="timeout"?"timeout":!c.httpSuccess(w)?
"error":e.ifModified&&c.httpNotModified(w,e.url)?"notmodified":"success";var p;if(j==="success")try{n=c.httpData(w,e.dataType,e)}catch(u){j="parsererror";p=u}if(j==="success"||j==="notmodified")i||b();else c.handleError(e,w,j,p);d();q==="timeout"&&w.abort();if(e.async)w=null}};try{var h=w.abort;w.abort=function(){w&&h.call(w);g("abort")}}catch(k){}e.async&&e.timeout>0&&setTimeout(function(){w&&!E&&g("timeout")},e.timeout);try{w.send(m==="POST"||m==="PUT"||m==="DELETE"?e.data:null)}catch(l){c.handleError(e,
w,null,l);d()}e.async||g();return w}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=
f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(j,n){if(c.isArray(n))c.each(n,
function(o,m){b?f(j,m):d(j+"["+(typeof m==="object"||c.isArray(m)?o:"")+"]",m)});else!b&&n!=null&&typeof n==="object"?c.each(n,function(o,m){d(j+"["+o+"]",m)}):f(j,n)}function f(j,n){n=c.isFunction(n)?n():n;e[e.length]=encodeURIComponent(j)+"="+encodeURIComponent(n)}var e=[];if(b===v)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var i in a)d(i,a[i]);return e.join("&").replace(vb,"+")}});var ka={},wb=/toggle|show|hide/,xb=/^([+-]=)?([\d+-.]+)(.*)$/,
W,ta=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(ka[d])f=ka[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();
ka[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a],"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&
c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)},animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var i=c.extend({},e),j,n=this.nodeType===1&&c(this).is(":hidden"),
o=this;for(j in a){var m=j.replace(ha,ia);if(j!==m){a[m]=a[j];delete a[j];j=m}if(a[j]==="hide"&&n||a[j]==="show"&&!n)return i.complete.call(this);if((j==="height"||j==="width")&&this.style){i.display=c.css(this,"display");i.overflow=this.style.overflow}if(c.isArray(a[j])){(i.specialEasing=i.specialEasing||{})[j]=a[j][1];a[j]=a[j][0]}}if(i.overflow!=null)this.style.overflow="hidden";i.curAnim=c.extend({},a);c.each(a,function(s,x){var A=new c.fx(o,i,s);if(wb.test(x))A[x==="toggle"?n?"show":"hide":x](a);
else{var B=xb.exec(x),C=A.cur(true)||0;if(B){x=parseFloat(B[2]);var E=B[3]||"px";if(E!=="px"){o.style[s]=(x||1)+E;C=(x||1)/A.cur(true)*C;o.style[s]=C+E}if(B[1])x=(B[1]==="-="?-1:1)*x+C;A.custom(C,x,E)}else A.custom(C,x,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",
1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration==="number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,
b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==
null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(i){return e.step(i)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop===
"width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=
this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem,e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=
c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=
null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in r.documentElement?function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),
f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(a)return this.each(function(s){c.offset.setOffset(this,a,s)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=
b,e=b.ownerDocument,i,j=e.documentElement,n=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var o=b.offsetTop,m=b.offsetLeft;(b=b.parentNode)&&b!==n&&b!==j;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;i=e?e.getComputedStyle(b,null):b.currentStyle;o-=b.scrollTop;m-=b.scrollLeft;if(b===d){o+=b.offsetTop;m+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){o+=parseFloat(i.borderTopWidth)||
0;m+=parseFloat(i.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&i.overflow!=="visible"){o+=parseFloat(i.borderTopWidth)||0;m+=parseFloat(i.borderLeftWidth)||0}f=i}if(f.position==="relative"||f.position==="static"){o+=n.offsetTop;m+=n.offsetLeft}if(c.offset.supportsFixedPosition&&f.position==="fixed"){o+=Math.max(j.scrollTop,n.scrollTop);m+=Math.max(j.scrollLeft,n.scrollLeft)}return{top:o,left:m}};c.offset={initialize:function(){var a=r.body,b=r.createElement("div"),
d,f,e,i=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.insertBefore(b,a.firstChild);
d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i;a.removeChild(b);c.offset.initialize=c.noop},
bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),i=parseInt(c.curCSS(a,"top",true),10)||0,j=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,d,e);d={top:b.top-e.top+i,left:b.left-
e.left+j};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=
this.offsetParent||r.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],i;if(!e)return null;if(f!==v)return this.each(function(){if(i=ua(this))i.scrollTo(!a?f:c(i).scrollLeft(),a?f:c(i).scrollTop());else this[d]=f});else return(i=ua(e))?"pageXOffset"in i?i[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&i.document.documentElement[d]||i.document.body[d]:e[d]}});
c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(i){var j=c(this);j[d](f.call(this,i,j[d]()))});return"scrollTo"in e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||
e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===v?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});z.jQuery=z.$=c})(window);
$(".actions-hover").append($('<li style="margin-left:5px"><span class="classicrt_icon">♲ </span><a href="#" class="classicrt"> Classic RT</a></li>'));
$(".classicrt").mouseover(function (e) {
$(this).siblings(".classicrt_icon").text("♻ ");
});
$(".classicrt").mouseout(function (e) {
$(this).siblings(".classicrt_icon").text("♲ ");
});
$(".classicrt").click( function(e) {
var tweeter = $(this).parents(".status-body").children().children(":first").text();
var tweet = $(this).parents(".status-body").children().children(".entry-content").text();
tweet.substr(1, tweet.length -1); // strip ""
$("#status").attr("value", "RT @"+tweeter+" "+tweet);
});
|
Java
|
# Shamelessly stolen from http://github.com/masak/yapsi/blob/master/Makefile
# With alpha replaced with perl6 & SOURCES changed to my sources.
PERL6 = perl6
SOURCES=lib/SIC/AST.pm lib/SIC/Grammar.pm \
lib/SIC/Actions.pm lib/SIC/Compiler.pm
PIRS=$(SOURCES:.pm=.pir)
all: $(PIRS)
%.pir: %.pm
env PERL6LIB=`pwd`/lib $(PERL6) --target=pir --output=$@ $<
clean:
rm -f $(PIRS)
test: all
env PERL6LIB=`pwd`/lib prove -e '$(PERL6)' -r --nocolor t/
|
Java
|
# GitURL
GitURL represents something that can be passed to `git clone`.
## clone
>method clone([Str](./Str.md) **:$to** ⟶ [File](./File.md))
Calls `git clone` on the the url and returns the path to the cloned directory.
```perl6
GitURL<https://github.com/spitsh/spitsh.git/>.clone.cd;
say ${ $*git status };
```
|Parameter|Description|
|---------|-----------|
|**:$to**| Path to clone the repo to|
## name
>method name( ⟶ [Str](./Str.md))
Gets the last section of the url without its extension. This is the same as directory name git will use to clone into by default.
```perl6
say GitURL<https://github.com/nodejs/node.git>.name #->node
```
|
Java
|
// (c) Jean Fabre, 2011-2013 All rights reserved.
// http://www.fabrejean.net
// contact: http://www.fabrejean.net/contact.htm
//
// Version Alpha 0.92
// INSTRUCTIONS
// Drop a PlayMakerArrayList script onto a GameObject, and define a unique name for reference if several PlayMakerArrayList coexists on that GameObject.
// In this Action interface, link that GameObject in "arrayListObject" and input the reference name if defined.
// Note: You can directly reference that GameObject or store it in an Fsm variable or global Fsm variable
using UnityEngine;
namespace HutongGames.PlayMaker.Actions
{
[ActionCategory("ArrayMaker/ArrayList")]
[Tooltip("Set an item at a specified index to a PlayMaker array List component")]
public class ArrayListSet : ArrayListActions
{
[ActionSection("Set up")]
[RequiredField]
[Tooltip("The gameObject with the PlayMaker ArrayList Proxy component")]
[CheckForComponent(typeof(PlayMakerArrayListProxy))]
public FsmOwnerDefault gameObject;
[Tooltip("Author defined Reference of the PlayMaker ArrayList Proxy component (necessary if several component coexists on the same GameObject)")]
[UIHint(UIHint.FsmString)]
public FsmString reference;
[Tooltip("The index of the Data in the ArrayList")]
[UIHint(UIHint.FsmString)]
public FsmInt atIndex;
public bool everyFrame;
[ActionSection("Data")]
[Tooltip("The variable to add.")]
public FsmVar variable;
public override void Reset()
{
gameObject = null;
reference = null;
variable = null;
everyFrame = false;
}
public override void OnEnter()
{
if ( SetUpArrayListProxyPointer(Fsm.GetOwnerDefaultTarget(gameObject),reference.Value) )
SetToArrayList();
if (!everyFrame){
Finish();
}
}
public override void OnUpdate()
{
SetToArrayList();
}
public void SetToArrayList()
{
if (! isProxyValid() ) return;
proxy.Set(atIndex.Value,PlayMakerUtils.GetValueFromFsmVar(Fsm,variable),variable.Type.ToString());
}
}
}
|
Java
|
#!/bin/sh
#------------------------------------------------------------------------------
#
# MyRPM - Rpm Utilities
# Copyright (c) Jean-Marie RENOUARD 2014 - LightPath
# Contact : Jean-Marie Renouard <jmrenouard at gmail.com>
#
# This program is open source, licensed under the Artistic Licence v2.0.
#
# Artistic Licence 2.0
# Everyone is permitted to copy and distribute verbatim copies of
# this license document, but changing it is not allowed.
#
#------------------------------------------------------------------------------
TMP_DIR=/tmp
MD5_SUM=$(echo "$1_$2" | md5sum | cut -d' ' -f 1)
TMP_FILE="$TMP_DIR/$MD5_SUM.dat"
if [ -e "$TMP_FILE" ]; then
DATE_TMP_FILE=$(stat -c '%Y' $TMP_FILE)
DATE=$(date +%s)
DIFF_DATE=$(echo "$DATE-$DATE_TMP_FILE"|bc)
if [ "$DIFF_DATE" -lt "200" ]; then
echo "$2:`cat $TMP_FILE`"
exit 0
fi
fi
#Recherche de la derniere version d'un repertoire
echo_last_installed_version() {
echo `ls -1tr -d $1/* | grep $2 | tail -n 1`
}
JAVA="$JAVA_HOME/bin/java JmxClient"
HOST="localhost"
PORT="7091"
ATTR="$2"
ATTR=`echo $2 | cut -d. -f1`
ELT=`echo $2 | cut -d. -f2`
result=`$JAVA $HOST $PORT $1 $ATTR`
if [ "$ATTR" != "$ELT" ]; then
result=`echo $result| cut -d{ -f2 | sed -e 's/})//' -e 's/ //g' -e 's/,/\n/g'| grep $ELT | cut -d= -f2`
fi
echo "$result" > $TMP_FILE
echo "$2:$result"
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_292) on Fri Jul 02 03:47:37 UTC 2021 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.destroystokyo.paper (Glowkit 1.12.2-R6.0-SNAPSHOT API)</title>
<meta name="date" content="2021-07-02">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="com.destroystokyo.paper (Glowkit 1.12.2-R6.0-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../co/aikar/util/package-summary.html">Prev Package</a></li>
<li><a href="../../../com/destroystokyo/paper/entity/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?com/destroystokyo/paper/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package com.destroystokyo.paper</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../com/destroystokyo/paper/ParticleBuilder.html" title="class in com.destroystokyo.paper">ParticleBuilder</a></td>
<td class="colLast">
<div class="block">Helps prepare a particle to be sent to players.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../com/destroystokyo/paper/Title.html" title="class in com.destroystokyo.paper">Title</a></td>
<td class="colLast">
<div class="block">Represents a title to may be sent to a <a href="../../../org/bukkit/entity/Player.html" title="interface in org.bukkit.entity"><code>Player</code></a>.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../com/destroystokyo/paper/Title.Builder.html" title="class in com.destroystokyo.paper">Title.Builder</a></td>
<td class="colLast">
<div class="block">A builder for creating titles</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Summary table, listing enums, and an explanation">
<caption><span>Enum Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Enum</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../com/destroystokyo/paper/VersionHistoryManager.html" title="enum in com.destroystokyo.paper">VersionHistoryManager</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../co/aikar/util/package-summary.html">Prev Package</a></li>
<li><a href="../../../com/destroystokyo/paper/entity/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?com/destroystokyo/paper/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2021. All rights reserved.</small></p>
</body>
</html>
|
Java
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Transforms</title>
<style>
#threed-example {
margin: 50px 20px;
-webkit-transform: rotateZ(5deg);
-moz-transform: rotateZ(5deg);
-o-transform: rotateZ(5deg);
transform: rotateZ(5deg);
-webkit-transition: -webkit-transform 2s ease-in-out;
-moz-transition: -moz-transform 2s ease-in-out;
-o-transition: -o-transform 2s ease-in-out;
transition: transform 2s ease-in-out;
}
#threed-example:hover {
-webkit-transform: rotateZ(-5deg);
-moz-transform: rotateZ(-5deg);
-o-transform: rotateZ(-5deg);
transform: rotateZ(-5deg);
}
</style>
</head>
<body>
<div class="slide styling" id="css-transforms">
<header><span class="css">CSS</span> <h1>Transforms</h1></header>
<section>
<p class="center">
Hover over me:
</p>
<pre id="threed-example">-webkit-<b>transform</b>: <b>rotateY</b>(45deg);
-webkit-transform: <b>scaleX</b>(25deg);
-webkit-transform: <b>translate3d</b>(0, 0, 90deg);
-webkit-transform: <b>perspective</b>(500px)
</pre>
<pre>#threed-example {
-webkit-transform: rotateZ(5deg);
-webkit-transition: -webkit-transform 2s ease-in-out;
}
#threed-example:hover {
-webkit-transform: rotateZ(-5deg);
}
</pre>
<p class="center">
Now press <span class="key">3</span>!
</p>
</section>
</div>
</body>
</html>
|
Java
|
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>De Mulierum Subtili Deceptione</title>
</head>
<body>
<!--XXVII De Mulierum Subtili Deceptione-->
<h4>The Subtle Deciption of a Woman</h4>
<p>
<!--
Darius regnavit prudens valde, qui tres filios habuit quos
multum dilexit. Cum vero mori deberet totam hereditatem
primogenito legavit; secundo filio dedit omnia quae in
tempore suo acquisivit; tertio filio, scilicet minori,
tria iocalia pretiosa dedit, scilicet anulum aureum,
monile et pannum pretiosum. Anulus illam virtutem habuit
quod qui ipsum in digito gestabat gratiam omnium habuit,
in tantum quod, quicquid ab eis peteret, obtineret; monile
illam virtutem habuit quod qui eum in pectore portabat,
quicquid cor suum desiderabat quod possibile esset,
obtineret. Pannus illam virtutem habuit quod, quicumque
super eum sederet et intra se cogitaret ubicumque esse
vellet, subito ibi esset.
-->
Once upon a time Darius reigned. He was highly learned,
and loved his three sons intensely. Indeed, when he was
about to die he bequeathed his entire inheritance to the
first-born; to the second he gave everything that he had
acquired in his lifetime; and to the third, the youngest
of course, he gave three costly possesions - a gold ring,
a necklace and a costly rug. The ring had the virtue
that whoever wore it on their finger had the goodwill of
all men, so much so, that whatsoever they might ask of
them, they would gain; the necklace had the virtue that
whoever carried it on their breast, whatever their heart
desired that might be possible, they would gain. The rug
had the virtue that, whoever might sit upon it and think
to themselves wherever they wished to be, they would
suddenly be there.
<!--
Ista tria iocalia dedit filio suo iuniori ut ad studium
pergeret et mater ea custodiret et tempore opportuno ei
daret; statimque rex spiritum emisit, qui honorifice
est sepultus. Duo primi filii eius legata occupabant,
tertius filius anulum a matre recepit ut ad studium
pergeret; cui mater dixit: "Fili, scientiam acquire et a
muliere caveas ne forte anulum perdas." Ionathas anulum
accepit, ad studium accessit et in scientia profecit.
-->
He gave these three possessions to his youngest son so
that he could proceed with his studies and that his
mother should watch over them and give them to him at an
opportune time; and at once the king gave up the ghost,
and was honorably buried. His first two sons seized
their legacies, while the third son recieved the ring
from his mother so that he might continue with his
studies. And his mother said to him: "Son, gain
learning, and may you avoid a woman, and not by chance
lose the ring." Jonathan accepted the ring, undertook
his studies and became accomplished in learning.
</p>
<p>
<!--
Post hoc cito quadam die in platea ei quaedam puella
occurrebat satis formosa et, captus eius amore, eam secum
duxit; continuo anulo utebatur et gratiam omnium habuit et
quicquid ab eis voluit habere obtinuit. Puella eius
concubina mirabatur quod tam laute viveret cum tamen
pecuniam non haberet; rationem quadam vice, cum laetus
esset, quaesivit, dicens quod creatura* sub caelo non
esset quam magis diligeret; ideo sibi dicere
deberet. Ille, de malitia non praemeditatus sibi, dixit
virtutem anuli esse talem, etc.
-->
Soon after this there came a day that he met a young
woman in the high street. She was pretty enough and,
seized with love, he led her away with him. He constantly
made use of the ring and had all goodwill and whatsoever
he wished to have of them he gained. The young woman,
now his concubine, marvelled that he lived so sumptuously
when he didn't have any money; and one day, when he was
in a good mood, she asked how it was, saying that there
was no creature under heaven who loved him more; and
therefore he should tell her. He, not considering malice
towards himself, told her that virtue of the ring was
such, etc.
<!--
At illa: "Cum singulis diebus cum hominibus conversare
soles, perdere posses; ideo custodiam tibi eum fideliter."
Qui tradidit ei anulum, sed cum repeteret, penuria ductus,
illa alta voce clamavit quod fures abstulissent; qui motus
flevit amare, quia unde viveret non habuit. Qui statim
ad reginam, matrem suam, est reversus denuntians ei anulum
perditum. At illa: "Fili mi, tibi praedixi ut a muliere te
caveres; ecce tibi iam trado monile quod diligentius
custodias; si perdideris, honore et commodo perpetuo
carebis." Ionathas monile recepit et ad idem studium est
reversus, et ecce concubina eius in porta civitatis
occurrit et cum gaudio eum recepit; ille, ut prius,
convivia multa habuit et laute vixit.
-->
But she said: "You are wont to keep company with men
every day, you might lose it; therefore I will faithfully
guard it for you." And he handed over the ring, but when
he returned, led by want, she cried out in a loud voice
that theives had carried it off; and he was agitated and
wept bitterly, for he didn't have the wherewithall to
live on. And he returned at once to his mother the queen,
and announced the loss of the ring to her. But she said:
"My son, I warned you to beware a woman. Look, I am now
handing over to you the necklace that you must guard
carefully; if you were to lose it, then you will lose
honor and profit forever." Jonathan accepted the
necklace and returned to his studies, and lo his
concubine met him at the gate of the city and received
him joyfully; and he, as before, had great banquets and
lived sumptuously.
</p>
<p>
<!--
Concubina mirabatur quia nec aurum nec argentum videbat, et
cogitabat quod aliud iocale apportasset, quod sagaciter ab
eo indagavit; qui ei monile ostendit et virtutem eius dixit.
Quae ait: "Semper monile tecum portas; una hora tantum
cogitare posses quod per annum sufficeret tibi; ideo trade
mihi ad custodiendum."
-->
The concubine marveled, for she saw neither gold nor silver, and
reflected that he had brought another possession, which she
shrewdly dug out from him; and he showed her the necklace and
told her of its virtue. And she said: "You always carry the
necklace with you; a single hour is enough for you to imagine
what would suffice you for a year; therefore hand it over to me
for safekeeping."
<!--
At ille: "Timeo quod sicut anulum perdidisti sic perderes monile
et sic damnum maximum incurrerem."
-->
But he said: "I'm afraid that, just as you lost the ring, so
might you lose the necklace, and so I would incur a very great
loss."
<!--
Quae ait: "O domine, iam per anulum scientiam acquisivi; unde
tibi fideliter promitto quod sic custodiam monile quod nullus
posset a me auferre."
-->
And she said: "O lord, I have already gotten experience from
the ring; from which I faithfully promise you that I will guard
the ring so well that no one could carry it away from me."
<!--
Ille credens dictis eius, monile ei tradidit. Postquam omnia
consumpta fuissent monile petiit; ilia, sicut prius, iuravit quod
furtive ablatum esset. Quod audiens Ionathas flevit amare et ait:
"Nonne sensum perdidi quod post anulum perditum monile tibi
tradidi!"
-->
Believing in her words, he handed the necklace over to her.
After everything had been used up he asked for the necklace;
but she, as before, swore that it had been furtively stolen
away. On hearing this Jonathan wept bitterly and said: "Surely
I have not lost the thought that, after losing the ring, I gave
you the necklace!"
</p>
<p>
<!--
Perrexit ad matrem et ei totum processum nuntiavit; illa non
modicum dolens dixit: "O fili carissime, quare spem posuisti in
muliere? Iam altera vice deceptus es per eam et ab omnibus ut
stultus reputaris; ammodo sapientiam addiscas quia nihil habeo
tibi nisi pannum pretiosum quem pater tuus tibi dedit, et si
illum perdideris, ad me amplius redire non valeas."
-->
He proceeded to his mother and reported to her the entire course
of events. She, grieving not a little, said: "O my dearest son,
why have you put your hope in a women? You have already been
cheated in another exchange with her and are thought to be
foolish by everyone; henceforth you should learn wisdom, for I
have nothing else for you except the costly length of cloth that
your father gave you, and if you lose that, it will not avail
you to come back to me."
<!--
Ille pannum recepit et ad studium perrexit et concubina eius, ut
prius, gaudenter eum recepit. Qui expandens pannum dixit:
"Carissima, istum pannum dedit mihi pater meus," et ambo
posuerunt se super pannum.
-->
He accepted this length of cloth and went on to his studies and
his concubine, as before, received him with joy. And he,
spreading out the cloth, said: "Dearest love, my father gave me
this cloth," and they both sat down upon the cloth.
<!--
Ionathas intra se cogitabat: "Utinam essemus in tantam
distantiam ubi nullus hominum ante venit!" Et sic factum
est; fuerunt enim in fine mundi in una foresta quae multum
distabat ab hominibus. Illa tristabatur et Ionathas votum
vovit Deo caeli quod dimitteret eam bestiis ad devorandum
donec redderet anulum et monile; quae promisit facere si
posset, et ad petitionem concubinae Ionathas virtutem panni
dixit, scilicet, quicumque super eo quiesceret et cogitaret ubi
esse vellet, ibi statim esset.
-->
Jonathan thought to himself: "If only we were so far away
that no man had been there before!" And so it happened; for
they were at the end of the world in a forest which was far away
from men. She was grieved, and Jonathan made a vow to God in heaven
that he would leave her to be devoured by wild animals unless
she restored the ring and the necklace. She promised to do this
if she could, and Jonathan spoke of the virtue of the cloth,
namely, that whoever sat on it and thought where they wished to
go, there they were at once.
<!--
Deinde ipsa se super pannum posuit et caput eius in gremio suo
collocavit et, cum dormire coepisset, ipsa partem panni supra quam
sedebat ad se traxit. At illa cogitabat: "Utinam essem in loco ubi
mane fui!" Quod et factum est, et Ionathas dormiens in foresta
mansit.
-->
Then she positioned herself on the cloth and placed his head on her
lap and, when he had fallen asleep, drew the part of the cloth on
which he was lying towards her. But then she thought: "If only I
were in the place where I was this morning!" And this was
accomplished, and Jonathan remained asleep in the forest.
</p>
<p>
<!--
Cum autem de somno surrexisset et pannum ablatum cum concubina
vidisset, flevit amarissime nec scivit ad quem locum pergeret.
Surrexit et, signo crucis se muniens, per quandam viam ambulavit, per
quam ad aquam profundam venit per quam transire oportebat, quae tam
amara et fervida fuit quod carnes pedum usque ad nuda ossa
separavit. Ille vero, de hoc contristatus, vas implevit et secum
portavit et ulterius veniens coepit esurire, vidensque quandam
arborem, de fructu eius comedit et statim factus est leprosus. De
fructu illo etiam collegit et secum portavit. Tunc veniens ad aliam
aquam, per quam transivit, quae aqua carnes restaurabat pedum, vas de
ea implevit et secum portavit et ulterius procedens coepit esurire;
et videns quandam arborem, de cuius fructu cepit et comedit et, sicut
per primum fructum infectus erat, sic per secundum fructum a lepra
est mundatus. De illo fructu etiam attulit et secum portavit.
-->
But when he awoke from his sleep and saw that the cloth had been
carried off, along with his concubine, he wept most bitterly and
knew not where to go. He got up and, fortifying himself with the
sign of the cross, wandered along a road, which led him to a deep
body of water that he needed to cross, but which was so caustic and
boiling hot that the flesh of his feet was nearly stripped to the
bone. Indeed, he was disheartened by this, filled up a vessel and
carried it with him and, coming to the far side, began to feel
hunger. He saw a tree, and ate of its fruit and at once contracted
leprosy. He gathered some of this fruit as well and carried it with
him. Then he came to another body of water and crossed over it, and
it restored the flesh to his feet. He filled a vessel with this
water and carried it with him and, once on the other side, grew
hungry. And when he saw a tree, he seized its fruit and ate it, so
that as he had been infected by the the first fruit, so by the
second he was healed of the leprosy. He picked more of this fruit
and carried it away with him.
</p>
<p>
<!--
Dum vero ulterius ambularet vidit quoddam castrum, et duo homines ei
obviabant, quaerentes quis esset. At ille: "Medicus peritus sum."
Qui dixerunt: "Rex istius regni manet in isto castro et est homo
leprosus; si eum a lepra curare posses, multas divitias tibi daret."
At ille: "Etiam."
-->
Truly, while he wandered on the far shore he saw a castle, and two
men met him, asking who he might be. And he said, "I am a skilled
physician." And they said: "The king of this realm lies in that
castle and is a leper; if you can cure him of the leprosy, he will
give you great riches." And he said: "Very well."
</p>
<p>
<!--
Qui adducentes ipsum ad regem, dedit ei de secundo fructu et curatus
est a lepra, et de secunda aqua ad bibendum, quae carnes eius
restaurabat. Rex ergo multa donaria ei contulit. Ionathas igitur
postea invenit navem de civitate sua et illuc transfretavit. Rumor
per totam civitatem exivit quod magnus medicus advenisset et
concubina sua, quae abstulerat iocalia ei, ad mortem infirmata est
mittens pro medico isto.
-->
They conducted him to the king, and he gave him some of the second
fruit and he was cured of the leprosy. And he gave him some of the
second water to drink, and his flesh was restored. And so the king
gathered together many gifts for him. And so Jonathan afterwards
found a ship and sailed from that city to there. The rumor issued
through the entire city that a great physician had arrived, and his
concubine, who had stolen his possessions, was sick unto death and
sent for this physician.
<!--
Ionathas ignotus est ab omnibus sed ipse eam cognoscens dixit ei quod
medicina sua non valeret ei, nisi prius confiteretur omnia peccata
sua, et si aliquem defraudasset, quod redderet. Illa vero alta voce
confitebatur quomodo Ionatham decepisset de anulo, monili et panno et
quomodo eum in loco deserto reliquisset bestiis ad devorandum. Ille
hoc audiens ait: "Dic, domina, ubi sunt ista tria iocalia?" Et illa:
"In area mea." Et dedit ei claves arcae et invenit ea. Ionathas ei
de fructu illius arboris a qua lepram recepit ad comedendum dedit et
de aqua prima, quae carnem de ossibus separavit, ad bibendum ei
tribuit; et cum gustasset et bibisset statim est arefacta et, dolores
interiores sentiens, lacrimabiliter clamavit et spiritum
emisit. Ionathas cum iocalibus suis ad matrem suam perrexit, de cuius
adventu totus populus gaudebat. Ille vero matri a principio usque ad
finem narravit quomodo Deus eum a multis malis periculis liberavit et
per aliquos annos vixit et vitam in pace finivit.
-->
Jonathan was a stranger to all, but he recognized her and said to
her that his medicine would avail her nothing, unless she would
first confess all of her sins, and if she had cheated anyone, then
she must pay them back. Indeed she confessed in a loud voice how
she had abandoned Jonathan to be devoured by the wild animals. He
heard this and said: "Tell me, lady, where are the three
possessions?" And she said: "In my courtyard." And she gave him the
keys to the courtyard and he found them. Jonathan gave her the
fruit of the first tree and she recieved leprosy from it. And he
gave her some of the first water, which strips the flesh from the
bones, and presented it to her to drink; and when she had eaten and
drunk she at once withered up and, feeling pain within her, cried
out mournfully and gave up the ghost. Jonathan took his possessions
and proceeded to his mother, and the whole population rejoiced at
his coming. Indeed he related to his mother from beginning to end
how God freed him from many grim perils, and lived for some years,
and finished his life in peace.
</p>
</body>
</html>
|
Java
|
// Convert DMD CodeView debug information to PDB files
// Copyright (c) 2009-2010 by Rainer Schuetze, All Rights Reserved
//
// License for redistribution is given by the Artistic License 2.0
// see file LICENSE for further details
#include "mspdb.h"
#include <windows.h>
#pragma comment(lib, "rpcrt4.lib")
HMODULE modMsPdb;
mspdb::fnPDBOpen2W *pPDBOpen2W;
char* mspdb80_dll = "mspdb80.dll";
char* mspdb100_dll = "mspdb100.dll";
bool mspdb::DBI::isVS10 = false;
bool getInstallDir(const char* version, char* installDir, DWORD size)
{
char key[260] = "SOFTWARE\\Microsoft\\";
strcat(key, version);
HKEY hkey;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, key, 0, KEY_QUERY_VALUE, &hkey) != ERROR_SUCCESS)
return false;
bool rc = RegQueryValueExA(hkey, "InstallDir", 0, 0, (LPBYTE)installDir, &size) == ERROR_SUCCESS;
RegCloseKey(hkey);
return rc;
}
bool tryLoadMsPdb(const char* version, const char* mspdb)
{
char installDir[260];
if (!getInstallDir(version, installDir, sizeof(installDir)))
return false;
char* p = installDir + strlen(installDir);
if (p[-1] != '\\' && p[-1] != '/')
*p++ = '\\';
strcpy(p, mspdb);
modMsPdb = LoadLibraryA(installDir);
return modMsPdb != 0;
}
bool initMsPdb()
{
if (!modMsPdb)
modMsPdb = LoadLibraryA(mspdb80_dll);
if (!modMsPdb)
tryLoadMsPdb("VisualStudio\\9.0", mspdb80_dll);
if (!modMsPdb)
tryLoadMsPdb("VisualStudio\\8.0", mspdb80_dll);
if (!modMsPdb)
tryLoadMsPdb("VCExpress\\9.0", mspdb80_dll);
if (!modMsPdb)
tryLoadMsPdb("VCExpress\\8.0", mspdb80_dll);
#if 1
if (!modMsPdb)
{
modMsPdb = LoadLibraryA(mspdb100_dll);
if (!modMsPdb)
tryLoadMsPdb("VisualStudio\\10.0", mspdb100_dll);
if (!modMsPdb)
tryLoadMsPdb("VCExpress\\10.0", mspdb100_dll);
if (modMsPdb)
mspdb::DBI::isVS10 = true;
}
#endif
if (!modMsPdb)
return false;
if (!pPDBOpen2W)
pPDBOpen2W = (mspdb::fnPDBOpen2W*) GetProcAddress(modMsPdb, "PDBOpen2W");
if (!pPDBOpen2W)
return false;
return true;
}
bool exitMsPdb()
{
pPDBOpen2W = 0;
if (modMsPdb)
FreeLibrary(modMsPdb);
modMsPdb = 0;
return true;
}
mspdb::PDB* CreatePDB(const wchar_t* pdbname)
{
if (!initMsPdb ())
return 0;
mspdb::PDB* pdb = 0;
long data[194] = { 193, 0 };
wchar_t ext[256] = L".exe";
if (!(*pPDBOpen2W) (pdbname, "wf", data, ext, 0x400, &pdb))
return 0;
return pdb;
}
|
Java
|
package TearDrop::Command::import_blast;
use 5.12.0;
use Mojo::Base 'Mojolicious::Command';
use Carp;
use Try::Tiny;
use TearDrop::Task::ImportBLAST;
use Getopt::Long qw(GetOptionsFromArray :config no_auto_abbrev no_ignore_case);
has description => 'Import BLAST results (currently only custom format)';
has usage => sub { shift->extract_usage };
sub run {
my ($self, @args) = @_;
my %opt = (evalue_cutoff => 0.01, max_target_seqs => 20);
GetOptionsFromArray(\@args, \%opt, 'project|p=s', 'reverse',
'db_source|db=s', 'assembly|a=s', 'evalue_cutoff=f', 'max_target_seqs=i')
or croak $self->help;
croak 'need project context' unless $opt{project};
croak 'need db_source that was blasted' unless $opt{db_source};
croak 'need assembly that was blasted against for reverse' if $opt{reverse} && !$opt{assembly};
my $task = new TearDrop::Task::ImportBLAST(
project => $opt{project},
assembly => $opt{assembly},
database => $opt{db_source},
reverse => $opt{reverse},
files => \@args,
evalue_cutoff => $opt{evalue_cutoff},
max_target_seqs => $opt{max_target_seqs},
);
try {
my $res = $task->run || croak 'task failed!';
say $res->{count}." entries imported.\n";
} catch {
croak 'import failed: '.$_;
};
}
1;
=pod
=head1 NAME
TearDrop::Command::import_blast - import BLAST results
=head1 SYNOPSIS
Usage: tear_drop import_blast [OPTIONS] [files...]
Required Options:
-p, --project [project]
Name of the project context in which to run. See L<TearDrop::Command::deploy_project>.
"Forward" BLAST:
--db, --db_source [db]
Name of a configured db source that was queried
"Reverse" BLAST:
--reverse
This was a reverse BLAST, ie. you extracted sequences from a BLAST db and blasted against a transcript assembly.
-a, --assembly [assembly]
Name of the assembly that was queried
--db, --db_source [db]
Name of the database that was BLASTed, ie. where you extracted the sequences from. This database needs to be configured!
Filtering (currently non-functional, please set the corresponding BLAST options).
--evalue_cutoff
default .01
--max_target_seqs
default 20
If no files are specified, input is read from STDIN.
Currently only a custom tabular format is understood, please use
-outfmt "6 qseqid sseqid bitscore qlen length nident pident ppos evalue slen qseq sseq qstart qend sstart send stitle"
=head1 DESCRIPTION
=head1 METHODS
Inherits all methods from L<Mojolicious::Command> and implements the following new ones.
=head2 run
$import_blast->run(@ARGV);
=cut
|
Java
|
public class Lab4_2
{
public static void main(String[] arg)
{
System.out.print(" * |");
for(int x=1;x<=12;x++) {
if (x<10) System.out.print(' ');
if (x<100) System.out.print(' ');
System.out.print(x+" ");
}
System.out.println();
for(int x=1;x<=21;x++) {
if (x<10) System.out.print('-');
System.out.print("--");
}
System.out.println();
for(int i=1;i<=12;i++)
{
if (i<10) System.out.print(' ');
System.out.print(i+" |");
for(int j=1;j<=12;j++) {
if (i*j<10) System.out.print(' ');
if (j*i<100) System.out.print(' ');
System.out.print(j*i+" ");
}
System.out.println();
}
System.out.println();
System.out.println();
System.out.print(" + |");
for(int x=1;x<=12;x++) {
if (x<10) System.out.print(' ');
if (x<100) System.out.print(' ');
System.out.print(x+" ");
}
System.out.println();
for(int x=1;x<=21;x++) {
if (x<10) System.out.print('-');
System.out.print("--");
}
System.out.println();
for(int i=1;i<=12;i++)
{
if (i<10) System.out.print(' ');
System.out.print(i+" |");
for(int j=1;j<=12;j++) {
if (i+j<10) System.out.print(' ');
if (j+i<100) System.out.print(' ');
System.out.print(j+i+" ");
}
System.out.println();
}
}
}
|
Java
|
var HLSP = {
/*
set squareness to 0 for a flat land
*/
// intensità colore land audioreattivab più bassa
mizu: {
cameraPositionY: 10,
seaLevel: 0,
displayText: '<b>CHAPTER ONE, MIZU</b><br/><i>TO BE TRAPPED INTO THE MORNING UNDERTOW</i>',
speed: 10,
modelsParams: ['stones', function(){return 1+Math.random()*40}, 3, true, true, 0],
tiles: 62,
repeatUV: 1,
bFactor: 0.5,
cFactor: 0.07594379703811609,
buildFreq: 10,
natural: 0.6834941733430447,
rainbow: 0.5641539208545766,
squareness: 0.022450016948639295,
map: 'white',
landRGB: 1966335,
horizonRGB: 0,
skyMap: 'sky4',
},
// fft1 più speedup moveSpeed
solar_valley: {
cameraPositionY: -180,
seaLevel: -450,
fogDensity: 0.00054,
displayText: '<b>CHAPTER TWO, SOLAR VALLEY</b><br><i>FIRE EXECUTION STOPPED BY CLOUDS</i>',
speed: 10,
modelsParams: ['stones', function(){return 1+Math.random()*5}, 40, true, false, -750],
tiles: 200,
repeatUV: 7,
bFactor: 0.6617959456178687,
cFactor: 0.3471716436028164,
buildFreq: 10,
natural: 0.18443493566399619,
rainbow: 0.03254734158776403,
squareness: 0.00001,
map: 'land3',
landRGB: 9675935,
horizonRGB: 3231404,
skyMap: 'sky4',
},
// camera underwater
escher_surfers: {
cameraPositionY: 40,
seaLevel: 50,
displayText: '<b>CHAPTER THREE, ESCHER SURFERS</b><br><i>TAKING REST ON K 11</i>',
speed: 15,
modelsParams: ['cube', 3, 1, true, true, 0 ],
tiles: 73,
repeatUV: 112,
bFactor: 1.001,
cFactor: 0,
buildFreq: 10,
natural: 0,
rainbow: 0.16273670793882017,
squareness: 0.08945796327125173,
map: 'pattern1',
landRGB: 16727705,
horizonRGB: 7935,
skyMap: 'sky1',
},
// sea level più basso
// modelli: cubid
currybox: {
cameraPositionY: 100,//HLE.WORLD_HEIGHT*.5,
seaLevel: -100,
displayText: '<b>CHAPTER FOUR, CURRYBOX</b><br><i>A FLAKE ON THE ROAD AND A KING AND HIS BONES</i>',
speed: 5,
modelsParams: [['cube'], function(){return 1+Math.random()*5}, 1, true, false,-100],
tiles: 145,
repeatUV: 1,
bFactor: 0.751,
cFactor: 0.054245569312940056,
buildFreq: 10,
natural: 0.176420247632921,
rainbow: 0.21934025248846812,
squareness: 0.01,
map: 'white',
landRGB: 13766158,
horizonRGB: 2665099,
skyMap: 'sky1',
},
// sealevel basso
galaxy_glacier: {
cameraPositionY: 50,
seaLevel: -100,
displayText: '<b>CHAPTER FIVE, GALAXY GLACIER</b><br><i>HITTING ICEBERGS BLAMES</i>',
speed: 2,
modelsParams: [null, 1, true, true],
tiles: 160,
repeatUV: 1,
bFactor: 0.287989180087759,
cFactor: 0.6148319562024518,
buildFreq: 61.5837970429,
natural: 0.4861551769529205,
rainbow: 0.099628324585666777,
squareness: 0.01198280149135716,
map: 'pattern5', //%
landRGB: 11187452,
horizonRGB: 6705,
skyMap: 'sky1',
},
firefly: {
cameraPositionY: 50,
displayText: '<b>CHAPTER SIX, FIREFLY</b>',
speed: 10,
modelsParams: ['sea', 1, true, true],
tiles: 100,
repeatUV: 1,
bFactor: 1,
cFactor: 1,
buildFreq: 1,
natural: 1,
rainbow: 0,
squareness: 0,
map: 'white',
landRGB: 2763306,
horizonRGB: 0,
skyMap: 'sky1',
},
//camera position.y -400
// partire sopra acqua, e poi gradualmente finire sott'acqua
//G
drift: {
cameraPositionY: -450,
seaLevel: 0,
displayText: '<b>CHAPTER SEVEN, DRIFT</b><br><i>LEAVING THE BOAT</i>',
speed: 3,
modelsParams: [['ducky'], function(){return 1+Math.random()*2}, 2, true, true, 0],
tiles: 128,
repeatUV: 0,
bFactor: 0.24952961883952426,
cFactor: 0.31,
buildFreq: 15.188759407623216,
natural: 0.3471716436028164,
rainbow: 1.001,
squareness: 0.00001,
map: 'land1',
landRGB: 16777215,
horizonRGB: 6039170,
skyMap: 'sky2',
},
//H
hyperocean: {
cameraPositionY: 50,
displayText: '<b>CHAPTER EIGHT, HYPEROCEAN</b><br><i>CRAVING FOR LOVE LASTS FOR LIFE</i>',
speed: 8,//18,
modelsParams: ['space', 2, 40, true, false, 200],
tiles: 200,
repeatUV: 12,
bFactor: 1.001,
cFactor: 0.21934025248846812,
buildFreq: 15.188759407623216,
natural: 0.7051924010682208,
rainbow: 0.1952840495265842,
squareness: 0.00001,
map: 'land5',
landRGB: 14798516,
horizonRGB: 7173242,
skyMap: 'sky2',
},
// balene
// capovolgere di conseguenza modelli balene
//I
twin_horizon: {
cameraPositionY: 100,
displayText: '<b>CHAPTER NINE, TWIN HORIZON</b><br><i>ON THE RIGHT VISION TO THE RIGHT SEASON</i>',
speed: 10,
modelsParams: ['sea', function(){return 20+Math.random()*20}, 20, false, false, 550],
tiles: 99,
repeatUV: 1,
bFactor: 0.20445411338494512,
cFactor: 0.33632252974022836,
buildFreq: 45.50809304437684,
natural: 0.4448136683661085,
rainbow: 0,
squareness: 0.0013619887944460984,
map: 'white',
landRGB: 0x000fff,
horizonRGB: 16728899,
skyMap: 'sky1',
},
// da un certo punto random colors (quando il pezzo aumenta)
// da stesso punto aumenta velocità
// sea level basso
// modelli elettrodomestici / elettronica
//J
else: {
cameraPositionY: 50,
displayText: '<b>CHAPTER TEN, ELSE</b><br><i>DIE LIKE AN ELECTRIC MACHINE</i>',
speed: 10,
modelsParams: [['ducky'], function(){return 2+Math.random()*20}, 3, true, true, 0],
tiles: 104,
repeatUV: 128,
bFactor: 0.5641539208545766,
cFactor: 0,
buildFreq: 30.804098302357595,
natural: 0.0,
rainbow: 0.6458797021572349,
squareness: 0.013562721707765414,
map: 'pattern2',
landRGB: 65399,
horizonRGB: 0x000000,
skyMap: 'sky3',
},
// quando iniziano i kick randomizza landscape
// odissea nello spazio
// cielo stellato (via lattea)
//K
roger_water: {
cameraPositionY: 50,
displayText: '<b>CHAPTER ELEVEN, ROGER WATER</b><br><i>PROTECT WATER</i>',
speed: 10,
modelsParams: ['stones', function(){return 1+Math.random()*40}, 3, true, true, 0],
tiles: 80,
repeatUV: 1,
bFactor: 0,
cFactor: 0.20613316338917223,
buildFreq: 10,
natural: 1.001,
rainbow: 0.1735858218014082,
squareness: 0.00001,
map: 'white',
landRGB: 2105376,
horizonRGB: 0,
skyMap: 'sky1',
},
//L
alpha_11: {
cameraPositionY: 50,
displayText: '<b>CHAPTER TWELVE, ALPHA 11</b><br><i>A MASSIVE WAVE IS DRIVING ME HOME</i>',
speed: 1,
modelsParams: ['stones', function(){return 1+Math.random()*40}, 3, true, true, 0],
tiles: 6,
repeatUV: 1,
bFactor: 0,
cFactor: 0,
buildFreq: 44.48136683661085,
natural: 0,
rainbow: 0,
squareness: 0.00001,
map: 'white',
landRGB: 0,
horizonRGB: 3980219,
skyMap: 'sky1',
},
//M
blackpool: {
displayText: 'BLACKPOOL',
speed: -10,
modelsParams: ['space', 2, 400, true, false, 200],
cameraPositionY: 110,
seaLevel: 10,
// speed: 4,
// modelsParams: ['sea', 1, true, true],
tiles: 182,
repeatUV: 16.555478741450983,
bFactor: 0.6048772396441062,
cFactor: 0.016358953883098624,
buildFreq: 73.3797815423632,
natural: 0.9833741906510363,
rainbow: 0.10821609644148733,
squareness: 0.00599663055740593,
map: 'land3',
landRGB: 12105440,
horizonRGB: 2571781,
skyMap: 'sky1',
},
intro: {
cameraPositionY: 650,
seaLevel:0,
displayText: 'INTRO',
speed: 0,
modelsParams: ['sea', 1, true, true],
tiles: 100,
repeatUV: 1,
bFactor: 0,
cFactor: 0,
buildFreq: 10,
natural: 1,
rainbow: 0,
squareness: 0,
map: 'sky1',
landRGB: 0x111111,
horizonRGB: 0x6f6f6f,
skyMap: 'sky3'
}
}
|
Java
|
/* ######################## Shared ######################## */
* { box-sizing: border-box; }
body {
background-color: #D4D4D4;
padding: 0px;
margin: 0px;
font-family: 'Rubik', serif;
}
section {
float: left;
width: 100%;
min-height: 100vh;
padding: 40px 80px;
}
section div {
max-width: 800px;
margin: auto;
}
p, #essay p, #classes p {
font-family: 'Roboto Mono', serif;
font-size: 1.3em;
}
li {
color: #D4D4D4;
line-height: 1.4em;
font-style: italic;
padding-right: 30px;
}
h1, h2, h3, h4, h5, h6 { /*reset for mobile browsers */
font-weight: normal;
}
h2 {
color: #ff431d;
font-size: 3em;
}
a {
color: indianred;
text-decoration: none;
font-weight: bold;
}
a:hover {
color: #ff431d;
}
/*######################## hero ########################*/
#hero h1 {
color: #ff431d;
font-weight: 800;
font-size: 5em;
font-family: "Rubik", sans-serif;
margin-bottom: 0px;
font-style: italic;
}
h3 {
font-size: 2em;
font-family: "Roboto Mono", sans-serif;
}
#hero a {
text-transform: uppercase;
}
/*######################## footer ########################*/
#colophon {
background-color: #7b868e;
padding-top: 10vh;
text-align: center;
border-top: 1px solid #333;
}
#colophon div p {
font-size: .9em;
color: #333;
margin: 20px 40px;
}
#colophon a {
text-decoration: none;
color: #1d6496;
}
#colophon h2 {
color: #D4D4D4;
font-size: 1.3em;
border-bottom: 1px solid #D4D4D4;
line-height: 200%;
margin:5px 20px;
}
/* ######################## Mobile ######################## */
@media screen and (max-width: 800px) {
* {
box-sizing: border-box;
}
body {
margin: 0px;
padding: 0px;
font-size: 20px;
}
#hero h1 {
font-size: 2.5em;
}
#hero h3, h3 {
font-size: 1em;
}
p {
font-size: .9em;
}
}
|
Java
|
/*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package uk.co.senab.photoview;
import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener;
import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener;
import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;
public class PhotoView extends ImageView implements IPhotoView {
private final PhotoViewAttacher mAttacher;
private ScaleType mPendingScaleType;
public PhotoView(Context context) {
this(context, null);
}
public PhotoView(Context context, AttributeSet attr) {
this(context, attr, 0);
}
public PhotoView(Context context, AttributeSet attr, int defStyle) {
super(context, attr, defStyle);
super.setScaleType(ScaleType.MATRIX);
mAttacher = new PhotoViewAttacher(this);
if (null != mPendingScaleType) {
setScaleType(mPendingScaleType);
mPendingScaleType = null;
}
}
@Override
public void setPhotoViewRotation(float rotationDegree) {
mAttacher.setPhotoViewRotation(rotationDegree);
}
@Override
public boolean canZoom() {
return mAttacher.canZoom();
}
@Override
public RectF getDisplayRect() {
return mAttacher.getDisplayRect();
}
@Override
public Matrix getDisplayMatrix() {
return mAttacher.getDrawMatrix();
}
@Override
public boolean setDisplayMatrix(Matrix finalRectangle) {
return mAttacher.setDisplayMatrix(finalRectangle);
}
@Override
@Deprecated
public float getMinScale() {
return getMinimumScale();
}
@Override
public float getMinimumScale() {
return mAttacher.getMinimumScale();
}
@Override
@Deprecated
public float getMidScale() {
return getMediumScale();
}
@Override
public float getMediumScale() {
return mAttacher.getMediumScale();
}
@Override
@Deprecated
public float getMaxScale() {
return getMaximumScale();
}
@Override
public float getMaximumScale() {
return mAttacher.getMaximumScale();
}
@Override
public float getScale() {
return mAttacher.getScale();
}
@Override
public ScaleType getScaleType() {
return mAttacher.getScaleType();
}
@Override
public void setAllowParentInterceptOnEdge(boolean allow) {
mAttacher.setAllowParentInterceptOnEdge(allow);
}
@Override
@Deprecated
public void setMinScale(float minScale) {
setMinimumScale(minScale);
}
@Override
public void setMinimumScale(float minimumScale) {
mAttacher.setMinimumScale(minimumScale);
}
@Override
@Deprecated
public void setMidScale(float midScale) {
setMediumScale(midScale);
}
@Override
public void setMediumScale(float mediumScale) {
mAttacher.setMediumScale(mediumScale);
}
@Override
@Deprecated
public void setMaxScale(float maxScale) {
setMaximumScale(maxScale);
}
@Override
public void setMaximumScale(float maximumScale) {
mAttacher.setMaximumScale(maximumScale);
}
@Override
// setImageBitmap calls through to this method
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {
mAttacher.setOnMatrixChangeListener(listener);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAttacher.setOnLongClickListener(l);
}
@Override
public void setOnPhotoTapListener(OnPhotoTapListener listener) {
mAttacher.setOnPhotoTapListener(listener);
}
@Override
public OnPhotoTapListener getOnPhotoTapListener() {
return mAttacher.getOnPhotoTapListener();
}
@Override
public void setOnViewTapListener(OnViewTapListener listener) {
mAttacher.setOnViewTapListener(listener);
}
@Override
public OnViewTapListener getOnViewTapListener() {
return mAttacher.getOnViewTapListener();
}
@Override
public void setScale(float scale) {
mAttacher.setScale(scale);
}
@Override
public void setScale(float scale, boolean animate) {
mAttacher.setScale(scale, animate);
}
@Override
public void setScale(float scale, float focalX, float focalY, boolean animate) {
mAttacher.setScale(scale, focalX, focalY, animate);
}
@Override
public void setScaleType(ScaleType scaleType) {
if (null != mAttacher) {
mAttacher.setScaleType(scaleType);
} else {
mPendingScaleType = scaleType;
}
}
@Override
public void setZoomable(boolean zoomable) {
mAttacher.setZoomable(zoomable);
}
@Override
public Bitmap getVisibleRectangleBitmap() {
return mAttacher.getVisibleRectangleBitmap();
}
@Override
public void setZoomTransitionDuration(int milliseconds) {
mAttacher.setZoomTransitionDuration(milliseconds);
}
@Override
protected void onDetachedFromWindow() {
mAttacher.cleanup();
super.onDetachedFromWindow();
}
}
|
Java
|
package Mojolicious::Plugins;
use Mojo::Base 'Mojo::EventEmitter';
use Mojo::Util 'camelize';
has namespaces => sub { ['Mojolicious::Plugin'] };
sub emit_hook {
my $self = shift;
for my $cb (@{$self->subscribers(shift)}) { $cb->(@_) }
return $self;
}
sub emit_chain {
my ($self, $name, @args) = @_;
my $wrapper;
for my $cb (reverse @{$self->subscribers($name)}) {
my $next = $wrapper;
$wrapper = sub { $cb->($next, @args) };
}
!$wrapper ? return : return $wrapper->();
}
sub emit_hook_reverse {
my $self = shift;
for my $cb (reverse @{$self->subscribers(shift)}) { $cb->(@_) }
return $self;
}
sub load_plugin {
my ($self, $name) = @_;
# Try all namespaces and full module name
my $suffix = $name =~ /^[a-z]/ ? camelize($name) : $name;
my @classes = map {"${_}::$suffix"} @{$self->namespaces};
for my $class (@classes, $name) { return $class->new if _load($class) }
# Not found
die qq{Plugin "$name" missing, maybe you need to install it?\n};
}
sub register_plugin {
shift->load_plugin(shift)->register(shift, ref $_[0] ? $_[0] : {@_});
}
sub _load {
my $module = shift;
return $module->isa('Mojolicious::Plugin')
unless my $e = Mojo::Loader->new->load($module);
ref $e ? die $e : return undef;
}
1;
=encoding utf8
=head1 NAME
Mojolicious::Plugins - Plugin manager
=head1 SYNOPSIS
use Mojolicious::Plugins;
my $plugins = Mojolicious::Plugins->new;
push @{$plugins->namespaces}, 'MyApp::Plugin';
=head1 DESCRIPTION
L<Mojolicious::Plugins> is the plugin manager of L<Mojolicious>.
=head1 PLUGINS
The following plugins are included in the L<Mojolicious> distribution as
examples.
=over 2
=item L<Mojolicious::Plugin::Charset>
Change the application charset.
=item L<Mojolicious::Plugin::Config>
Perl-ish configuration files.
=item L<Mojolicious::Plugin::DefaultHelpers>
General purpose helper collection, loaded automatically.
=item L<Mojolicious::Plugin::EPLRenderer>
Renderer for plain embedded Perl templates, loaded automatically.
=item L<Mojolicious::Plugin::EPRenderer>
Renderer for more sophisticated embedded Perl templates, loaded automatically.
=item L<Mojolicious::Plugin::HeaderCondition>
Route condition for all kinds of headers, loaded automatically.
=item L<Mojolicious::Plugin::JSONConfig>
JSON configuration files.
=item L<Mojolicious::Plugin::Mount>
Mount whole L<Mojolicious> applications.
=item L<Mojolicious::Plugin::PODRenderer>
Renderer for turning POD into HTML and documentation browser for
L<Mojolicious::Guides>.
=item L<Mojolicious::Plugin::TagHelpers>
Template specific helper collection, loaded automatically.
=back
=head1 EVENTS
L<Mojolicious::Plugins> inherits all events from L<Mojo::EventEmitter>.
=head1 ATTRIBUTES
L<Mojolicious::Plugins> implements the following attributes.
=head2 namespaces
my $namespaces = $plugins->namespaces;
$plugins = $plugins->namespaces(['Mojolicious::Plugin']);
Namespaces to load plugins from, defaults to L<Mojolicious::Plugin>.
# Add another namespace to load plugins from
push @{$plugins->namespaces}, 'MyApp::Plugin';
=head1 METHODS
L<Mojolicious::Plugins> inherits all methods from L<Mojo::EventEmitter> and
implements the following new ones.
=head2 emit_chain
$plugins->emit_chain('foo');
$plugins->emit_chain(foo => 123);
Emit events as chained hooks.
=head2 emit_hook
$plugins = $plugins->emit_hook('foo');
$plugins = $plugins->emit_hook(foo => 123);
Emit events as hooks.
=head2 emit_hook_reverse
$plugins = $plugins->emit_hook_reverse('foo');
$plugins = $plugins->emit_hook_reverse(foo => 123);
Emit events as hooks in reverse order.
=head2 load_plugin
my $plugin = $plugins->load_plugin('some_thing');
my $plugin = $plugins->load_plugin('SomeThing');
my $plugin = $plugins->load_plugin('MyApp::Plugin::SomeThing');
Load a plugin from the configured namespaces or by full module name.
=head2 register_plugin
$plugins->register_plugin('some_thing', Mojolicious->new);
$plugins->register_plugin('some_thing', Mojolicious->new, foo => 23);
$plugins->register_plugin('some_thing', Mojolicious->new, {foo => 23});
$plugins->register_plugin('SomeThing', Mojolicious->new);
$plugins->register_plugin('SomeThing', Mojolicious->new, foo => 23);
$plugins->register_plugin('SomeThing', Mojolicious->new, {foo => 23});
$plugins->register_plugin('MyApp::Plugin::SomeThing', Mojolicious->new);
$plugins->register_plugin(
'MyApp::Plugin::SomeThing', Mojolicious->new, foo => 23);
$plugins->register_plugin(
'MyApp::Plugin::SomeThing', Mojolicious->new, {foo => 23});
Load a plugin from the configured namespaces or by full module name and run
C<register>, optional arguments are passed through.
=head1 SEE ALSO
L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicio.us>.
=cut
|
Java
|
# Crafting
- Rethink of Crafting Ideas....
- It takes a village to craft an item.
- Crafting will no longer be something every player has several types of on each character – making alts to max it out on each.
- Crafting will be done at a guild / tribe level.
- Players provide mats to NPCs who can craft items for them.
- Crafted items take a non-trivial amount of time to produce.
- Making 20 of an item and vending it is the opposite of what we want.
- Recipes will be very hard to come by.
- Crafted items will rely on 'tech level' and factors like which materials are available and who can 'remember' how to 'card wool' / 'spin yarn' etc.
## Resources
- Basic resource nodes should be plentiful and respawn at frequent intervals.
- It should be enjoyable to harvest them.
- A freshly made char should be able to access all areas and harvest all nodes.
- Your harvesting skill should in part determine what you harvest e.g. lvl 1 gets only white resources, lvl 2 some white occasional greens, lvl 3 greens mostly some blues, etc
- Short-term buffs ala Tera
- Harvest time of day, cycle of moon and other factors affect what you are harvesting to some degree
## Crafting
- Only the most base recipes are learnt at first
- You don't need to craft things to lvl up i.e. 10 x robe of vending to prevent vast waste of mats and time / money
- Recipes are learnt from a trainer or another player...you trade money and potentially mats / etc in order to learn the recipe. You can teach that recipe to others once you've made it x number of times. The further down the chain of learning you are the more times you need to make it to perfect the recipe. You cannot charge any more than half of what you paid to learn the recipe when teaching it to others – making a shiny pyramid.
- A recipe can be taught no end of times – the pyramid can be very wide, but limited in depth eventually by value recouped on teaching it – and selling items from it
- Recipes are viral – and very very rarely ever drop making them one of the most important resources on a server to control.
- City armour, and armour specific to regions / bosses
- New recipes can be discovered or possibly formulated e.g. new armour created based on a piece of armour, a bunch of mats, gems, etc. This might be the same model as the base armour or one of many specialisations e.g. more ornate detail on the front, a fur collar, a special effect (maybe)
- Craft mats can be used from any storage you have, starting with your bags, then your bank
- Consider crafting failure, creating a lesser item
- You can learn all the crafts and all harvesting
## Harvesting
Nodes will be of a few basic types.
- Crystals
- Ore
- Plants
- Leather drops from animals / teeth / claws / sinew / etc
- Wood – or buy this from lumber mills?
- Highly rare mats like oil, sulfur, guano, unguents...bark, mushrooms, moss, etc? Weird spawn times, midnight for some items, blood moon, waxing moon...
What you harvest will be limited by both the quality of the node and your resource skill. Spread nodes of all quality over all the regions...I want regions to feel free, so you can herb in your favorite zone...you might not get mushrooms in a desert, but you shouldn't get only lvl 15 stuff because you don't like the lvl 60 regions.
## Mob Drops
Bosses and mobs don't drop armour, at least not anything worth wearing, though some might be good for prototyping other armour on...white lvl armour with a good look.
Drops will usually be rare mats for crafting, gold, potions / consumables, very very rarely a recipe,
## Customisation
Armour can be re-worked to look like any other armour in it's class i.e. leather made to look like other leather
Armour can be customised with colour
- Enchants. Just another layer of bullshit on top? Every mage ended up with basically the same enchants, same with DPS warriors and prot warriors.
- Gems. Same shit as enchants or worth thinking over?
- Reforge. Same shit as enchants?
- 3 different systems to tweak your armour – seems better to handle via one system that is far more flexible – but give them a small ability to tweak it. These seem more like cheap ways to drain cash out the economy...think of a better way.
|
Java
|
"""
WSGI config for brp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from dj_static import Cling
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "brp.settings")
os.environ.setdefault('DJANGO_CONFIGURATION', 'Dev')
application = Cling(get_wsgi_application())
|
Java
|
class Imagemagick < Formula
desc "Tools and libraries to manipulate images in many formats"
homepage "https://www.imagemagick.org/"
# Please always keep the Homebrew mirror as the primary URL as the
# ImageMagick site removes tarballs regularly which means we get issues
# unnecessarily and older versions of the formula are broken.
url "https://dl.bintray.com/homebrew/mirror/imagemagick-7.0.7-7.tar.xz"
mirror "https://www.imagemagick.org/download/ImageMagick-7.0.7-7.tar.xz"
sha256 "01b7171b784fdc689697fa35fbfa70e716a9e1608d45f81015ba78f6583f1dcf"
head "https://github.com/ImageMagick/ImageMagick.git"
bottle do
sha256 "7ba7870bae8a8b3236240cbbb6f9fde5598d78dd567c936857dd1470f7e3c7af" => :high_sierra
sha256 "7fe3ef5dc80215fb9050f441d1d00191233b90da646b3eb60f0295f00cf38169" => :sierra
sha256 "3da2ca31353e9139acd51037696a4b0bd5e2ebecdcd9f06cef1d889836e99277" => :el_capitan
end
option "with-fftw", "Compile with FFTW support"
option "with-hdri", "Compile with HDRI support"
option "with-opencl", "Compile with OpenCL support"
option "with-openmp", "Compile with OpenMP support"
option "with-perl", "Compile with PerlMagick"
option "without-magick-plus-plus", "disable build/install of Magick++"
option "without-modules", "Disable support for dynamically loadable modules"
option "without-threads", "Disable threads support"
option "with-zero-configuration", "Disables depending on XML configuration files"
deprecated_option "enable-hdri" => "with-hdri"
deprecated_option "with-jp2" => "with-openjpeg"
depends_on "pkg-config" => :build
depends_on "libtool" => :run
depends_on "xz"
depends_on "jpeg" => :recommended
depends_on "libpng" => :recommended
depends_on "libtiff" => :recommended
depends_on "freetype" => :recommended
depends_on :x11 => :optional
depends_on "fontconfig" => :optional
depends_on "little-cms" => :optional
depends_on "little-cms2" => :optional
depends_on "libwmf" => :optional
depends_on "librsvg" => :optional
depends_on "liblqr" => :optional
depends_on "openexr" => :optional
depends_on "ghostscript" => :optional
depends_on "webp" => :optional
depends_on "openjpeg" => :optional
depends_on "fftw" => :optional
depends_on "pango" => :optional
depends_on :perl => ["5.5", :optional]
needs :openmp if build.with? "openmp"
skip_clean :la
def install
args = %W[
--disable-osx-universal-binary
--prefix=#{prefix}
--disable-dependency-tracking
--disable-silent-rules
--enable-shared
--enable-static
]
if build.without? "modules"
args << "--without-modules"
else
args << "--with-modules"
end
if build.with? "opencl"
args << "--enable-opencl"
else
args << "--disable-opencl"
end
if build.with? "openmp"
args << "--enable-openmp"
else
args << "--disable-openmp"
end
if build.with? "webp"
args << "--with-webp=yes"
else
args << "--without-webp"
end
if build.with? "openjpeg"
args << "--with-openjp2"
else
args << "--without-openjp2"
end
args << "--without-gslib" if build.without? "ghostscript"
args << "--with-perl" << "--with-perl-options='PREFIX=#{prefix}'" if build.with? "perl"
args << "--with-gs-font-dir=#{HOMEBREW_PREFIX}/share/ghostscript/fonts" if build.without? "ghostscript"
args << "--without-magick-plus-plus" if build.without? "magick-plus-plus"
args << "--enable-hdri=yes" if build.with? "hdri"
args << "--without-fftw" if build.without? "fftw"
args << "--without-pango" if build.without? "pango"
args << "--without-threads" if build.without? "threads"
args << "--with-rsvg" if build.with? "librsvg"
args << "--without-x" if build.without? "x11"
args << "--with-fontconfig=yes" if build.with? "fontconfig"
args << "--with-freetype=yes" if build.with? "freetype"
args << "--enable-zero-configuration" if build.with? "zero-configuration"
args << "--without-wmf" if build.without? "libwmf"
# versioned stuff in main tree is pointless for us
inreplace "configure", "${PACKAGE_NAME}-${PACKAGE_VERSION}", "${PACKAGE_NAME}"
system "./configure", *args
system "make", "install"
end
def caveats
s = <<-EOS.undent
For full Perl support you may need to adjust your PERL5LIB variable:
export PERL5LIB="#{HOMEBREW_PREFIX}/lib/perl5/site_perl":$PERL5LIB
EOS
s if build.with? "perl"
end
test do
assert_match "PNG", shell_output("#{bin}/identify #{test_fixtures("test.png")}")
# Check support for recommended features and delegates.
features = shell_output("#{bin}/convert -version")
%w[Modules freetype jpeg png tiff].each do |feature|
assert_match feature, features
end
end
end
|
Java
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;
using CSScriptLibrary;
using System.Windows.Controls;
using Mono.CSharp;
namespace RobinhoodDesktop.Script
{
/// <summary>
/// Specifies the options for keeping processed data in memory. Ideally all processed data would be kept,
/// but if there is not enough memory for that then some may be discarded once processing has completed.
/// </summary>
public enum MemoryScheme
{
MEM_KEEP_NONE,
MEM_KEEP_SOURCE,
MEM_KEEP_DERIVED
}
[Serializable]
public class StockSession
{
#region Constants
/// <summary>
/// The designator for the stock data source (the data read from the file/live interface)
/// </summary>
public const string SOURCE_CLASS = "StockDataSource";
/// <summary>
/// The designator for the stock data sink (the analyzed data)
/// </summary>
public const string SINK_CLASS = "StockDataSink";
#endregion
#region Variables
/// <summary>
/// Stores a reference to the most recent session that was created (probably the only session)
/// </summary>
public static StockSession Instance;
/// <summary>
/// The path to the source data file
/// </summary>
public string SourceFilePath;
/// <summary>
/// The list of scripts that should be loaded to process the stock data
/// </summary>
public List<string> DataScriptPaths = new List<string>();
/// <summary>
/// The data file the source stock data is being pulled from
/// </summary>
[NonSerialized]
public StockDataFile SourceFile;
/// <summary>
/// The data file representing the analyzed stock data
/// </summary>
[NonSerialized]
public StockDataFile SinkFile;
/// <summary>
/// The stock data associated with the session
/// </summary>
[NonSerialized]
public Dictionary<string, List<StockDataInterface>> Data;
/// <summary>
/// List of action scripts that have been executed
/// </summary>
public Dictionary<object, Assembly> Scripts = new Dictionary<object, Assembly>();
/// <summary>
/// Callback that can be used to add an element to the GUI
/// </summary>
[NonSerialized]
public static AddGuiFunc AddToGui = null;
public delegate void AddGuiFunc(System.Windows.Forms.Control c);
/// <summary>
/// The container object that other GUI elements should be added to
/// </summary>
[NonSerialized]
public static System.Windows.Forms.Control GuiContainer = null;
/// <summary>
/// Callback that can be executed when the session is reloaded
/// </summary>
/// [NonSerialized]
public Action OnReload;
/// <summary>
/// A list of charts associated with this session
/// </summary>
public List<DataChartGui> Charts = new List<DataChartGui>();
#endregion
/// <summary>
/// Creates a session based on the specified source data an analysis scripts
/// </summary>
/// <param name="sources">The source data files</param>
/// <param name="sinkScripts">The data analysis scripts</param>
/// <returns>The session instance</returns>
public static StockSession LoadData(List<string> sources, List<string> sinkScripts)
{
StockSession session = new StockSession();
session.DataScriptPaths.Clear();
Directory.CreateDirectory("tmp");
// Convert any legacy files before further processing
var legacyFiles = sources.Where((s) => { return s.EndsWith(".csv"); }).ToList();
if(legacyFiles.Count() > 0)
{
System.Windows.Forms.SaveFileDialog saveDiag = new System.Windows.Forms.SaveFileDialog();
saveDiag.Title = "Save converted data file as...";
saveDiag.CheckFileExists = false;
if (saveDiag.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
List<string> convertedFileNames;
var convertedFiles = StockDataFile.ConvertByMonth(legacyFiles, Path.GetDirectoryName(saveDiag.FileName), out convertedFileNames);
foreach (var cf in convertedFileNames) sources.Add(cf);
}
else
{
// Cancel running the script
return null;
}
foreach(var l in legacyFiles) sources.Remove(l);
}
session.SourceFile = StockDataFile.Open(sources.ConvertAll<Stream>((s) => { return System.IO.Stream.Synchronized(new FileStream(s, FileMode.Open)); }));
session.DataScriptPaths.Add("tmp/" + SOURCE_CLASS + ".cs");
using(var file = new StreamWriter(new FileStream(session.DataScriptPaths.Last(), FileMode.Create))) file.Write(session.SourceFile.GetSourceCode(SOURCE_CLASS));
// Put the data set reference script first
List<string> totalSinkScripts = sinkScripts.ToList();
totalSinkScripts.Insert(0, "Script\\Data\\DataSetReference.cs");
session.SinkFile = new StockDataFile(totalSinkScripts.ConvertAll<string>((f) => { return Path.GetFileNameWithoutExtension(f); }), totalSinkScripts.ConvertAll<string>((f) => { return File.ReadAllText(f); }));
session.SinkFile.Interval = session.SourceFile.Interval;
session.DataScriptPaths.Add("tmp/" + SINK_CLASS + ".cs");
using(var file = new StreamWriter(new FileStream(session.DataScriptPaths.Last(), FileMode.Create))) file.Write(session.SinkFile.GenStockDataSink());
session.DataScriptPaths.AddRange(totalSinkScripts);
// Create the evaluator file (needs to be compiled in the script since it references StockDataSource)
string[] embeddedFiles = new string[]
{
"RobinhoodDesktop.Script.StockEvaluator.cs",
"RobinhoodDesktop.Script.StockProcessor.cs"
};
foreach(var f in embeddedFiles)
{
session.DataScriptPaths.Add(string.Format("tmp/{0}.cs", f.Substring(24, f.Length - 27)));
StringBuilder analyzerCode = new StringBuilder();
analyzerCode.Append(new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(f)).ReadToEnd());
using(var file = new StreamWriter(new FileStream(session.DataScriptPaths.Last(), FileMode.Create))) file.Write(StockDataFile.FormatSource(analyzerCode.ToString()));
}
// Add the user defined analyzers
foreach(string path in Directory.GetFiles(@"Script/Decision", "*.cs", SearchOption.AllDirectories)) session.DataScriptPaths.Add(path);
foreach(string path in Directory.GetFiles(@"Script/Action", "*.cs", SearchOption.AllDirectories)) session.DataScriptPaths.Add(path);
// Build the data
session.Reload();
if(session.Data != null)
{
StockSession.Instance = session;
}
else
{
session.SourceFile.Close();
}
return StockSession.Instance;
}
/// <summary>
/// Creates a chart instance within a data script
/// </summary>
/// <param name="sources">The data sources to load</param>
/// <param name="sinkScripts">The data processors to apply</param>
public static DataChartGui AddChart(List<string> sources, List<string> sinkScripts)
{
var session = (Instance != null) ? Instance : LoadData(sources, sinkScripts);
DataChartGui chart = null;
if(session != null) chart = session.AddChart();
return chart;
}
/// <summary>
/// Creates a new chart and adds it to the session
/// </summary>
/// <returns>The created chart</returns>
public DataChartGui AddChart()
{
DataChartGui chart = null;
if(this.Data != null)
{
try
{
chart = new DataChartGui(this.Data, this);
this.Charts.Add(chart);
var ctrl = (System.Windows.Forms.Control)(chart.GuiPanel);
if((ctrl != null) && (AddToGui != null))
{
AddToGui(ctrl);
}
}
catch(Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}
return chart;
}
/// <summary>
/// Reloads the scripts and executes them
/// </summary>
public void Reload()
{
Data = null;
SourceFile.Reload();
SinkFile.Reload();
// Re-load the data scripts, pulling in any recent changes
Run(this, DataScriptPaths);
// Create and get the StockProcessor instance, which also populates the Data field in the session
Assembly dataScript;
if(Scripts.TryGetValue(this, out dataScript))
{
var getProcessor = dataScript.GetStaticMethod("RobinhoodDesktop.Script.StockProcessor.GetInstance", this);
var processor = getProcessor(this);
// Execute the reload callback
if(OnReload != null) OnReload();
}
}
/// <summary>
/// Loads a script instance
/// </summary>
public void Run(object owner, List<string> scripts)
{
#if DEBUG
var isDebug = true;
#else
var isDebug = false;
#endif
Assembly oldScript;
if(Scripts.TryGetValue(owner, out oldScript))
{
oldScript.UnloadOwnerDomain();
Scripts.Remove(owner);
}
try
{
CSScript.EvaluatorConfig.Engine = EvaluatorEngine.Mono;
CSScript.MonoEvaluator.CompilerSettings.Platform = Mono.CSharp.Platform.X64;
List<string> references = new List<string>()
{
"TensorFlow.NET.dll",
"Google.Protobuf.dll",
"Newtonsoft.Json",
"NumSharp.Lite",
"netstandard",
"System.Memory",
"System.Numerics"
};
foreach(var s in Scripts.Values) references.Add(s.Location);
Scripts[owner] = CSScript.LoadFiles(scripts.ToArray(), null, isDebug, references.ToArray());
// Check if a "Run" method should be executed
MethodDelegate runFunc = null;
try { runFunc = Scripts[owner].GetStaticMethod("*.Run", this); } catch(Exception ex) { };
if(runFunc != null)
{
System.Threading.Tasks.Task.Run(() => { runFunc(this); });
}
}
catch(Exception ex)
{
string err = ex.ToString();
System.Text.RegularExpressions.Regex.Replace(err, "\r\n.*?warning.*?\r\n", "\r\n");
Console.WriteLine(err);
System.Windows.Forms.MessageBox.Show(err);
}
}
}
}
|
Java
|
/*_ generic.hpp Tue Jul 5 1988 Modified by: Walter Bright */
#ifndef __GENERIC_H
#define __GENERIC_H 1
/* Name concatenator functions */
#define name2(n1,n2) n1 ## n2
#define name3(n1,n2,n3) n1 ## n2 ## n3
#define name4(n1,n2,n3,n4) n1 ## n2 ## n3 ## n4
typedef int (*GPT) (int,char *);
extern int genericerror(int,char *);
#define set_handler(generic,type,x) set_##type##generic##_handler(x)
#define errorhandler(generic,type) type##generic##handler
#define callerror(generic,type,a,b) (*errorhandler(generic,type))(a,b)
#define declare(a,type) a##declare(type)
#define implement(a,type) a##implement(type)
#define declare2(a,type1,type2) a##declare2(type1,type2)
#define implement2(a,type1,type2) a##implement2(type1,type2)
#endif /* __GENERIC_H */
|
Java
|
<?php
$bbcode["code"] = array(
'callback' => 'bbcodeCodeHighlight',
'pre' => TRUE,
);
$bbcode["source"] = array(
'callback' => 'bbcodeCodeHighlight',
'pre' => TRUE,
);
function bbcodeCodeHighlight($dom, $contents, $arg)
{
// in <pre> style
$contents = preg_replace('/^\n|\n$/', "", $contents);
include_once("geshi.php");
if(!$arg)
{
$div = $dom->createElement('div');
$div->setAttribute('class', 'codeblock');
$div->appendChild($dom->createTextNode($contents));
return $div;
}
else
{
$language = $arg;
$geshi = new GeSHi($contents, $language);
$geshi->set_header_type(GESHI_HEADER_NONE);
$geshi->enable_classes();
$geshi->enable_keyword_links(false);
$code = str_replace("\n", "", $geshi->parse_code());
return markupToMarkup($dom, "<div class=\"codeblock geshi\">$code</div>");
}
}
|
Java
|
@font-face {
font-family: 'Source Sans Pro';
font-style: normal;
font-weight: 400;
src: local('Source Sans Pro'), local('SourceSansPro-Regular'), url(fonts/SourceSansPro-Regular.otf) format('opentype');
}
@font-face {
font-family: 'Source Sans Pro';
font-style: normal;
font-weight: 600;
src: local('Source Sans Pro Semibold'), local('SourceSansPro-Semibold'), url(fonts/SourceSansPro-Semibold.otf) format('opentype');
}
@font-face {
font-family: 'Source Sans Pro';
font-style: normal;
font-weight: 700;
src: local('Source Sans Pro Bold'), local('SourceSansPro-Bold'), url(fonts/SourceSansPro-Bold.otf) format('opentype');
}
@font-face {
font-family: 'Source Sans Pro';
font-style: normal;
font-weight: 900;
src: local('Source Sans Pro Black'), local('SourceSansPro-Black'), url(fonts/SourceSansPro-Black.otf) format('opentype');
}
body {
font-family: 'Source Sans Pro', 'Helvetica Neue', 'Arial', sans-serif;
line-height: 1.8em;
color: #333935;
background-color: #f5f5f5;
font-size: 15px;
margin: 0;
}
div, header, select, a {
box-sizing: border-box;
}
.full-width {
width: 100%;
}
.u-floatRight {
float: right;
}
.u-floatLeft {
float: left;
}
.u-textCenter {
text-align: center;
}
.u-textRight {
text-align: right;
}
.u-posFixed {
position: fixed;
}
li {
padding-bottom: 4px;
}
.nav {
width: 100%;
background-color: #fafafa;
top: 0;
}
.wrap-width {
width: 600px;
margin: auto;
padding: 0 20px;
}
.wrapper {
min-width: 800px;
margin-top: 60px;
}
.page-wrapper {
max-width: 600px;
margin: 60px auto 0;
padding: 15px;
}
.sidebar {
width: 25%;
position: fixed;
height: 100%;
background-color: #f5f5f5;
}
.content {
padding: 15px;
margin-left: 25%;
width: 75%;
height: 100%;
background-color: #fff;
}
.site-header {
height: 60px;
position: fixed;
top: 0;
width: 100%;
font-size: 20px;
z-index: 9;
text-align: center;
background: #fafafa;
padding: 10px 0;
border-bottom: 1px solid #e0e0e0;
}
.challenge-title {
text-transform: capitalize;
font-size: 19px;
font-weight: 800;
color: #4BABFF;
line-height: 1;
display: inline-block;
}
.pagination {
position: absolute;
top: 12px;
right: 15px;
}
.list-of-challenges {
list-style-type: none;
margin: 0;
padding: 0;
}
.list-of-challenges li {
padding: 0;
}
.challenge-item {
padding: 3px 10px;
display: block;
text-transform: capitalize;
border-top: 3px solid transparent;
border-left: 3px solid transparent;
border-bottom: 3px solid transparent;
}
/* :after instead of :before cause it messes with text-transform */
.challenge-item:after {
content: " ";
float: left;
width: 20px;
display: inline-block;
}
.challenge-item.completed:after {
content: "✔️ ";
position: absolute;
left: 10px;
top: 4px;
color: #fff;
}
.challenge-item.current .current-arrow {
display: block;
}
.current-arrow {
float: right;
display: none;
}
.challenge-item.completed:hover {
background-color: #1EA577;
}
.challenge-item.current {
background-color: #ECFCE0;
color: #456;
margin-right: -3px;
border-color: white;
}
.challenge-item.completed {
position: relative;
background-color: #22B784;
color: #fff;
padding-left: 30px;
}
.hand,
.lang-select {
padding: 4px 13px;
border-radius: 3px;
color: #0087ff;
display: inline-block;
}
.hand {
border: 1px solid #8cf;
font-size: 26px;
margin-left: 10px;
}
.lang-select {
border-color: #8cf;
position: absolute;
height: 36px;
width: 100px;
margin: 5px 8px;
top: 0;
left: 0;
appearance: none;
-webkit-appearance: none;
}
.lang-select:after {
content: "";
border: 5px solid transparent;
border-top-color: #8cf;
position: relative;
left: 40px;
top: 5px;
pointer-events: none;
display: inline-block;
z-index: 10;
}
.hand:hover {
border-color: transparent;
background-color: #08f;
color: #fff;
}
.challenge-name {
text-transform: capitalize;
font-weight: 900;
color: #0087ff;
}
.filledblock {
display: inline-block;
padding: 4px 10px;
font-weight: 900;
}
.filledblock:hover {
background: #4BABFF;
color: #fff;
}
.all-caps {
font-size: 12px;
text-transform: uppercase;
}
.site-header h2 {
margin-top: 12px;
}
h1, h2, h3, h4, .toc {
font-family: 'Source Sans Pro', 'Helvetica Neue', 'Arial', sans-serif;
}
.content h1, .content h2, .content h3, .content h4 {
margin-top: 50px;
}
a {
color: #0087ff;
text-decoration: none;
}
a:hover {
color: #4BABFF;
}
.toc li {
margin-bottom: 10px;
}
.toc li a {
font-weight: 700;
}
.toc {
padding-left: 0;
text-align: left;
list-style-position: inside;
}
.toc .done:before {
content: 'done!';
float: right;
color: #aaa;
text-decoration: none !important;
}
.toc .done a {
text-decoration: line-through;
}
code, .outof {
font-size: 0.9em;
border: 1px solid #9DA6B3;
padding: 4px 6px;
border-radius: 2px;
font-family: Liberation Mono, Monaco, Courier New, monospace;
white-space: nowrap;
}
footer {
border-top: 3px solid #0087ff;
margin: 20px 0 0;
padding: 12px 0;
}
footer ul {
margin: 0;
padding: 0;
text-align: center;
}
footer ul li {
display: inline-block;
padding: 0 6px;
}
.prenext {
overflow: auto;
}
.challenge-desc {
color: #777;
font-style: italic;
}
#git-tips,
.didnt-pass {
border: 1px solid #BADFFF;
padding: 18px;
margin: 18px 0 36px;
}
.didnt-pass {
border-color: #999;
}
#git-tips h2 {
color: #08f;
}
#git-tips h2,
.didnt-pass h2 {
margin: -32px -8px 0;
float: left;
background: #fff;
padding: 0 8px;
}
#git-tips h2 + p {
margin-top: 0;
}
#git-tips p:last-child,
.didnt-pass p:last-child {
margin-bottom: 0;
}
#git-tips ul {
list-style: none;
margin: 0;
padding: 0;
}
#git-tips code, .didnt-pass code {
border-color: #0087ff;
}
#git-tips li {
margin-top: 0px;
}
.challenge, .verify {
background-color: #0087ff;
color: #fff;
padding: 18px 18px 5px;
}
.verify code {
border-color: #fff;
display: inline-block;
}
.verify {
margin-top: 30px;
margin-bottom: 30px;
}
#git-tips h4,
.challenge h2,
.verify h3 {
margin-top: 0;
}
.didnt-pass h4 {
margin: 10px 0 0;
}
.didnt-pass h4:before {
content: '⚠️ ';
font-weight: normal;
}
.didnt-pass p + h4 {
padding-top: 30px;
}
.verify h3 {
display: inline-block;
padding-right: 12px;
}
blockquote {
border-left: 2px solid #acacac;
padding-left: 30px;
margin: 30px 0;
color: #acacac;
}
.weehero {
background-color: #0087ff;
padding: 30px;
text-align: center;
color: #fff;
font-size: 50px;
font-weight: 900;
}
img {
margin: 30px 0 18px;
}
n, v, adj {
position: relative;
}
.superscript {
font-size: 0.6em;
position: absolute;
top: -20%;
line-height: 0.6em;
font-weight: normal;
white-space: nowrap;
opacity: 0.8;
}
.u-inlineBlock {
display: inline-block;
}
/* new stuff */
#directory-path:empty {
display: none;
}
#path-required-warning,
#directory-path {
font-family: Liberation Mono, Monaco, Courier New, monospace;
padding: 6px 12px 6px 10px;
vertical-align: middle;
margin-bottom: 0;
font-size: 13px;
font-weight: 400;
text-align: center;
white-space: nowrap;
border-right: 1px solid #fff;
border-top: 1px solid #fff;
border-bottom: 1px solid #fff;
margin-left: -3px;
}
#path-required-warning {
display: none;
color: #ff0;
}
#path-required-warning.show {
display: inline;
}
#path-required-warning.show + #directory-path {
display: none;
}
.verify-fail:before {
content: '✗ ';
}
.verify-pass:before {
content: '✔︎ ';
}
#verify-list {
list-style: none;
padding-left: 0;
}
#challenge-completed {
color: #2BDA9E;
font-size: 24px;
font-family: "NothingYouCouldDo";
}
#challenge-completed h2 {
padding: 0; margin: 0;
}
.completed-challenge-list {
font-family: "NothingYouCouldDo";
/*background-color: #BADFFF;*/
color: #2BDA9E;
padding: 2px 4px;
text-transform: uppercase;
font-size: 12px;
}
button {
display: inline-block;
background-color: #CBCBCB;
color: #818181;
padding: 6px 12px;
margin-bottom: 0;
font-size: 12px;
font-weight: 400;
text-align: center;
white-space: nowrap;
vertical-align: middle;
cursor: pointer;
-webkit-user-select: none;
border: 1px solid transparent;
font-family: 'Source Sans Pro', 'Helvetica Neue', 'Arial', sans-serif;
text-transform: uppercase;
}
button:focus {
outline: 0;
}
button:hover {
background-color: #e7e7e7;
}
button.white {
background-color: #fff;
color: #0087ff;
}
button.white:hover {
background-color: #eeeeee;
}
button.white:disabled {
background-color: #F5F5F5;
color: #C8C8C8;
}
button.light-blue {
background-color: #D2EAFF;
color: #86B6E0;
}
button.light-blue:hover {
background-color: #e2effa;
}
#clear-completed-challenge {
margin-bottom: 11px;
}
#clear-all-challenges:disabled,
#get-started:disabled {
display: none;
}
.teal {
background: #2BDA9E;
color: #fff;
}
.teal:hover {
background: #6EE7BD;
color: #fff;
}
.grey-border {
border: 1px solid #818181
}
|
Java
|
/*
+------------------------------------------------------------------------+
| Phalcon Framework |
+------------------------------------------------------------------------+
| Copyright (c) 2011-2014 Phalcon Team (http://www.phalconphp.com) |
+------------------------------------------------------------------------+
| This source file is subject to the New BSD License that is bundled |
| with this package in the file docs/LICENSE.txt. |
| |
| 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@phalconphp.com so we can send you a copy immediately. |
+------------------------------------------------------------------------+
| Authors: Andres Gutierrez <andres@phalconphp.com> |
| Eduar Carvajal <eduar@phalconphp.com> |
+------------------------------------------------------------------------+
*/
#include "mvc/view/engine.h"
#include "mvc/view/engineinterface.h"
#include "di/injectable.h"
#include "kernel/main.h"
#include "kernel/memory.h"
#include "kernel/object.h"
#include "kernel/fcall.h"
/**
* Phalcon\Mvc\View\Engine
*
* All the template engine adapters must inherit this class. This provides
* basic interfacing between the engine and the Phalcon\Mvc\View component.
*/
zend_class_entry *phalcon_mvc_view_engine_ce;
PHP_METHOD(Phalcon_Mvc_View_Engine, __construct);
PHP_METHOD(Phalcon_Mvc_View_Engine, getContent);
PHP_METHOD(Phalcon_Mvc_View_Engine, partial);
PHP_METHOD(Phalcon_Mvc_View_Engine, getView);
ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine___construct, 0, 0, 1)
ZEND_ARG_INFO(0, view)
ZEND_ARG_INFO(0, dependencyInjector)
ZEND_END_ARG_INFO()
static const zend_function_entry phalcon_mvc_view_engine_method_entry[] = {
PHP_ME(Phalcon_Mvc_View_Engine, __construct, arginfo_phalcon_mvc_view_engine___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
PHP_ME(Phalcon_Mvc_View_Engine, getContent, NULL, ZEND_ACC_PUBLIC)
PHP_ME(Phalcon_Mvc_View_Engine, partial, arginfo_phalcon_mvc_view_engineinterface_partial, ZEND_ACC_PUBLIC)
PHP_ME(Phalcon_Mvc_View_Engine, getView, NULL, ZEND_ACC_PUBLIC)
PHP_FE_END
};
/**
* Phalcon\Mvc\View\Engine initializer
*/
PHALCON_INIT_CLASS(Phalcon_Mvc_View_Engine){
PHALCON_REGISTER_CLASS_EX(Phalcon\\Mvc\\View, Engine, mvc_view_engine, phalcon_di_injectable_ce, phalcon_mvc_view_engine_method_entry, ZEND_ACC_EXPLICIT_ABSTRACT_CLASS);
zend_declare_property_null(phalcon_mvc_view_engine_ce, SL("_view"), ZEND_ACC_PROTECTED TSRMLS_CC);
zend_class_implements(phalcon_mvc_view_engine_ce TSRMLS_CC, 1, phalcon_mvc_view_engineinterface_ce);
return SUCCESS;
}
/**
* Phalcon\Mvc\View\Engine constructor
*
* @param Phalcon\Mvc\ViewInterface $view
* @param Phalcon\DiInterface $dependencyInjector
*/
PHP_METHOD(Phalcon_Mvc_View_Engine, __construct){
zval *view, *dependency_injector = NULL;
phalcon_fetch_params(0, 1, 1, &view, &dependency_injector);
if (!dependency_injector) {
dependency_injector = PHALCON_GLOBAL(z_null);
}
phalcon_update_property_this(this_ptr, SL("_view"), view TSRMLS_CC);
phalcon_update_property_this(this_ptr, SL("_dependencyInjector"), dependency_injector TSRMLS_CC);
}
/**
* Returns cached ouput on another view stage
*
* @return array
*/
PHP_METHOD(Phalcon_Mvc_View_Engine, getContent)
{
zval *view = phalcon_fetch_nproperty_this(this_ptr, SL("_view"), PH_NOISY TSRMLS_CC);
PHALCON_RETURN_CALL_METHODW(view, "getcontent");
}
/**
* Renders a partial inside another view
*
* @param string $partialPath
* @param array $params
* @return string
*/
PHP_METHOD(Phalcon_Mvc_View_Engine, partial){
zval *partial_path, *params = NULL, *view;
phalcon_fetch_params(0, 1, 1, &partial_path, ¶ms);
if (!params) {
params = PHALCON_GLOBAL(z_null);
}
view = phalcon_fetch_nproperty_this(this_ptr, SL("_view"), PH_NOISY TSRMLS_CC);
PHALCON_RETURN_CALL_METHODW(view, "partial", partial_path, params);
}
/**
* Returns the view component related to the adapter
*
* @return Phalcon\Mvc\ViewInterface
*/
PHP_METHOD(Phalcon_Mvc_View_Engine, getView){
RETURN_MEMBER(this_ptr, "_view");
}
|
Java
|
FROM microsoft/aspnetcore:2.0
ARG source
WORKDIR /app
EXPOSE 80
COPY ${source:-obj/Docker/publish} .
ENTRYPOINT ["dotnet", "WebApi.dll"]
|
Java
|
"""
recursely
"""
__version__ = "0.1"
__description__ = "Recursive importer for Python submodules"
__author__ = "Karol Kuczmarski"
__license__ = "Simplified BSD"
import sys
from recursely._compat import IS_PY3
from recursely.importer import RecursiveImporter
from recursely.utils import SentinelList
__all__ = ['install']
def install(retroactive=True):
"""Install the recursive import hook in ``sys.meta_path``,
enabling the use of ``__recursive__`` directive.
:param retroactive: Whether the hook should be retroactively applied
to module's that have been imported before
it was installed.
"""
if RecursiveImporter.is_installed():
return
importer = RecursiveImporter()
# because the hook is a catch-all one, we ensure that it's always
# at the very end of ``sys.meta_path``, so that it's tried only if
# no other (more specific) hook has been chosen by Python
if IS_PY3:
for i in reversed(range(len(sys.meta_path))):
ih_module = getattr(sys.meta_path[i], '__module__', '')
is_builtin = ih_module == '_frozen_importlib'
if not is_builtin:
break
sys.meta_path = SentinelList(
sys.meta_path[:i],
sentinels=[importer] + sys.meta_path[i:])
else:
sys.meta_path = SentinelList(sys.meta_path, sentinel=importer)
# look through already imported packages and recursively import
# their submodules, if they contain the ``__recursive__`` directive
if retroactive:
for module in list(sys.modules.values()):
importer.recurse(module)
|
Java
|
// This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-ptrn-id-init-unresolvable.case
// - src/dstr-binding/error/for-of-let.template
/*---
description: Destructuring initializer is an unresolvable reference (for-of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation
es6id: 13.7.5.11
features: [destructuring-binding]
flags: [generated]
info: |
IterationStatement :
for ( ForDeclaration of AssignmentExpression ) Statement
[...]
3. Return ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult,
lexicalBinding, labelSet).
13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation
[...]
3. Let destructuring be IsDestructuring of lhs.
[...]
5. Repeat
[...]
h. If destructuring is false, then
[...]
i. Else
i. If lhsKind is assignment, then
[...]
ii. Else if lhsKind is varBinding, then
[...]
iii. Else,
1. Assert: lhsKind is lexicalBinding.
2. Assert: lhs is a ForDeclaration.
3. Let status be the result of performing BindingInitialization
for lhs passing nextValue and iterationEnv as arguments.
[...]
13.3.3.7 Runtime Semantics: KeyedBindingInitialization
SingleNameBinding : BindingIdentifier Initializeropt
[...]
6. If Initializer is present and v is undefined, then
a. Let defaultValue be the result of evaluating Initializer.
b. Let v be GetValue(defaultValue).
c. ReturnIfAbrupt(v).
6.2.3.1 GetValue (V)
1. ReturnIfAbrupt(V).
2. If Type(V) is not Reference, return V.
3. Let base be GetBase(V).
4. If IsUnresolvableReference(V), throw a ReferenceError exception.
---*/
assert.throws(ReferenceError, function() {
for (let { x = unresolvableReference } of [{}]) {
return;
}
});
|
Java
|
import {Component, OnInit} from '@angular/core';
import {MarketCard} from '../market-card';
import {MarketCardType} from '../market-card-type';
import {MarketService} from '../market.service';
import {Expansion} from '../expansion';
import { GameModeService } from '../game-mode.service';
import { GameMode } from '../game-mode';
@Component({
selector: 'app-market-selection',
templateUrl: './market-selection.component.html',
styleUrls: ['./market-selection.component.css']
})
export class MarketSelectionComponent implements OnInit {
constructor(private marketService: MarketService, private gameModeService: GameModeService) { }
cards: MarketCard[];
expeditionMode: boolean;
ngOnInit() {
this.marketService.marketCards$.subscribe((cards: MarketCard[]) => {
this.cards = cards;
});
this.cards = this.marketService.marketCards;
this.gameModeService.selectedGameMode$.subscribe((newGameMode: GameMode) => {
this.updateExpeditionMode(newGameMode);
});
this.updateExpeditionMode(this.gameModeService.selectedGameMode);
}
getCardCssClass(type: MarketCardType): string {
switch (type) {
case MarketCardType.Gem:
return 'gem-card';
case MarketCardType.Relic:
return 'relic-card';
case MarketCardType.Spell:
return 'spell-card';
}
}
getCardTypeLabel(type: MarketCardType): string {
switch (type) {
case MarketCardType.Gem:
return 'Gem';
case MarketCardType.Relic:
return 'Relic';
case MarketCardType.Spell:
return 'Spell';
}
}
private updateExpeditionMode(gameMode: GameMode): void {
this.expeditionMode = (gameMode !== GameMode.SingleGame);
}
}
|
Java
|
/**
* Copyright (c) 2013, Jens Hohmuth
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.lessvoid.coregl;
import com.lessvoid.coregl.spi.CoreGL;
/**
* Simple helper methods to render vertex arrays.
*
* @author void
*/
public class CoreRender {
private final CoreGL gl;
CoreRender(final CoreGL gl) {
this.gl = gl;
}
public static CoreRender createCoreRender(final CoreGL gl) {
return new CoreRender(gl);
}
// Lines
/**
* Render lines.
*
* @param count
* number of vertices
*/
public void renderLines(final int count) {
gl.glDrawArrays(gl.GL_LINE_STRIP(), 0, count);
gl.checkGLError("glDrawArrays");
}
/**
* Render adjacent lines.
*
* @param count
* number of vertices
*/
public void renderLinesAdjacent(final int count) {
gl.glDrawArrays(gl.GL_LINE_STRIP_ADJACENCY(), 0, count);
gl.checkGLError("glDrawArrays");
}
// Triangle Strip
/**
* Render the currently active VAO using triangle strips with the given number
* of vertices.
*
* @param count
* number of vertices to render as triangle strips
*/
public void renderTriangleStrip(final int count) {
gl.glDrawArrays(gl.GL_TRIANGLE_STRIP(), 0, count);
gl.checkGLError("glDrawArrays");
}
/**
* Render the currently active VAO using triangle strips, sending the given
* number of indizes.
*
* @param count
* number of indizes to render as triangle strips
*/
public void renderTriangleStripIndexed(final int count) {
gl.glDrawElements(gl.GL_TRIANGLE_STRIP(), count, gl.GL_UNSIGNED_INT(), 0);
gl.checkGLError("glDrawElements(GL_TRIANGLE_STRIP)");
}
/**
* Render the currently active VAO using triangle strips with the given number
* of vertices AND do that primCount times.
*
* @param count
* number of vertices to render as triangle strips per primitve
* @param primCount
* number of primitives to render
*/
public void renderTriangleStripInstances(final int count, final int primCount) {
gl.glDrawArraysInstanced(gl.GL_TRIANGLE_STRIP(), 0, count, primCount);
gl.checkGLError("glDrawArraysInstanced(GL_TRIANGLE_STRIP)");
}
// Triangle Fan
/**
* Render the currently active VAO using triangle fan with the given number of
* vertices.
*
* @param count
* number of vertices to render as triangle fan
*/
public void renderTriangleFan(final int count) {
gl.glDrawArrays(gl.GL_TRIANGLE_FAN(), 0, count);
gl.checkGLError("glDrawArrays");
}
/**
* Render the currently active VAO using triangle fans, sending the given
* number of indizes.
*
* @param count
* number of indizes to render as triangle fans.
*/
public void renderTriangleFanIndexed(final int count) {
gl.glDrawElements(gl.GL_TRIANGLE_FAN(), count, gl.GL_UNSIGNED_INT(), 0);
gl.checkGLError("glDrawElements(GL_TRIANGLE_FAN)");
}
// Individual Triangles
/**
* Render the currently active VAO using triangles with the given number of
* vertices.
*
* @param vertexCount
* number of vertices to render as triangle strips
*/
public void renderTriangles(final int vertexCount) {
gl.glDrawArrays(gl.GL_TRIANGLES(), 0, vertexCount);
gl.checkGLError("glDrawArrays");
}
/**
* Render the currently active VAO using triangles with the given number of
* vertices starting at the given offset.
*
* @param offset
* offset to start sending vertices
* @param vertexCount
* number of vertices to render as triangle strips
*/
public void renderTrianglesOffset(final int offset, final int vertexCount) {
gl.glDrawArrays(gl.GL_TRIANGLES(), offset, vertexCount);
gl.checkGLError("glDrawArrays");
}
/**
* Render the currently active VAO using triangles with the given number of
* vertices.
*
* @param count
* number of vertices to render as triangles
*/
public void renderTrianglesIndexed(final int count) {
gl.glDrawElements(gl.GL_TRIANGLES(), count, gl.GL_UNSIGNED_INT(), 0);
gl.checkGLError("glDrawElements");
}
/**
* Render the currently active VAO using triangles with the given number of
* vertices AND do that primCount times.
*
* @param count
* number of vertices to render as triangles per primitve
* @param primCount
* number of primitives to render
*/
public void renderTrianglesInstances(final int count, final int primCount) {
gl.glDrawArraysInstanced(gl.GL_TRIANGLES(), 0, count, primCount);
gl.checkGLError("glDrawArraysInstanced(GL_TRIANGLES)");
}
// Points
/**
* Render the currently active VAO using points with the given number of
* vertices.
*
* @param count
* number of vertices to render as points
*/
public void renderPoints(final int count) {
gl.glDrawArrays(gl.GL_POINTS(), 0, count);
gl.checkGLError("glDrawArrays(GL_POINTS)");
}
/**
* Render the currently active VAO using points with the given number of
* vertices AND do that primCount times.
*
* @param count
* number of vertices to render as points per primitive
* @param primCount
* number of primitives to render
*/
public void renderPointsInstances(final int count, final int primCount) {
gl.glDrawArraysInstanced(gl.GL_POINTS(), 0, count, primCount);
gl.checkGLError("glDrawArraysInstanced(GL_POINTS)");
}
// Utils
/**
* Set the clear color.
*
* @param r
* red
* @param g
* green
* @param b
* blue
* @param a
* alpha
*/
public void clearColor(final float r, final float g, final float b, final float a) {
gl.glClearColor(r, g, b, a);
}
/**
* Clear the color buffer.
*/
public void clearColorBuffer() {
gl.glClear(gl.GL_COLOR_BUFFER_BIT());
}
}
|
Java
|
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include <curl/curl.h>
#include "urldata.h"
#include "getinfo.h"
#include "vtls/vtls.h"
#include "connect.h" /* Curl_getconnectinfo() */
#include "progress.h"
/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"
/*
* Initialize statistical and informational data.
*
* This function is called in curl_easy_reset, curl_easy_duphandle and at the
* beginning of a perform session. It must reset the session-info variables,
* in particular all variables in struct PureInfo.
*/
CURLcode Curl_initinfo(struct Curl_easy *data)
{
struct Progress *pro = &data->progress;
struct PureInfo *info = &data->info;
pro->t_nslookup = 0;
pro->t_connect = 0;
pro->t_appconnect = 0;
pro->t_pretransfer = 0;
pro->t_starttransfer = 0;
pro->timespent = 0;
pro->t_redirect = 0;
pro->is_t_startransfer_set = false;
info->httpcode = 0;
info->httpproxycode = 0;
info->httpversion = 0;
info->filetime = -1; /* -1 is an illegal time and thus means unknown */
info->timecond = FALSE;
info->header_size = 0;
info->request_size = 0;
info->proxyauthavail = 0;
info->httpauthavail = 0;
info->numconnects = 0;
free(info->contenttype);
info->contenttype = NULL;
free(info->wouldredirect);
info->wouldredirect = NULL;
info->conn_primary_ip[0] = '\0';
info->conn_local_ip[0] = '\0';
info->conn_primary_port = 0;
info->conn_local_port = 0;
info->conn_scheme = 0;
info->conn_protocol = 0;
#ifdef USE_SSL
Curl_ssl_free_certinfo(data);
#endif
return CURLE_OK;
}
static CURLcode getinfo_char(struct Curl_easy *data, CURLINFO info,
const char **param_charp)
{
switch(info) {
case CURLINFO_EFFECTIVE_URL:
*param_charp = data->change.url?data->change.url:(char *)"";
break;
case CURLINFO_CONTENT_TYPE:
*param_charp = data->info.contenttype;
break;
case CURLINFO_PRIVATE:
*param_charp = (char *) data->set.private_data;
break;
case CURLINFO_FTP_ENTRY_PATH:
/* Return the entrypath string from the most recent connection.
This pointer was copied from the connectdata structure by FTP.
The actual string may be free()ed by subsequent libcurl calls so
it must be copied to a safer area before the next libcurl call.
Callers must never free it themselves. */
*param_charp = data->state.most_recent_ftp_entrypath;
break;
case CURLINFO_REDIRECT_URL:
/* Return the URL this request would have been redirected to if that
option had been enabled! */
*param_charp = data->info.wouldredirect;
break;
case CURLINFO_PRIMARY_IP:
/* Return the ip address of the most recent (primary) connection */
*param_charp = data->info.conn_primary_ip;
break;
case CURLINFO_LOCAL_IP:
/* Return the source/local ip address of the most recent (primary)
connection */
*param_charp = data->info.conn_local_ip;
break;
case CURLINFO_RTSP_SESSION_ID:
*param_charp = data->set.str[STRING_RTSP_SESSION_ID];
break;
case CURLINFO_SCHEME:
*param_charp = data->info.conn_scheme;
break;
default:
return CURLE_UNKNOWN_OPTION;
}
return CURLE_OK;
}
static CURLcode getinfo_long(struct Curl_easy *data, CURLINFO info,
long *param_longp)
{
curl_socket_t sockfd;
union {
unsigned long *to_ulong;
long *to_long;
} lptr;
#ifdef DEBUGBUILD
char *timestr = getenv("CURL_TIME");
if(timestr) {
unsigned long val = strtol(timestr, NULL, 10);
switch(info) {
case CURLINFO_LOCAL_PORT:
*param_longp = (long)val;
return CURLE_OK;
default:
break;
}
}
/* use another variable for this to allow different values */
timestr = getenv("CURL_DEBUG_SIZE");
if(timestr) {
unsigned long val = strtol(timestr, NULL, 10);
switch(info) {
case CURLINFO_HEADER_SIZE:
case CURLINFO_REQUEST_SIZE:
*param_longp = (long)val;
return CURLE_OK;
default:
break;
}
}
#endif
switch(info) {
case CURLINFO_RESPONSE_CODE:
*param_longp = data->info.httpcode;
break;
case CURLINFO_HTTP_CONNECTCODE:
*param_longp = data->info.httpproxycode;
break;
case CURLINFO_FILETIME:
if(data->info.filetime > LONG_MAX)
*param_longp = LONG_MAX;
else if(data->info.filetime < LONG_MIN)
*param_longp = LONG_MIN;
else
*param_longp = (long)data->info.filetime;
break;
case CURLINFO_HEADER_SIZE:
*param_longp = (long)data->info.header_size;
break;
case CURLINFO_REQUEST_SIZE:
*param_longp = (long)data->info.request_size;
break;
case CURLINFO_SSL_VERIFYRESULT:
*param_longp = data->set.ssl.certverifyresult;
break;
case CURLINFO_PROXY_SSL_VERIFYRESULT:
*param_longp = data->set.proxy_ssl.certverifyresult;
break;
case CURLINFO_REDIRECT_COUNT:
*param_longp = data->set.followlocation;
break;
case CURLINFO_HTTPAUTH_AVAIL:
lptr.to_long = param_longp;
*lptr.to_ulong = data->info.httpauthavail;
break;
case CURLINFO_PROXYAUTH_AVAIL:
lptr.to_long = param_longp;
*lptr.to_ulong = data->info.proxyauthavail;
break;
case CURLINFO_OS_ERRNO:
*param_longp = data->state.os_errno;
break;
case CURLINFO_NUM_CONNECTS:
*param_longp = data->info.numconnects;
break;
case CURLINFO_LASTSOCKET:
sockfd = Curl_getconnectinfo(data, NULL);
/* note: this is not a good conversion for systems with 64 bit sockets and
32 bit longs */
if(sockfd != CURL_SOCKET_BAD)
*param_longp = (long)sockfd;
else
/* this interface is documented to return -1 in case of badness, which
may not be the same as the CURL_SOCKET_BAD value */
*param_longp = -1;
break;
case CURLINFO_PRIMARY_PORT:
/* Return the (remote) port of the most recent (primary) connection */
*param_longp = data->info.conn_primary_port;
break;
case CURLINFO_LOCAL_PORT:
/* Return the local port of the most recent (primary) connection */
*param_longp = data->info.conn_local_port;
break;
case CURLINFO_CONDITION_UNMET:
if(data->info.httpcode == 304)
*param_longp = 1L;
else
/* return if the condition prevented the document to get transferred */
*param_longp = data->info.timecond ? 1L : 0L;
break;
case CURLINFO_RTSP_CLIENT_CSEQ:
*param_longp = data->state.rtsp_next_client_CSeq;
break;
case CURLINFO_RTSP_SERVER_CSEQ:
*param_longp = data->state.rtsp_next_server_CSeq;
break;
case CURLINFO_RTSP_CSEQ_RECV:
*param_longp = data->state.rtsp_CSeq_recv;
break;
case CURLINFO_HTTP_VERSION:
switch(data->info.httpversion) {
case 10:
*param_longp = CURL_HTTP_VERSION_1_0;
break;
case 11:
*param_longp = CURL_HTTP_VERSION_1_1;
break;
case 20:
*param_longp = CURL_HTTP_VERSION_2_0;
break;
case 30:
*param_longp = CURL_HTTP_VERSION_3;
break;
default:
*param_longp = CURL_HTTP_VERSION_NONE;
break;
}
break;
case CURLINFO_PROTOCOL:
*param_longp = data->info.conn_protocol;
break;
default:
return CURLE_UNKNOWN_OPTION;
}
return CURLE_OK;
}
#define DOUBLE_SECS(x) (double)(x)/1000000
static CURLcode getinfo_offt(struct Curl_easy *data, CURLINFO info,
curl_off_t *param_offt)
{
#ifdef DEBUGBUILD
char *timestr = getenv("CURL_TIME");
if(timestr) {
unsigned long val = strtol(timestr, NULL, 10);
switch(info) {
case CURLINFO_TOTAL_TIME_T:
case CURLINFO_NAMELOOKUP_TIME_T:
case CURLINFO_CONNECT_TIME_T:
case CURLINFO_APPCONNECT_TIME_T:
case CURLINFO_PRETRANSFER_TIME_T:
case CURLINFO_STARTTRANSFER_TIME_T:
case CURLINFO_REDIRECT_TIME_T:
case CURLINFO_SPEED_DOWNLOAD_T:
case CURLINFO_SPEED_UPLOAD_T:
*param_offt = (curl_off_t)val;
return CURLE_OK;
default:
break;
}
}
#endif
switch(info) {
case CURLINFO_FILETIME_T:
*param_offt = (curl_off_t)data->info.filetime;
break;
case CURLINFO_SIZE_UPLOAD_T:
*param_offt = data->progress.uploaded;
break;
case CURLINFO_SIZE_DOWNLOAD_T:
*param_offt = data->progress.downloaded;
break;
case CURLINFO_SPEED_DOWNLOAD_T:
*param_offt = data->progress.dlspeed;
break;
case CURLINFO_SPEED_UPLOAD_T:
*param_offt = data->progress.ulspeed;
break;
case CURLINFO_CONTENT_LENGTH_DOWNLOAD_T:
*param_offt = (data->progress.flags & PGRS_DL_SIZE_KNOWN)?
data->progress.size_dl:-1;
break;
case CURLINFO_CONTENT_LENGTH_UPLOAD_T:
*param_offt = (data->progress.flags & PGRS_UL_SIZE_KNOWN)?
data->progress.size_ul:-1;
break;
case CURLINFO_TOTAL_TIME_T:
*param_offt = data->progress.timespent;
break;
case CURLINFO_NAMELOOKUP_TIME_T:
*param_offt = data->progress.t_nslookup;
break;
case CURLINFO_CONNECT_TIME_T:
*param_offt = data->progress.t_connect;
break;
case CURLINFO_APPCONNECT_TIME_T:
*param_offt = data->progress.t_appconnect;
break;
case CURLINFO_PRETRANSFER_TIME_T:
*param_offt = data->progress.t_pretransfer;
break;
case CURLINFO_STARTTRANSFER_TIME_T:
*param_offt = data->progress.t_starttransfer;
break;
case CURLINFO_REDIRECT_TIME_T:
*param_offt = data->progress.t_redirect;
break;
case CURLINFO_RETRY_AFTER:
*param_offt = data->info.retry_after;
break;
default:
return CURLE_UNKNOWN_OPTION;
}
return CURLE_OK;
}
static CURLcode getinfo_double(struct Curl_easy *data, CURLINFO info,
double *param_doublep)
{
#ifdef DEBUGBUILD
char *timestr = getenv("CURL_TIME");
if(timestr) {
unsigned long val = strtol(timestr, NULL, 10);
switch(info) {
case CURLINFO_TOTAL_TIME:
case CURLINFO_NAMELOOKUP_TIME:
case CURLINFO_CONNECT_TIME:
case CURLINFO_APPCONNECT_TIME:
case CURLINFO_PRETRANSFER_TIME:
case CURLINFO_STARTTRANSFER_TIME:
case CURLINFO_REDIRECT_TIME:
case CURLINFO_SPEED_DOWNLOAD:
case CURLINFO_SPEED_UPLOAD:
*param_doublep = (double)val;
return CURLE_OK;
default:
break;
}
}
#endif
switch(info) {
case CURLINFO_TOTAL_TIME:
*param_doublep = DOUBLE_SECS(data->progress.timespent);
break;
case CURLINFO_NAMELOOKUP_TIME:
*param_doublep = DOUBLE_SECS(data->progress.t_nslookup);
break;
case CURLINFO_CONNECT_TIME:
*param_doublep = DOUBLE_SECS(data->progress.t_connect);
break;
case CURLINFO_APPCONNECT_TIME:
*param_doublep = DOUBLE_SECS(data->progress.t_appconnect);
break;
case CURLINFO_PRETRANSFER_TIME:
*param_doublep = DOUBLE_SECS(data->progress.t_pretransfer);
break;
case CURLINFO_STARTTRANSFER_TIME:
*param_doublep = DOUBLE_SECS(data->progress.t_starttransfer);
break;
case CURLINFO_SIZE_UPLOAD:
*param_doublep = (double)data->progress.uploaded;
break;
case CURLINFO_SIZE_DOWNLOAD:
*param_doublep = (double)data->progress.downloaded;
break;
case CURLINFO_SPEED_DOWNLOAD:
*param_doublep = (double)data->progress.dlspeed;
break;
case CURLINFO_SPEED_UPLOAD:
*param_doublep = (double)data->progress.ulspeed;
break;
case CURLINFO_CONTENT_LENGTH_DOWNLOAD:
*param_doublep = (data->progress.flags & PGRS_DL_SIZE_KNOWN)?
(double)data->progress.size_dl:-1;
break;
case CURLINFO_CONTENT_LENGTH_UPLOAD:
*param_doublep = (data->progress.flags & PGRS_UL_SIZE_KNOWN)?
(double)data->progress.size_ul:-1;
break;
case CURLINFO_REDIRECT_TIME:
*param_doublep = DOUBLE_SECS(data->progress.t_redirect);
break;
default:
return CURLE_UNKNOWN_OPTION;
}
return CURLE_OK;
}
static CURLcode getinfo_slist(struct Curl_easy *data, CURLINFO info,
struct curl_slist **param_slistp)
{
union {
struct curl_certinfo *to_certinfo;
struct curl_slist *to_slist;
} ptr;
switch(info) {
case CURLINFO_SSL_ENGINES:
*param_slistp = Curl_ssl_engines_list(data);
break;
case CURLINFO_COOKIELIST:
*param_slistp = Curl_cookie_list(data);
break;
case CURLINFO_CERTINFO:
/* Return the a pointer to the certinfo struct. Not really an slist
pointer but we can pretend it is here */
ptr.to_certinfo = &data->info.certs;
*param_slistp = ptr.to_slist;
break;
case CURLINFO_TLS_SESSION:
case CURLINFO_TLS_SSL_PTR:
{
struct curl_tlssessioninfo **tsip = (struct curl_tlssessioninfo **)
param_slistp;
struct curl_tlssessioninfo *tsi = &data->tsi;
#ifdef USE_SSL
struct connectdata *conn = data->conn;
#endif
*tsip = tsi;
tsi->backend = Curl_ssl_backend();
tsi->internals = NULL;
#ifdef USE_SSL
if(conn && tsi->backend != CURLSSLBACKEND_NONE) {
unsigned int i;
for(i = 0; i < (sizeof(conn->ssl) / sizeof(conn->ssl[0])); ++i) {
if(conn->ssl[i].use) {
tsi->internals = Curl_ssl->get_internals(&conn->ssl[i], info);
break;
}
}
}
#endif
}
break;
default:
return CURLE_UNKNOWN_OPTION;
}
return CURLE_OK;
}
static CURLcode getinfo_socket(struct Curl_easy *data, CURLINFO info,
curl_socket_t *param_socketp)
{
switch(info) {
case CURLINFO_ACTIVESOCKET:
*param_socketp = Curl_getconnectinfo(data, NULL);
break;
default:
return CURLE_UNKNOWN_OPTION;
}
return CURLE_OK;
}
CURLcode Curl_getinfo(struct Curl_easy *data, CURLINFO info, ...)
{
va_list arg;
long *param_longp = NULL;
double *param_doublep = NULL;
curl_off_t *param_offt = NULL;
const char **param_charp = NULL;
struct curl_slist **param_slistp = NULL;
curl_socket_t *param_socketp = NULL;
int type;
CURLcode result = CURLE_UNKNOWN_OPTION;
if(!data)
return result;
va_start(arg, info);
type = CURLINFO_TYPEMASK & (int)info;
switch(type) {
case CURLINFO_STRING:
param_charp = va_arg(arg, const char **);
if(param_charp)
result = getinfo_char(data, info, param_charp);
break;
case CURLINFO_LONG:
param_longp = va_arg(arg, long *);
if(param_longp)
result = getinfo_long(data, info, param_longp);
break;
case CURLINFO_DOUBLE:
param_doublep = va_arg(arg, double *);
if(param_doublep)
result = getinfo_double(data, info, param_doublep);
break;
case CURLINFO_OFF_T:
param_offt = va_arg(arg, curl_off_t *);
if(param_offt)
result = getinfo_offt(data, info, param_offt);
break;
case CURLINFO_SLIST:
param_slistp = va_arg(arg, struct curl_slist **);
if(param_slistp)
result = getinfo_slist(data, info, param_slistp);
break;
case CURLINFO_SOCKET:
param_socketp = va_arg(arg, curl_socket_t *);
if(param_socketp)
result = getinfo_socket(data, info, param_socketp);
break;
default:
break;
}
va_end(arg);
return result;
}
|
Java
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simulation — OSIM 0.1 documentation</title>
<link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '0.1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="next" title="Optimization" href="Optimization.html" />
<link rel="prev" title="Components" href="Components.html" />
<link rel="stylesheet" href="_static/custom.css" type="text/css" />
<meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
</head>
<body role="document">
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="simulation">
<h1>Simulation<a class="headerlink" href="#simulation" title="Permalink to this headline">¶</a></h1>
<div class="section" id="module-Simulation.NetToComp">
<span id="simulation-nettocomp"></span><h2>Simulation.NetToComp<a class="headerlink" href="#module-Simulation.NetToComp" title="Permalink to this headline">¶</a></h2>
<p>Use the triangle class to represent triangles.</p>
<dl class="class">
<dt id="Simulation.NetToComp.NetToComp">
<em class="property">class </em><code class="descclassname">Simulation.NetToComp.</code><code class="descname">NetToComp</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/Simulation/NetToComp.html#NetToComp"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#Simulation.NetToComp.NetToComp" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <code class="xref py py-class docutils literal"><span class="pre">object</span></code></p>
<p>Beispielkommentar</p>
<dl class="method">
<dt id="Simulation.NetToComp.NetToComp.getCommentsFromNetlist">
<code class="descname">getCommentsFromNetlist</code><span class="sig-paren">(</span><em>netListFile</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/Simulation/NetToComp.html#NetToComp.getCommentsFromNetlist"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#Simulation.NetToComp.NetToComp.getCommentsFromNetlist" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a triangle with sides of lengths <cite>a</cite>, <cite>b</cite>, and <cite>c</cite>.</p>
<p>Raises <cite>ValueError</cite> if the three length values provided cannot
actually form a triangle.</p>
</dd></dl>
<dl class="method">
<dt id="Simulation.NetToComp.NetToComp.getComponents">
<code class="descname">getComponents</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/Simulation/NetToComp.html#NetToComp.getComponents"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#Simulation.NetToComp.NetToComp.getComponents" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a triangle with sides of lengths <cite>a</cite>, <cite>b</cite>, and <cite>c</cite>.</p>
<p>Raises <cite>ValueError</cite> if the three length values provided cannot
actually form a triangle.</p>
</dd></dl>
<dl class="method">
<dt id="Simulation.NetToComp.NetToComp.parseCommentsToArgs">
<code class="descname">parseCommentsToArgs</code><span class="sig-paren">(</span><em>args</em>, <em>commentList</em>, <em>name</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/Simulation/NetToComp.html#NetToComp.parseCommentsToArgs"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#Simulation.NetToComp.NetToComp.parseCommentsToArgs" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="Simulation.NetToComp.NetToComp.stringArrToDict">
<code class="descname">stringArrToDict</code><span class="sig-paren">(</span><em>strArr</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/Simulation/NetToComp.html#NetToComp.stringArrToDict"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#Simulation.NetToComp.NetToComp.stringArrToDict" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a triangle with sides of lengths <cite>a</cite>, <cite>b</cite>, and <cite>c</cite>.</p>
<p>Raises <cite>ValueError</cite> if the three length values provided cannot
actually form a triangle.</p>
</dd></dl>
</dd></dl>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="index.html">Table Of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">Simulation</a><ul>
<li><a class="reference internal" href="#module-Simulation.NetToComp">Simulation.NetToComp</a></li>
</ul>
</li>
</ul>
<div class="relations">
<h3>Related Topics</h3>
<ul>
<li><a href="index.html">Documentation overview</a><ul>
<li>Previous: <a href="Components.html" title="previous chapter">Components</a></li>
<li>Next: <a href="Optimization.html" title="next chapter">Optimization</a></li>
</ul></li>
</ul>
</div>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/Simulation.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<div><input type="text" name="q" /></div>
<div><input type="submit" value="Go" /></div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer">
©2017, Tim Maiwald.
|
Powered by <a href="http://sphinx-doc.org/">Sphinx 1.5.4</a>
& <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.9</a>
|
<a href="_sources/Simulation.rst.txt"
rel="nofollow">Page source</a>
</div>
</body>
</html>
|
Java
|
# coding: utf-8
import sys
from setuptools import setup, find_packages
NAME = "pollster"
VERSION = "2.0.2"
# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setuptools
REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil", "pandas >= 0.19.1"]
setup(
name=NAME,
version=VERSION,
description="Pollster API",
author_email="Adam Hooper <adam.hooper@huffingtonpost.com>",
url="https://github.com/huffpostdata/python-pollster",
keywords=["Pollster API"],
install_requires=REQUIRES,
packages=find_packages(),
include_package_data=True,
long_description="""Download election-related polling data from Pollster."""
)
|
Java
|
import requests
import logging
import redis
from requests.packages.urllib3.exceptions import ConnectionError
from core.serialisers import json
from dss import localsettings
# TODO(fergal.moran@gmail.com): refactor these out to
# classes to avoid duplicating constants below
HEADERS = {
'content-type': 'application/json'
}
logger = logging.getLogger('spa')
def post_notification(session_id, image, message):
try:
payload = {
'sessionid': session_id,
'image': image,
'message': message
}
data = json.dumps(payload)
r = requests.post(
localsettings.REALTIME_HOST + 'notification',
data=data,
headers=HEADERS
)
if r.status_code == 200:
return ""
else:
return r.text
except ConnectionError:
#should probably implement some sort of retry in here
pass
|
Java
|
unless ENV["HOMEBREW_BREW_FILE"]
raise "HOMEBREW_BREW_FILE was not exported! Please call bin/brew directly!"
end
require "constants"
require "tmpdir"
require "pathname"
HOMEBREW_BREW_FILE = Pathname.new(ENV["HOMEBREW_BREW_FILE"])
TEST_TMPDIR = ENV.fetch("HOMEBREW_TEST_TMPDIR") do |k|
dir = Dir.mktmpdir("homebrew-tests-", ENV["HOMEBREW_TEMP"] || "/tmp")
at_exit { FileUtils.remove_entry(dir) }
ENV[k] = dir
end
# Paths pointing into the Homebrew code base that persist across test runs
HOMEBREW_LIBRARY_PATH = Pathname.new(File.expand_path("../../../..", __FILE__))
HOMEBREW_SHIMS_PATH = HOMEBREW_LIBRARY_PATH.parent+"Homebrew/shims"
HOMEBREW_LOAD_PATH = [File.expand_path("..", __FILE__), HOMEBREW_LIBRARY_PATH].join(":")
# Paths redirected to a temporary directory and wiped at the end of the test run
HOMEBREW_PREFIX = Pathname.new(TEST_TMPDIR).join("prefix")
HOMEBREW_REPOSITORY = HOMEBREW_PREFIX
HOMEBREW_LIBRARY = HOMEBREW_REPOSITORY+"Library"
HOMEBREW_CACHE = HOMEBREW_PREFIX.parent+"cache"
HOMEBREW_CACHE_FORMULA = HOMEBREW_PREFIX.parent+"formula_cache"
HOMEBREW_LINKED_KEGS = HOMEBREW_PREFIX.parent+"linked"
HOMEBREW_PINNED_KEGS = HOMEBREW_PREFIX.parent+"pinned"
HOMEBREW_LOCK_DIR = HOMEBREW_PREFIX.parent+"locks"
HOMEBREW_CELLAR = HOMEBREW_PREFIX.parent+"cellar"
HOMEBREW_LOGS = HOMEBREW_PREFIX.parent+"logs"
HOMEBREW_TEMP = HOMEBREW_PREFIX.parent+"temp"
TEST_FIXTURE_DIR = HOMEBREW_LIBRARY_PATH.join("test", "support", "fixtures")
TESTBALL_SHA1 = "be478fd8a80fe7f29196d6400326ac91dad68c37".freeze
TESTBALL_SHA256 = "91e3f7930c98d7ccfb288e115ed52d06b0e5bc16fec7dce8bdda86530027067b".freeze
TESTBALL_PATCHES_SHA256 = "799c2d551ac5c3a5759bea7796631a7906a6a24435b52261a317133a0bfb34d9".freeze
PATCH_A_SHA256 = "83404f4936d3257e65f176c4ffb5a5b8d6edd644a21c8d8dcc73e22a6d28fcfa".freeze
PATCH_B_SHA256 = "57958271bb802a59452d0816e0670d16c8b70bdf6530bcf6f78726489ad89b90".freeze
LINUX_TESTBALL_SHA256 = "fa7fac451a7c37e74f02e2a425a76aff89106098a55707832a02be5af5071cf8".freeze
TEST_SHA1 = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef".freeze
TEST_SHA256 = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".freeze
|
Java
|
# Copyright (c) 2015-2016, Ruslan Baratov
# All rights reserved.
include(hunter_apply_copy_rules)
include(hunter_apply_gate_settings)
include(hunter_calculate_self)
include(hunter_create_cache_file)
include(hunter_fatal_error)
include(hunter_internal_error)
include(hunter_sanity_checks)
include(hunter_status_debug)
include(hunter_status_print)
include(hunter_test_string_not_empty)
# Continue initialization of key variables (also see 'hunter_initialize')
# * calculate toolchain-id
# * calculate config-id
macro(hunter_finalize)
# Check preconditions
hunter_sanity_checks()
list(APPEND HUNTER_CACHE_SERVERS "https://github.com/ingenue/hunter-cache")
list(REMOVE_DUPLICATES HUNTER_CACHE_SERVERS)
hunter_status_debug("List of cache servers:")
foreach(_server ${HUNTER_CACHE_SERVERS})
hunter_status_debug(" * ${_server}")
endforeach()
get_property(_enabled_languages GLOBAL PROPERTY ENABLED_LANGUAGES)
list(FIND _enabled_languages "C" _c_enabled_result)
if(_c_enabled_result EQUAL -1)
set(_c_enabled FALSE)
else()
set(_c_enabled TRUE)
endif()
list(FIND _enabled_languages "CXX" _cxx_enabled_result)
if(_cxx_enabled_result EQUAL -1)
set(_cxx_enabled FALSE)
else()
set(_cxx_enabled TRUE)
endif()
if(_c_enabled AND NOT CMAKE_C_ABI_COMPILED)
hunter_fatal_error(
"ABI not detected for C compiler" WIKI "error.abi.detection.failure"
)
endif()
if(_cxx_enabled AND NOT CMAKE_CXX_ABI_COMPILED)
hunter_fatal_error(
"ABI not detected for CXX compiler" WIKI "error.abi.detection.failure"
)
endif()
string(COMPARE NOTEQUAL "$ENV{HUNTER_BINARY_DIR}" "" _env_not_empty)
if(_env_not_empty)
get_filename_component(HUNTER_BINARY_DIR "$ENV{HUNTER_BINARY_DIR}" ABSOLUTE)
hunter_status_debug("HUNTER_BINARY_DIR: ${HUNTER_BINARY_DIR}")
endif()
# * Read HUNTER_GATE_* variables
# * Check cache HUNTER_* variables is up-to-date
# * Update cache if needed
hunter_apply_gate_settings()
string(SUBSTRING "${HUNTER_SHA1}" 0 7 HUNTER_ID)
string(SUBSTRING "${HUNTER_CONFIG_SHA1}" 0 7 HUNTER_CONFIG_ID)
string(SUBSTRING "${HUNTER_TOOLCHAIN_SHA1}" 0 7 HUNTER_TOOLCHAIN_ID)
set(HUNTER_ID_PATH "${HUNTER_CACHED_ROOT}/_Base/${HUNTER_ID}")
set(HUNTER_CONFIG_ID_PATH "${HUNTER_ID_PATH}/${HUNTER_CONFIG_ID}")
set(
HUNTER_TOOLCHAIN_ID_PATH
"${HUNTER_CONFIG_ID_PATH}/${HUNTER_TOOLCHAIN_ID}"
)
set(HUNTER_INSTALL_PREFIX "${HUNTER_TOOLCHAIN_ID_PATH}/Install")
list(APPEND CMAKE_PREFIX_PATH "${HUNTER_INSTALL_PREFIX}")
if(ANDROID)
# OpenCV support: https://github.com/ruslo/hunter/issues/153
list(APPEND CMAKE_PREFIX_PATH "${HUNTER_INSTALL_PREFIX}/sdk/native/jni")
endif()
list(APPEND CMAKE_FIND_ROOT_PATH "${HUNTER_INSTALL_PREFIX}")
hunter_status_print("HUNTER_ROOT: ${HUNTER_CACHED_ROOT}")
hunter_status_debug("HUNTER_TOOLCHAIN_ID_PATH: ${HUNTER_TOOLCHAIN_ID_PATH}")
hunter_status_debug(
"HUNTER_CONFIGURATION_TYPES: ${HUNTER_CACHED_CONFIGURATION_TYPES}"
)
set(_id_info "[ Hunter-ID: ${HUNTER_ID} |")
set(_id_info "${_id_info} Config-ID: ${HUNTER_CONFIG_ID} |")
set(_id_info "${_id_info} Toolchain-ID: ${HUNTER_TOOLCHAIN_ID} ]")
hunter_status_print("${_id_info}")
set(HUNTER_CACHE_FILE "${HUNTER_TOOLCHAIN_ID_PATH}/cache.cmake")
hunter_create_cache_file("${HUNTER_CACHE_FILE}")
if(MSVC)
include(hunter_setup_msvc)
hunter_setup_msvc()
endif()
### Disable package registry
### http://www.cmake.org/cmake/help/v3.1/manual/cmake-packages.7.html#disabling-the-package-registry
set(CMAKE_EXPORT_NO_PACKAGE_REGISTRY ON)
set(CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY ON)
set(CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY ON)
### -- end
### Disable environment variables
### http://www.cmake.org/cmake/help/v3.3/command/find_package.html
set(ENV{CMAKE_PREFIX_PATH} "")
set(ENV{CMAKE_FRAMEWORK_PATH} "")
set(ENV{CMAKE_APPBUNDLE_PATH} "")
### -- end
### 1. Clear all '<NAME>_ROOT' variables (cache, environment, ...)
### 2. Set '<NAME>_ROOT' or 'HUNTER_<name>_VERSION' variables
set(HUNTER_ALLOW_CONFIG_LOADING YES)
include("${HUNTER_CONFIG_ID_PATH}/config.cmake")
set(HUNTER_ALLOW_CONFIG_LOADING NO)
hunter_test_string_not_empty("${HUNTER_INSTALL_PREFIX}")
hunter_test_string_not_empty("${CMAKE_BINARY_DIR}")
file(
WRITE
"${CMAKE_BINARY_DIR}/_3rdParty/Hunter/install-root-dir"
"${HUNTER_INSTALL_PREFIX}"
)
hunter_apply_copy_rules()
if(ANDROID AND CMAKE_VERSION VERSION_LESS "3.7.1")
hunter_user_error(
"CMake version 3.7.1+ required for Android platforms, see"
" https://docs.hunter.sh/en/latest/quick-start/cmake.html"
)
endif()
# Android GDBSERVER moved to
# https://github.com/hunter-packages/android-apk/commit/32531adeb287d3e3b20498ff1a0f76336cbe0551
# Fix backslashed provided by user:
# * https://github.com/ruslo/hunter/issues/693
# Note: we can't use 'get_filename_component(... ABSOLUTE)' because sometimes
# original path expected. E.g. NMake build:
# * https://ci.appveyor.com/project/ingenue/hunter/build/1.0.1412/job/o8a21ue85ivt5d0p
string(REPLACE "\\" "\\\\" CMAKE_MAKE_PROGRAM "${CMAKE_MAKE_PROGRAM}")
endmacro()
|
Java
|
# Copyright (c) 2021, DjaoDjin Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
__version__ = '0.6.4-dev'
|
Java
|
/*
* Copyright (C) 2005 by egnite Software GmbH. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* For additional information see http://www.ethernut.de/
*/
/*
* $Log$
* Revision 0.01 2009/09/20 ulrichprinz
* First checkin of using DBGU as limited standard USART.
*
*/
//#define NUT_DEPRECATED
#include <cfg/os.h>
#include <cfg/clock.h>
#include <cfg/arch.h>
#include <cfg/uart.h>
#include <string.h>
#include <sys/atom.h>
#include <sys/event.h>
#include <sys/timer.h>
#include <dev/irqreg.h>
#include <dev/debug.h>
#include <arch/cm3.h>
#include <arch/arm/at91_dbgu.h>
#include <dev/usartat91.h>
/*
* Local function prototypes.
*
* Commented functions are not supported by DBGU
*
*/
static uint32_t At91UsartGetSpeed(void);
static int At91UsartSetSpeed(uint32_t rate);
static uint8_t At91UsartGetDataBits(void);
static int At91UsartSetDataBits( uint8_t bits);
static uint8_t At91UsartGetParity(void);
static int At91UsartSetParity(uint8_t mode);
static uint8_t At91UsartGetStopBits(void);
static int At91UsartSetStopBits(uint8_t bits);
static uint32_t At91UsartGetStatus(void);
static int At91UsartSetStatus(uint32_t flags);
static uint8_t At91UsartGetClockMode(void);
static int At91UsartSetClockMode(uint8_t mode);
static void At91UsartTxStart(void);
static void At91UsartRxStart(void);
static int At91UsartInit(void);
static int At91UsartDeinit(void);
static uint32_t At91UsartGetFlowControl(void);
static int At91UsartSetFlowControl(uint32_t flags);
#define sig_DBGU sig_UART
#define DBGU_BASE AT91C_BASE_DBGU
#define US_ID AT91C_ID_DBGU
#define PMC_PCER AT91C_PMC_PCER
#define PMC_PCDR AT91C_PMC_PCDR
extern IRQ_HANDLER sig_DBGU;
/*!
* \addtogroup xgNutArchArmAt91Us
*/
/*@{*/
/*!
* \brief DBGU device control block structure.
*/
static USARTDCB dcb_dbgu = {
0, /* dcb_modeflags */
0, /* dcb_statusflags */
0, /* dcb_rtimeout */
0, /* dcb_wtimeout */
{0, 0, 0, 0, 0, 0, 0, 0}, /* dcb_tx_rbf */
{0, 0, 0, 0, 0, 0, 0, 0}, /* dcb_rx_rbf */
0, /* dbc_last_eol */
At91UsartInit, /* dcb_init */
At91UsartDeinit, /* dcb_deinit */
At91UsartTxStart, /* dcb_tx_start */
At91UsartRxStart, /* dcb_rx_start */
At91UsartSetFlowControl, /* dcb_set_flow_control */
At91UsartGetFlowControl, /* dcb_get_flow_control */
At91UsartSetSpeed, /* dcb_set_speed */
At91UsartGetSpeed, /* dcb_get_speed */
At91UsartSetDataBits, /* dcb_set_data_bits */
At91UsartGetDataBits, /* dcb_get_data_bits */
At91UsartSetParity, /* dcb_set_parity */
At91UsartGetParity, /* dcb_get_parity */
At91UsartSetStopBits, /* dcb_set_stop_bits */
At91UsartGetStopBits, /* dcb_get_stop_bits */
At91UsartSetStatus, /* dcb_set_status */
At91UsartGetStatus, /* dcb_get_status */
At91UsartSetClockMode, /* dcb_set_clock_mode */
At91UsartGetClockMode, /* dcb_get_clock_mode */
};
/*!
* \name AT91 DBGU Device
*/
/*@{*/
/*!
* \brief USART0 device information structure.
*
* An application must pass a pointer to this structure to
* NutRegisterDevice() before using the serial communication
* driver of the AT91's on-chip USART0.
*
* The device is named \b uart0.
*
* \showinitializer
*/
NUTDEVICE devDebug = {
0, /* Pointer to next device, dev_next. */
{'d', 'b', 'g', 'u', 0, 0, 0, 0, 0}, /* Unique device name, dev_name. */
IFTYP_CHAR, /* Type of device, dev_type. */
AT91C_BASE_DBGU, /* Base address, dev_base (not used). */
0, /* First interrupt number, dev_irq (not used). */
0, /* Interface control block, dev_icb (not used). */
&dcb_dbgu, /* Driver control block, dev_dcb. */
UsartInit, /* Driver initialization routine, dev_init. */
UsartIOCtl, /* Driver specific control function, dev_ioctl. */
UsartRead, /* Read from device, dev_read. */
UsartWrite, /* Write to device, dev_write. */
UsartOpen, /* Open a device or file, dev_open. */
UsartClose, /* Close a device or file, dev_close. */
UsartSize /* Request file size, dev_size. */
};
/*@}*/
/*@}*/
/* Modem control includes hardware handshake. */
/*
* Hardware driven control signals are not available
* with the DBUG unit of most chips.
*/
#undef UART_MODEM_CONTROL
#undef UART_HARDWARE_HANDSHAKE
#define UART_RXTX_PINS (AT91C_PA11_DRXD|AT91C_PA12_DTXD)
#undef UART_HDX_PIN
#undef UART_RTS_PIN
#undef UART_CTS_PIN
#undef UART_MODEM_PINS
#define UART_RXTX_PINS_ENABLE() outr(AT91C_PIOA_PDR, UART_RXTX_PINS)
#define UART_INIT_BAUDRATE 115200
#define USARTn_BASE AT91C_BASE_DBGU
#define US_ID AT91C_ID_DBGU
#define SIG_UART sig_UART
#define dcb_usart dcb_dbgu
#include "usartat91.c"
|
Java
|
global _check_for_key
_check_for_key:
push bp
mov bp, sp
mov ax, word [bp+4]
call os_check_for_key
pop bp
ret
|
Java
|
// --------------------------------------------------------------------------------
// SharpDisasm (File: SharpDisasm\ud_operand_code.cs)
// Copyright (c) 2014-2015 Justin Stenning
// http://spazzarama.com
// https://github.com/spazzarama/SharpDisasm
// https://sharpdisasm.codeplex.com/
//
// SharpDisasm is distributed under the 2-clause "Simplified BSD License".
//
// Portions of SharpDisasm are ported to C# from udis86 a C disassembler project
// also distributed under the terms of the 2-clause "Simplified BSD License" and
// Copyright (c) 2002-2012, Vivek Thampi <vivek.mt@gmail.com>
// All rights reserved.
// UDIS86: https://github.com/vmt/udis86
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// --------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SharpDisasm.Udis86
{
#pragma warning disable 1591
/* operand type constants -- order is important! */
/// <summary>
/// Operand codes
/// </summary>
public enum ud_operand_code {
OP_NONE,
OP_A, OP_E, OP_M, OP_G,
OP_I, OP_F,
OP_R0, OP_R1, OP_R2, OP_R3,
OP_R4, OP_R5, OP_R6, OP_R7,
OP_AL, OP_CL, OP_DL,
OP_AX, OP_CX, OP_DX,
OP_eAX, OP_eCX, OP_eDX,
OP_rAX, OP_rCX, OP_rDX,
OP_ES, OP_CS, OP_SS, OP_DS,
OP_FS, OP_GS,
OP_ST0, OP_ST1, OP_ST2, OP_ST3,
OP_ST4, OP_ST5, OP_ST6, OP_ST7,
OP_J, OP_S, OP_O,
OP_I1, OP_I3, OP_sI,
OP_V, OP_W, OP_Q, OP_P,
OP_U, OP_N, OP_MU, OP_H,
OP_L,
OP_R, OP_C, OP_D,
OP_MR
}
#pragma warning restore 1591
}
|
Java
|
# Contacts and Contributors
This section contains important contacts for the project, in different know how areas. It is also our know how management list.
## Active Contacts
Topic | Contacts
:---|:---
Product Management | Joakim Bucher, Patrick Schweizer
Business Analysis | Markus Flückiger, Stephan Koch
Interaction Design and UX | Markus Flückiger
Requirements Engineering | Stephan Koch, Patrick Schweizer, Markus Flückiger
Business Consulting | Christoph Hauert
Software Architecture | Joakim Bucher, Rolf Bruderer, Patrick Schweizer
Development | Joakim Bucher, Martin Leimer, Patrick Schweizer, Rolf Bruderer, ...
Build System | ???
BDD Testing with Spec Flow in C# | Joakim Bucher
BDD Testing with JBehave in Java | Martin Leimer
Markdown Tooling | Rolf Bruderer
Scenarioo | Rolf Bruderer, Patrick Schweizer
This list should help to find quickly a contact for a special know how area. It also helps to identify quickly in which area we have enough contributors with know how and where we should try to do more know how transfer during our work.
## Alumni Contributors
These are the former contributors that have left the team, with their most important know how areas. Just to remember all contributors that gave valuable input, in case to contact them for later questions and also to know who to invite for any "Project Success Event" ;-)
Name | Contributions | Year of Leave
:---|:---|:---
Joram Zimmermann | Conducting first Spec-by-Ex Workshops, Focus Group Kickoff | 2015
|
Java
|
# Copyright 2014 Dev in Cachu authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from django.conf import settings
from django.conf.urls import include, patterns, url
from django.views.decorators import csrf
from django.views.generic import base
from django.contrib import admin
admin.autodiscover()
from devincachu.destaques import views as dviews
from devincachu.inscricao import views as iviews
from devincachu.palestras import views as pviews
p = patterns
urlpatterns = p("",
url(r"^admin/", include(admin.site.urls)),
url(r"^palestrantes/$",
pviews.PalestrantesView.as_view(),
name="palestrantes"),
url(r"^programacao/$",
pviews.ProgramacaoView.as_view(),
name="programacao"),
url(r"^programacao/(?P<palestrantes>.*)/(?P<slug>[\w-]+)/$",
pviews.PalestraView.as_view(),
name="palestra"),
url(r"^inscricao/$",
iviews.Inscricao.as_view(),
name="inscricao"),
url(r"^notificacao/$",
csrf.csrf_exempt(iviews.Notificacao.as_view()),
name="notificacao"),
url(r"^certificado/validar/$",
iviews.ValidacaoCertificado.as_view(),
name="validacao_certificado"),
url(r"^certificado/$",
iviews.BuscarCertificado.as_view(),
name="busca_certificado"),
url(r"^certificado/(?P<slug>[0-9a-f]+)/$",
iviews.Certificado.as_view(),
name="certificado"),
url(r"^sobre/$",
base.TemplateView.as_view(
template_name="sobre.html",
),
name="sobre-o-evento"),
url(r"^quando-e-onde/$",
base.TemplateView.as_view(
template_name="quando-e-onde.html",
),
name="quando-e-onde"),
url(r"^$", dviews.IndexView.as_view(), name="index"),
)
if settings.DEBUG:
urlpatterns += patterns("",
url(r"^media/(?P<path>.*)$",
"django.views.static.serve",
{"document_root": settings.MEDIA_ROOT}),
)
|
Java
|
{-# LANGUAGE TupleSections #-}
module Arbitrary.TestModule where
import Data.Integrated.TestModule
import Test.QuickCheck
import Data.ModulePath
import Control.Applicative
import Arbitrary.Properties
import Test.Util
import Filesystem.Path.CurrentOS
import Prelude hiding (FilePath)
import qualified Arbitrary.ModulePath as MP
import qualified Data.Set as S
testModulePath :: Gen Char -> S.Set ModulePath -> Gen ModulePath
testModulePath subpath avoided =
suchThat
(fromModPath <$> MP.toModulePath subpath)
(not . flip S.member avoided)
where
fromModPath :: ModulePath -> ModulePath
fromModPath (ModulePath pth) =
ModulePath $ take (length pth - 1) pth ++ [testFormat $ last pth]
toTestModule :: ModulePath -> Gen TestModule
toTestModule mp = do
props <- arbitrary :: Gen Properties
return $ TestModule mp (list props)
-- Generate a random test file, care must be taken to avoid generating
-- the same path twice
toGenerated :: Gen Char -> S.Set ModulePath -> Gen (FilePath, TestModule)
toGenerated subpath avoided = do
mp <- testModulePath subpath avoided
(relPath mp,) <$> toTestModule mp
|
Java
|
# -*- coding: utf-8 -*-
class Pkg
@pkgDir
@jailDir
def self.init()
@pkgDir = System.getConf("pkgDir")
@jailDir = System.getConf("jailDir")
end
def self.main(data)
if (data["control"] == "search") then
search(data["name"]).each_line do |pname|
pname = pname.chomp
SendMsg.machine("pkg","search",pname)
end
elsif(data["control"] == "list") then
pkg = list("all")
pkg.each do |pname|
SendMsg.machine("pkg","list",pname[0])
end
elsif(data["control"] == "install") then
cmdLog,cause = install(data["name"])
if(cmdLog == false)
SendMsg.status(MACHINE,"failed",cause)
return
else
SendMsg.status(MACHINE,"success","完了しました。")
end
end
end
def self.add(jname,pname)
puts "pkg-static -j #{jname} add /pkg/#{pname}.txz"
s,e = Open3.capture3("pkg-static -j #{jname} add /pkg/#{pname}.txz")
end
def self.search(pname) #host側でやらせる
s,e = Open3.capture3("pkg-static search #{pname}")
return s
end
def self.download(pname)
flag = false
pkgVal = 0
now = 1
IO.popen("echo y|pkg-static fetch -d #{pname}") do |pipe|
pipe.each do | line |
# puts line
if(line.include?("New packages to be FETCHED:")) then #ダウンロードするパッケージの数を計算(NEw packages〜からThe process〜までの行数)
flag = true
end
if(line.include?("The process will require")) then
pkgVal -= 2
flag = false
end
if(flag == true) then
pkgVal += 1
end
if(line.include?("Fetching")) then
if(line.include?("Proceed with fetching packages? [y/N]: ")) then
line.gsub!("Proceed with fetching packages? [y/N]: ","")
end
SendMsg.status(MACHINE,"log","#{line}(#{now}/#{pkgVal})")
now += 1
end
end
end
cmdLog,e = Open3.capture3("ls #{@jailDir}/sharedfs/pkg")
s,e = Open3.capture3("cp -pn #{@pkgDir}/* #{@jailDir}/sharedfs/pkg/") #sharedfsにコピー(qjail)
cmdLog2,e = Open3.capture3("ls #{@jailDir}/sharedfs/pkg")
=begin
if(cmdLog == cmdLog2) #ダウンロード前後にlsの結果を取って、要素が同じならばダウンロードに失敗しているとわかる(ファイルが増えていない)
puts ("pkgcopyerror")
return false,"pkgcopy"
end
=end
end
def self.install(pname) #host側でやらせる
cmdLog, cause = download(pname)
SendMsg.status(MACHINE,"report","pkgdownload")
cmdLog,e = Open3.capture3("ls #{@jailDir}/sharedfs/pkg/#{pname}.txz")
cmdLog = cmdLog.chomp #改行削除
if(cmdLog != "#{@jailDir}/sharedfs/pkg/#{pname}.txz")
return false,"copy"
end
SendMsg.status(MACHINE,"report","pkgcopy")
nextid = SQL.select("pkg","maxid") + 1
SQL.insert("pkg",pname)
sqlid = SQL.select("pkg",nextid)[0] #作成したpkgのIDを取得
if (sqlid != nextid ) then #sqlidがnextidではない(恐らくnextid-1)場合は、データベースが正常に作成されていない
return false,"database"
end
return true
end
def self.list(mode)
if (mode == "all") then
return SQL.sql("select name from pkg")
end
end
end
|
Java
|
#!/usr/bin/env python
#*********************************************************************
# Software License Agreement (BSD License)
#
# Copyright (c) 2011 andrewtron3000
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of the Willow Garage nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#********************************************************************/
import roslib; roslib.load_manifest('face_detection')
import rospy
import sys
import cv
from cv_bridge import CvBridge
from sensor_msgs.msg import Image
from geometry_msgs.msg import Point
from geometry_msgs.msg import PointStamped
#
# Instantiate a new opencv to ROS bridge adaptor
#
cv_bridge = CvBridge()
#
# Define the callback that will be called when a new image is received.
#
def callback(publisher, coord_publisher, cascade, imagemsg):
#
# Convert the ROS imagemsg to an opencv image.
#
image = cv_bridge.imgmsg_to_cv(imagemsg, 'mono8')
#
# Blur the image.
#
cv.Smooth(image, image, cv.CV_GAUSSIAN)
#
# Allocate some storage for the haar detect operation.
#
storage = cv.CreateMemStorage(0)
#
# Call the face detector function.
#
faces = cv.HaarDetectObjects(image, cascade, storage, 1.2, 2,
cv.CV_HAAR_DO_CANNY_PRUNING, (100,100))
#
# If faces are detected, compute the centroid of all the faces
# combined.
#
face_centroid_x = 0.0
face_centroid_y = 0.0
if len(faces) > 0:
#
# For each face, draw a rectangle around it in the image,
# and also add the position of the face to the centroid
# of all faces combined.
#
for (i, n) in faces:
x = int(i[0])
y = int(i[1])
width = int(i[2])
height = int(i[3])
cv.Rectangle(image,
(x, y),
(x + width, y + height),
cv.CV_RGB(0,255,0), 3, 8, 0)
face_centroid_x += float(x) + (float(width) / 2.0)
face_centroid_y += float(y) + (float(height) / 2.0)
#
# Finish computing the face_centroid by dividing by the
# number of faces found above.
#
face_centroid_x /= float(len(faces))
face_centroid_y /= float(len(faces))
#
# Lastly, if faces were detected, publish a PointStamped
# message that contains the centroid values.
#
pt = Point(x = face_centroid_x, y = face_centroid_y, z = 0.0)
pt_stamped = PointStamped(point = pt)
coord_publisher.publish(pt_stamped)
#
# Convert the opencv image back to a ROS image using the
# cv_bridge.
#
newmsg = cv_bridge.cv_to_imgmsg(image, 'mono8')
#
# Republish the image. Note this image has boxes around
# faces if faces were found.
#
publisher.publish(newmsg)
def listener(publisher, coord_publisher):
rospy.init_node('face_detector', anonymous=True)
#
# Load the haar cascade. Note we get the
# filename from the "classifier" parameter
# that is configured in the launch script.
#
cascadeFileName = rospy.get_param("~classifier")
cascade = cv.Load(cascadeFileName)
rospy.Subscriber("/stereo/left/image_rect",
Image,
lambda image: callback(publisher, coord_publisher, cascade, image))
rospy.spin()
# This is called first.
if __name__ == '__main__':
publisher = rospy.Publisher('face_view', Image)
coord_publisher = rospy.Publisher('face_coords', PointStamped)
listener(publisher, coord_publisher)
|
Java
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import urllib
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from jp.ac.kyoto_su.aokilab.dragon.mvc.model import OpenGLModel
from jp.ac.kyoto_su.aokilab.dragon.mvc.view import *
from jp.ac.kyoto_su.aokilab.dragon.opengl.triangle import OpenGLTriangle
from jp.ac.kyoto_su.aokilab.dragon.opengl.polygon import OpenGLPolygon
TRACE = True
DEBUG = False
class DragonModel(OpenGLModel):
"""ドラゴンのモデル。"""
def __init__(self):
"""ドラゴンのモデルのコンストラクタ。"""
if TRACE: print(__name__), self.__init__.__doc__
super(DragonModel, self).__init__()
self._eye_point = [-5.5852450791872 , 3.07847342734 , 15.794105252496]
self._sight_point = [0.27455347776413 , 0.20096999406815 , -0.11261999607086]
self._up_vector = [0.1018574904194 , 0.98480906061847 , -0.14062775604137]
self._fovy = self._default_fovy = 12.642721790235
filename = os.path.join(os.getcwd(), 'dragon.txt')
if os.path.exists(filename) and os.path.isfile(filename):
pass
else:
url = 'http://www.cc.kyoto-su.ac.jp/~atsushi/Programs/Dragon/dragon.txt'
urllib.urlretrieve(url, filename)
with open(filename, "rU") as a_file:
while True:
a_string = a_file.readline()
if len(a_string) == 0: break
a_list = a_string.split()
if len(a_list) == 0: continue
first_string = a_list[0]
if first_string == "number_of_vertexes":
number_of_vertexes = int(a_list[1])
if first_string == "number_of_triangles":
number_of_triangles = int(a_list[1])
if first_string == "end_header":
get_tokens = (lambda file: file.readline().split())
collection_of_vertexes = []
for n_th in range(number_of_vertexes):
a_list = get_tokens(a_file)
a_vertex = map(float, a_list[0:3])
collection_of_vertexes.append(a_vertex)
index_to_vertex = (lambda index: collection_of_vertexes[index-1])
for n_th in range(number_of_triangles):
a_list = get_tokens(a_file)
indexes = map(int, a_list[0:3])
vertexes = map(index_to_vertex, indexes)
a_tringle = OpenGLTriangle(*vertexes)
self._display_object.append(a_tringle)
return
def default_window_title(self):
"""ドラゴンのウィンドウのタイトル(ラベル)を応答する。"""
if TRACE: print(__name__), self.default_window_title.__doc__
return "Dragon"
class WaspModel(OpenGLModel):
"""スズメバチのモデル。"""
def __init__(self):
"""スズメバチのモデルのコンストラクタ。"""
if TRACE: print(__name__), self.__init__.__doc__
super(WaspModel, self).__init__()
self._eye_point = [-5.5852450791872 , 3.07847342734 , 15.794105252496]
self._sight_point = [0.19825005531311 , 1.8530999422073 , -0.63795006275177]
self._up_vector = [0.070077999093727 , 0.99630606032682 , -0.049631725731267]
self._fovy = self._default_fovy = 41.480099231656
filename = os.path.join(os.getcwd(), 'wasp.txt')
if os.path.exists(filename) and os.path.isfile(filename):
pass
else:
url = 'http://www.cc.kyoto-su.ac.jp/~atsushi/Programs/Wasp/wasp.txt'
urllib.urlretrieve(url, filename)
with open(filename, "rU") as a_file:
while True:
a_string = a_file.readline()
if len(a_string) == 0: break
a_list = a_string.split()
if len(a_list) == 0: continue
first_string = a_list[0]
if first_string == "number_of_vertexes":
number_of_vertexes = int(a_list[1])
if first_string == "number_of_polygons":
number_of_polygons = int(a_list[1])
if first_string == "end_header":
get_tokens = (lambda file: file.readline().split())
collection_of_vertexes = []
for n_th in range(number_of_vertexes):
a_list = get_tokens(a_file)
a_vertex = map(float, a_list[0:3])
collection_of_vertexes.append(a_vertex)
index_to_vertex = (lambda index: collection_of_vertexes[index-1])
for n_th in range(number_of_polygons):
a_list = get_tokens(a_file)
number_of_indexes = int(a_list[0])
index = number_of_indexes + 1
indexes = map(int, a_list[1:index])
vertexes = map(index_to_vertex, indexes)
rgb_color = map(float, a_list[index:index+3])
a_polygon = OpenGLPolygon(vertexes, rgb_color)
self._display_object.append(a_polygon)
return
def default_view_class(self):
"""スズメバチのモデルを表示するデフォルトのビューのクラスを応答する。"""
if TRACE: print(__name__), self.default_view_class.__doc__
return WaspView
def default_window_title(self):
"""スズメバチのウィンドウのタイトル(ラベル)を応答する。"""
if TRACE: print(__name__), self.default_window_title.__doc__
return "Wasp"
class BunnyModel(OpenGLModel):
"""うさぎのモデル。"""
def __init__(self):
"""うさぎのモデルのコンストラクタ。"""
if TRACE: print(__name__), self.__init__.__doc__
super(BunnyModel, self).__init__()
filename = os.path.join(os.getcwd(), 'bunny.ply')
if os.path.exists(filename) and os.path.isfile(filename):
pass
else:
url = 'http://www.cc.kyoto-su.ac.jp/~atsushi/Programs/Bunny/bunny.ply'
urllib.urlretrieve(url, filename)
with open(filename, "rU") as a_file:
while True:
a_string = a_file.readline()
if len(a_string) == 0: break
a_list = a_string.split()
if len(a_list) == 0: continue
first_string = a_list[0]
if first_string == "element":
second_string = a_list[1]
if second_string == "vertex":
number_of_vertexes = int(a_list[2])
if second_string == "face":
number_of_faces = int(a_list[2])
if first_string == "end_header":
get_tokens = (lambda file: file.readline().split())
collection_of_vertexes = []
for n_th in range(number_of_vertexes):
a_list = get_tokens(a_file)
a_vertex = map(float, a_list[0:3])
collection_of_vertexes.append(a_vertex)
index_to_vertex = (lambda index: collection_of_vertexes[index])
for n_th in range(number_of_faces):
a_list = get_tokens(a_file)
indexes = map(int, a_list[1:4])
vertexes = map(index_to_vertex, indexes)
a_tringle = OpenGLTriangle(*vertexes)
self._display_object.append(a_tringle)
if first_string == "comment":
second_string = a_list[1]
if second_string == "eye_point_xyz":
self._eye_point = map(float, a_list[2:5])
if second_string == "sight_point_xyz":
self._sight_point = map(float, a_list[2:5])
if second_string == "up_vector_xyz":
self._up_vector = map(float, a_list[2:5])
if second_string == "zoom_height" and a_list[3] == "fovy":
self._fovy = self._default_fovy = float(a_list[4])
return
def default_view_class(self):
"""うさぎのモデルを表示するデフォルトのビューのクラスを応答する。"""
if TRACE: print(__name__), self.default_view_class.__doc__
return BunnyView
def default_window_title(self):
"""うさぎのウィンドウのタイトル(ラベル)を応答する。"""
if TRACE: print(__name__), self.default_window_title.__doc__
return "Stanford Bunny"
# end of file
|
Java
|
# Copyright 2015-2017 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
from lino.core.roles import UserRole
class SimpleContactsUser(UserRole):
pass
class ContactsUser(SimpleContactsUser):
pass
class ContactsStaff(ContactsUser):
pass
|
Java
|
/*
* block.h -- block transfer
*
* Copyright (C) 2010-2012,2014-2015 Olaf Bergmann <bergmann@tzi.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP library libcoap. Please see README for terms
* of use.
*/
#ifndef COAP_BLOCK_H_
#define COAP_BLOCK_H_
#include "encode.h"
#include "option.h"
#include "pdu.h"
/**
* @defgroup block Block Transfer
* API functions for handling PDUs using CoAP BLOCK options
* @{
*/
#ifndef COAP_MAX_BLOCK_SZX
/**
* The largest value for the SZX component in a Block option.
*/
#define COAP_MAX_BLOCK_SZX 6
#endif /* COAP_MAX_BLOCK_SZX */
/**
* Structure of Block options.
*/
typedef struct {
unsigned int num; /**< block number */
unsigned int m:1; /**< 1 if more blocks follow, 0 otherwise */
unsigned int szx:3; /**< block size */
} coap_block_t;
#define COAP_BLOCK_USE_LIBCOAP 0x01 /* Use libcoap to do block requests */
#define COAP_BLOCK_SINGLE_BODY 0x02 /* Deliver the data as a single body */
/**
* Returns the value of the least significant byte of a Block option @p opt.
* For zero-length options (i.e. num == m == szx == 0), COAP_OPT_BLOCK_LAST
* returns @c NULL.
*/
#define COAP_OPT_BLOCK_LAST(opt) \
(coap_opt_length(opt) ? (coap_opt_value(opt) + (coap_opt_length(opt)-1)) : 0)
/** Returns the value of the More-bit of a Block option @p opt. */
#define COAP_OPT_BLOCK_MORE(opt) \
(coap_opt_length(opt) ? (*COAP_OPT_BLOCK_LAST(opt) & 0x08) : 0)
/** Returns the value of the SZX-field of a Block option @p opt. */
#define COAP_OPT_BLOCK_SZX(opt) \
(coap_opt_length(opt) ? (*COAP_OPT_BLOCK_LAST(opt) & 0x07) : 0)
/**
* Returns the value of field @c num in the given block option @p block_opt.
*/
unsigned int coap_opt_block_num(const coap_opt_t *block_opt);
/**
* Checks if more than @p num blocks are required to deliver @p data_len
* bytes of data for a block size of 1 << (@p szx + 4).
*/
COAP_STATIC_INLINE int
coap_more_blocks(size_t data_len, unsigned int num, uint16_t szx) {
return ((num+1) << (szx + 4)) < data_len;
}
#if 0
/** Sets the More-bit in @p block_opt */
COAP_STATIC_INLINE void
coap_opt_block_set_m(coap_opt_t *block_opt, int m) {
if (m)
*(coap_opt_value(block_opt) + (coap_opt_length(block_opt) - 1)) |= 0x08;
else
*(coap_opt_value(block_opt) + (coap_opt_length(block_opt) - 1)) &= ~0x08;
}
#endif
/**
* Initializes @p block from @p pdu. @p number must be either COAP_OPTION_BLOCK1
* or COAP_OPTION_BLOCK2. When option @p number was found in @p pdu, @p block is
* initialized with values from this option and the function returns the value
* @c 1. Otherwise, @c 0 is returned.
*
* @param pdu The pdu to search for option @p number.
* @param number The option number to search for (must be COAP_OPTION_BLOCK1 or
* COAP_OPTION_BLOCK2).
* @param block The block structure to initilize.
*
* @return @c 1 on success, @c 0 otherwise.
*/
int coap_get_block(const coap_pdu_t *pdu, coap_option_num_t number,
coap_block_t *block);
/**
* Writes a block option of type @p number to message @p pdu. If the requested
* block size is too large to fit in @p pdu, it is reduced accordingly. An
* exception is made for the final block when less space is required. The actual
* length of the resource is specified in @p data_length.
*
* This function may change *block to reflect the values written to @p pdu. As
* the function takes into consideration the remaining space @p pdu, no more
* options should be added after coap_write_block_opt() has returned.
*
* @param block The block structure to use. On return, this object is
* updated according to the values that have been written to
* @p pdu.
* @param number COAP_OPTION_BLOCK1 or COAP_OPTION_BLOCK2.
* @param pdu The message where the block option should be written.
* @param data_length The length of the actual data that will be added the @p
* pdu by calling coap_add_block().
*
* @return @c 1 on success, or a negative value on error.
*/
int coap_write_block_opt(coap_block_t *block,
coap_option_num_t number,
coap_pdu_t *pdu,
size_t data_length);
/**
* Adds the @p block_num block of size 1 << (@p block_szx + 4) from source @p
* data to @p pdu.
*
* @param pdu The message to add the block.
* @param len The length of @p data.
* @param data The source data to fill the block with.
* @param block_num The actual block number.
* @param block_szx Encoded size of block @p block_number.
*
* @return @c 1 on success, @c 0 otherwise.
*/
int coap_add_block(coap_pdu_t *pdu,
size_t len,
const uint8_t *data,
unsigned int block_num,
unsigned char block_szx);
/**
* Re-assemble payloads into a body
*
* @param body_data The pointer to the data for the body holding the
* representation so far or NULL if the first time.
* @param length The length of @p data.
* @param data The payload data to update the body with.
* @param offset The offset of the @p data into the body.
* @param total The estimated total size of the body.
*
* @return The current representation of the body or @c NULL if error.
* If NULL, @p body_data will have been de-allocated.
*/
coap_binary_t *
coap_block_build_body(coap_binary_t *body_data, size_t length,
const uint8_t *data, size_t offset, size_t total);
/**
* Adds the appropriate part of @p data to the @p response pdu. If blocks are
* required, then the appropriate block will be added to the PDU and sent.
* Adds a ETAG option that is the hash of the entire data if the data is to be
* split into blocks
* Used by a request handler.
*
* Note: The application will get called for every packet of a large body to
* process. Consider using coap_add_data_response_large() instead.
*
* @param request The requesting pdu.
* @param response The response pdu.
* @param media_type The format of the data.
* @param maxage The maxmimum life of the data. If @c -1, then there
* is no maxage.
* @param length The total length of the data.
* @param data The entire data block to transmit.
*
*/
void
coap_add_data_blocked_response(const coap_pdu_t *request,
coap_pdu_t *response,
uint16_t media_type,
int maxage,
size_t length,
const uint8_t* data);
/**
* Callback handler for de-allocating the data based on @p app_ptr provided to
* coap_add_data_large_*() functions following transmission of the supplied
* data.
*
* @param session The session that this data is associated with
* @param app_ptr The application provided pointer provided to the
* coap_add_data_large_* functions.
*/
typedef void (*coap_release_large_data_t)(coap_session_t *session,
void *app_ptr);
/**
* Associates given data with the @p pdu that is passed as second parameter.
*
* If all the data can be transmitted in a single PDU, this is functionally
* the same as coap_add_data() except @p release_func (if not NULL) will get
* invoked after data transmission.
*
* Used for a client request.
*
* If the data spans multiple PDUs, then the data will get transmitted using
* BLOCK1 option with the addition of the SIZE1 option.
* The underlying library will handle the transmission of the individual blocks.
* Once the body of data has been transmitted (or a failure occurred), then
* @p release_func (if not NULL) will get called so the application can
* de-allocate the @p data based on @p app_data. It is the responsibility of
* the application not to change the contents of @p data until the data
* transfer has completed.
*
* There is no need for the application to include the BLOCK1 option in the
* @p pdu.
*
* coap_add_data_large_request() (or the alternative coap_add_data_large_*()
* functions) must be called only once per PDU and must be the last PDU update
* before the PDU is transmitted. The (potentially) initial data will get
* transmitted when coap_send() is invoked.
*
* Note: COAP_BLOCK_USE_LIBCOAP must be set by coap_context_set_block_mode()
* for libcoap to work correctly when using this function.
*
* @param session The session to associate the data with.
* @param pdu The PDU to associate the data with.
* @param length The length of data to transmit.
* @param data The data to transmit.
* @param release_func The function to call to de-allocate @p data or @c NULL
* if the function is not required.
* @param app_ptr A Pointer that the application can provide for when
* release_func() is called.
*
* @return @c 1 if addition is successful, else @c 0.
*/
int coap_add_data_large_request(coap_session_t *session,
coap_pdu_t *pdu,
size_t length,
const uint8_t *data,
coap_release_large_data_t release_func,
void *app_ptr);
/**
* Associates given data with the @p response pdu that is passed as fourth
* parameter.
*
* If all the data can be transmitted in a single PDU, this is functionally
* the same as coap_add_data() except @p release_func (if not NULL) will get
* invoked after data transmission. The MEDIA_TYPE, MAXAGE and ETAG options may
* be added in as appropriate.
*
* Used by a server request handler to create the response.
*
* If the data spans multiple PDUs, then the data will get transmitted using
* BLOCK2 (response) option with the addition of the SIZE2 and ETAG
* options. The underlying library will handle the transmission of the
* individual blocks. Once the body of data has been transmitted (or a
* failure occurred), then @p release_func (if not NULL) will get called so the
* application can de-allocate the @p data based on @p app_data. It is the
* responsibility of the application not to change the contents of @p data
* until the data transfer has completed.
*
* There is no need for the application to include the BLOCK2 option in the
* @p pdu.
*
* coap_add_data_large_response() (or the alternative coap_add_data_large*()
* functions) must be called only once per PDU and must be the last PDU update
* before returning from the request handler function.
*
* Note: COAP_BLOCK_USE_LIBCOAP must be set by coap_context_set_block_mode()
* for libcoap to work correctly when using this function.
*
* @param resource The resource the data is associated with.
* @param session The coap session.
* @param request The requesting pdu.
* @param response The response pdu.
* @param query The query taken from the (original) requesting pdu.
* @param media_type The format of the data.
* @param maxage The maxmimum life of the data. If @c -1, then there
* is no maxage.
* @param etag ETag to use if not 0.
* @param length The total length of the data.
* @param data The entire data block to transmit.
* @param release_func The function to call to de-allocate @p data or NULL if
* the function is not required.
* @param app_ptr A Pointer that the application can provide for when
* release_func() is called.
*
* @return @c 1 if addition is successful, else @c 0.
*/
int
coap_add_data_large_response(coap_resource_t *resource,
coap_session_t *session,
const coap_pdu_t *request,
coap_pdu_t *response,
const coap_string_t *query,
uint16_t media_type,
int maxage,
uint64_t etag,
size_t length,
const uint8_t *data,
coap_release_large_data_t release_func,
void *app_ptr);
/**
* Set the context level CoAP block handling bits for handling RFC7959.
* These bits flow down to a session when a session is created and if the peer
* does not support something, an appropriate bit may get disabled in the
* session block_mode.
* The session block_mode then flows down into coap_crcv_t or coap_srcv_t where
* again an appropriate bit may get disabled.
*
* Note: This function must be called before the session is set up.
*
* Note: COAP_BLOCK_USE_LIBCOAP must be set if libcoap is to do all the
* block tracking and requesting, otherwise the application will have to do
* all of this work (the default if coap_context_set_block_mode() is not
* called).
*
* @param context The coap_context_t object.
* @param block_mode Zero or more COAP_BLOCK_ or'd options
*/
void coap_context_set_block_mode(coap_context_t *context,
uint8_t block_mode);
/**
* Cancel an observe that is being tracked by the client large receive logic.
* (coap_context_set_block_mode() has to be called)
* This will trigger the sending of an observe cancel pdu to the server.
*
* @param session The session that is being used for the observe.
* @param token The original token used to initiate the observation.
* @param message_type The COAP_MESSAGE_ type (NON or CON) to send the observe
* cancel pdu as.
*
* @return @c 1 if observe cancel transmission initiation is successful,
* else @c 0.
*/
int coap_cancel_observe(coap_session_t *session, coap_binary_t *token,
coap_pdu_type_t message_type);
/**@}*/
#endif /* COAP_BLOCK_H_ */
|
Java
|
from django.db.models import Transform
from django.db.models import DateTimeField, TimeField
from django.utils.functional import cached_property
class TimeValue(Transform):
lookup_name = 'time'
function = 'time'
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
return 'TIME({})'.format(lhs), params
@cached_property
def output_field(self):
return TimeField()
DateTimeField.register_lookup(TimeValue)
|
Java
|
/*
Copyright (c) 2012, William Magato
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ''AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the copyright holder(s) or contributors.
*/
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
// define function pointer
typedef off64_t (*llamaos_lseek64_t) (int, off64_t, int);
// function pointer variable
static llamaos_lseek64_t llamaos_lseek64 = 0;
// function called by llamaOS to register pointer
void register_llamaos_lseek64 (llamaos_lseek64_t func)
{
llamaos_lseek64 = func;
}
/* Seek to OFFSET on FD, starting from WHENCE. */
off64_t __libc_lseek64 (int fd, off64_t offset, int whence)
{
if (0 != llamaos_lseek64)
{
if (fd < 0)
{
__set_errno (EBADF);
return -1;
}
switch (whence)
{
case SEEK_SET:
case SEEK_CUR:
case SEEK_END:
break;
default:
__set_errno (EINVAL);
return -1;
}
return llamaos_lseek64 (fd, offset, whence);
}
__set_errno (ENOSYS);
return -1;
}
weak_alias (__libc_lseek64, __lseek64)
weak_alias (__libc_lseek64, lseek64)
|
Java
|
<?php
header('Content-Type: text/html; charset=utf-8');
require_once 'Akna.php';
$user = '';
$pass = '';
$akna = new Akna( $user, $pass );
$contacts = $akna->emailMarketing->contacts;
$messages = $akna->emailMarketing->messages;
$campaigns = $akna->emailMarketing->campaigns;
try {
// $result_1 = $contacts->get('daniel@apiki.com', 'Apiki 1');
// var_dump($result_1);
// $result_2 = $contacts->getLists();
// var_dump($result_2);
// $result_3 = $messages->create( array(
// 'nome' => 'Teste',
// 'html' => htmlspecialchars( '<h1>Curso à distância</h1>' )
// ) );
// var_dump($result_3);
// $result_4 = $messages->test( array(
// 'titulo' => 'Teste',
// 'email_remetente' => 'daniel.antunes.rocha@gmail.com',
// 'assunto' => 'Teste de envio 15.07',
// 'email' => 'daniel@apiki.com'
// ) );
// var_dump($result_4);
// $result_5 = $campaigns->addAction( array(
// 'nome' => 'Itaú 6',
// 'mensagem' => 'Teste',
// 'data_encerramento' => '2013-07-30',
// 'nome_remetente' => 'CESP - Relações com Investidores',
// 'email_remetente' => 'firb.cesp@firb.com',
// 'email_retorno' => 'firb.cesp@firb.com',
// 'assunto' => 'Assunto 1',
// 'lista' => array( 'Apiki 1', 'Apiki 2' ),
// 'agendar' => array( 'datahora' => date( 'Y-m-d H:i:s' ) )
// ) );
// var_dump($result_5);
} catch( Akna_Exception $e ){
echo $e->getmessage();
}
|
Java
|
/*
* Copyright 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.initialization;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.gradle.api.internal.project.ProjectIdentifier;
import org.gradle.api.internal.project.ProjectRegistry;
import org.gradle.api.InvalidUserDataException;
import java.io.File;
import java.io.Serializable;
public class ProjectDirectoryProjectSpec extends AbstractProjectSpec implements Serializable {
private final File dir;
public ProjectDirectoryProjectSpec(File dir) {
this.dir = dir;
}
public String getDisplayName() {
return String.format("with project directory '%s'", dir);
}
public boolean isCorresponding(File file) {
return dir.equals(file);
}
protected String formatNoMatchesMessage() {
return String.format("No projects in this build have project directory '%s'.", dir);
}
protected String formatMultipleMatchesMessage(Iterable<? extends ProjectIdentifier> matches) {
return String.format("Multiple projects in this build have project directory '%s': %s", dir, matches);
}
protected boolean select(ProjectIdentifier project) {
return project.getProjectDir().equals(dir);
}
@Override
protected void checkPreconditions(ProjectRegistry<?> registry) {
if (!dir.exists()) {
throw new InvalidUserDataException(String.format("Project directory '%s' does not exist.", dir));
}
if (!dir.isDirectory()) {
throw new InvalidUserDataException(String.format("Project directory '%s' is not a directory.", dir));
}
}
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
|
Java
|
// Copyright 2014 David Miller. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sequtil
import (
"errors"
"github.com/dmiller/go-seq/iseq"
"github.com/dmiller/go-seq/murmur3"
//"fmt"
"math"
"reflect"
)
// Hash returns a hash code for an object.
// Uses iseq.Hashable.Hash if the interface is implemented.
// Otherwise, special cases Go numbers and strings.
// Returns a default value if not covered by these cases.
// Returning a default value is really not good for hashing performance.
// But it is one way not to have an error code and to avoid a panic.
// Use IsHashable to determine if Hash is supported.
// Or call HashE which has an error return.
func Hash(v interface{}) uint32 {
h, err := HashE(v)
if err != nil {
return 0
}
return h
}
// HashE returns a hash code for an object.
// Uses iseq.Hashable.Hash if the interface is implemented.
// It special cases Go numbers and strings.
// Returns an error if the object is not covered by these cases.
func HashE(v interface{}) (uint32, error) {
if h, ok := v.(iseq.Hashable); ok {
return h.Hash(), nil
}
switch v := v.(type) {
case bool, int, int8, int32, int64:
return murmur3.HashUInt64(uint64(reflect.ValueOf(v).Int())), nil
case uint, uint8, uint32, uint64:
return murmur3.HashUInt64(uint64(reflect.ValueOf(v).Uint())), nil
case float32, float64:
return murmur3.HashUInt64(math.Float64bits(reflect.ValueOf(v).Float())), nil
case nil:
return murmur3.HashUInt64(0), nil
case string:
return murmur3.HashString(v), nil
case complex64, complex128:
return HashComplex128(v.(complex128)), nil
}
return 0, errors.New("don't know how to hash")
}
// IsHashable returns true if Hash/HashE can compute a hash for this object.
func IsHashable(v interface{}) bool {
if _, ok := v.(iseq.Hashable); ok {
return true
}
switch v.(type) {
case bool, int, int8, int32, int64,
uint, uint8, uint32, uint64,
float32, float64,
nil,
string,
complex64, complex128:
return true
}
return false
}
// HashSeq computes a hash for an iseq.Seq
func HashSeq(s iseq.Seq) uint32 {
return HashOrdered(s)
}
// HashMap computes a hash for an iseq.PMap
func HashMap(m iseq.PMap) uint32 {
return HashUnordered(m.Seq())
}
// HashOrdered computes a hash for an iseq.Seq, where order is important
func HashOrdered(s iseq.Seq) uint32 {
n := int32(0)
hash := uint32(1)
for ; s != nil; s = s.Next() {
hash = 31*hash + Hash(s.First)
n++
}
return murmur3.FinalizeCollHash(hash, n)
}
// HashUnordered computes a hash for an iseq.Seq, independent of order of elements
func HashUnordered(s iseq.Seq) uint32 {
n := int32(0)
hash := uint32(0)
for ; s != nil; s = s.Next() {
hash += Hash(s.First)
n++
}
return murmur3.FinalizeCollHash(hash, n)
}
// HashComplex128 computes a hash for a complex128
func HashComplex128(c complex128) uint32 {
hash := murmur3.MixHash(
murmur3.HashUInt64(math.Float64bits(real(c))),
murmur3.HashUInt64(math.Float64bits(imag(c))))
return murmur3.Finalize(hash, 2)
}
|
Java
|
// Copyright (C) 2016 André Bargull. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-white-space
description: >
Mongolian Vowel Separator is not recognized as white space.
info: |
11.2 White Space
WhiteSpace ::
<TAB>
<VT>
<FF>
<SP>
<NBSP>
<ZWNBSP>
<USP>
<USP> ::
Other category “Zs” code points
General Category of U+180E is “Cf” (Format).
negative:
phase: parse
type: SyntaxError
features: [u180e]
---*/
throw "Test262: This statement should not be evaluated.";
// U+180E between "var" and "foo"; UTF8(0x180E) = 0xE1 0xA0 0x8E
varfoo;
|
Java
|
/*
* Copyright (C) 2006, 2007, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "AffineTransform.h"
#include "CanvasPathMethods.h"
#include "CanvasRenderingContext.h"
#include "CanvasStyle.h"
#include "Color.h"
#include "FloatSize.h"
#include "FontCascade.h"
#include "FontSelectorClient.h"
#include "GraphicsContext.h"
#include "GraphicsTypes.h"
#include "ImageBuffer.h"
#include "Path.h"
#include "PlatformLayer.h"
#include "TextFlags.h"
#include <wtf/Vector.h>
#include <wtf/text/WTFString.h>
namespace WebCore {
class CanvasGradient;
class CanvasPattern;
class DOMPath;
class FloatRect;
class GraphicsContext;
class HTMLCanvasElement;
class HTMLImageElement;
class HTMLVideoElement;
class ImageData;
class TextMetrics;
typedef int ExceptionCode;
class CanvasRenderingContext2D final : public CanvasRenderingContext, public CanvasPathMethods {
public:
CanvasRenderingContext2D(HTMLCanvasElement*, bool usesCSSCompatibilityParseMode, bool usesDashboardCompatibilityMode);
virtual ~CanvasRenderingContext2D();
const CanvasStyle& strokeStyle() const { return state().strokeStyle; }
void setStrokeStyle(CanvasStyle);
const CanvasStyle& fillStyle() const { return state().fillStyle; }
void setFillStyle(CanvasStyle);
float lineWidth() const;
void setLineWidth(float);
String lineCap() const;
void setLineCap(const String&);
String lineJoin() const;
void setLineJoin(const String&);
float miterLimit() const;
void setMiterLimit(float);
const Vector<float>& getLineDash() const;
void setLineDash(const Vector<float>&);
void setWebkitLineDash(const Vector<float>&);
float lineDashOffset() const;
void setLineDashOffset(float);
float webkitLineDashOffset() const;
void setWebkitLineDashOffset(float);
float shadowOffsetX() const;
void setShadowOffsetX(float);
float shadowOffsetY() const;
void setShadowOffsetY(float);
float shadowBlur() const;
void setShadowBlur(float);
String shadowColor() const;
void setShadowColor(const String&);
float globalAlpha() const;
void setGlobalAlpha(float);
String globalCompositeOperation() const;
void setGlobalCompositeOperation(const String&);
void save() { ++m_unrealizedSaveCount; }
void restore();
void scale(float sx, float sy);
void rotate(float angleInRadians);
void translate(float tx, float ty);
void transform(float m11, float m12, float m21, float m22, float dx, float dy);
void setTransform(float m11, float m12, float m21, float m22, float dx, float dy);
void setStrokeColor(const String& color, Optional<float> alpha = Nullopt);
void setStrokeColor(float grayLevel, float alpha = 1.0);
void setStrokeColor(float r, float g, float b, float a);
void setStrokeColor(float c, float m, float y, float k, float a);
void setFillColor(const String& color, Optional<float> alpha = Nullopt);
void setFillColor(float grayLevel, float alpha = 1.0f);
void setFillColor(float r, float g, float b, float a);
void setFillColor(float c, float m, float y, float k, float a);
void beginPath();
enum class WindingRule { Nonzero, Evenodd };
void fill(WindingRule = WindingRule::Nonzero);
void stroke();
void clip(WindingRule = WindingRule::Nonzero);
void fill(DOMPath&, WindingRule = WindingRule::Nonzero);
void stroke(DOMPath&);
void clip(DOMPath&, WindingRule = WindingRule::Nonzero);
bool isPointInPath(float x, float y, WindingRule = WindingRule::Nonzero);
bool isPointInStroke(float x, float y);
bool isPointInPath(DOMPath&, float x, float y, WindingRule = WindingRule::Nonzero);
bool isPointInStroke(DOMPath&, float x, float y);
void clearRect(float x, float y, float width, float height);
void fillRect(float x, float y, float width, float height);
void strokeRect(float x, float y, float width, float height);
void setShadow(float width, float height, float blur, const String& color = String(), Optional<float> alpha = Nullopt);
void setShadow(float width, float height, float blur, float grayLevel, float alpha = 1.0);
void setShadow(float width, float height, float blur, float r, float g, float b, float a);
void setShadow(float width, float height, float blur, float c, float m, float y, float k, float a);
void clearShadow();
void drawImage(HTMLImageElement&, float x, float y, ExceptionCode&);
void drawImage(HTMLImageElement&, float x, float y, float width, float height, ExceptionCode&);
void drawImage(HTMLImageElement&, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh, ExceptionCode&);
void drawImage(HTMLImageElement&, const FloatRect& srcRect, const FloatRect& dstRect, ExceptionCode&);
void drawImage(HTMLCanvasElement&, float x, float y, ExceptionCode&);
void drawImage(HTMLCanvasElement&, float x, float y, float width, float height, ExceptionCode&);
void drawImage(HTMLCanvasElement&, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh, ExceptionCode&);
void drawImage(HTMLCanvasElement&, const FloatRect& srcRect, const FloatRect& dstRect, ExceptionCode&);
void drawImage(HTMLImageElement&, const FloatRect& srcRect, const FloatRect& dstRect, const CompositeOperator&, const BlendMode&, ExceptionCode&);
#if ENABLE(VIDEO)
void drawImage(HTMLVideoElement&, float x, float y, ExceptionCode&);
void drawImage(HTMLVideoElement&, float x, float y, float width, float height, ExceptionCode&);
void drawImage(HTMLVideoElement&, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh, ExceptionCode&);
void drawImage(HTMLVideoElement&, const FloatRect& srcRect, const FloatRect& dstRect, ExceptionCode&);
#endif
void drawImageFromRect(HTMLImageElement&, float sx = 0, float sy = 0, float sw = 0, float sh = 0,
float dx = 0, float dy = 0, float dw = 0, float dh = 0, const String& compositeOperation = emptyString());
void setAlpha(float);
void setCompositeOperation(const String&);
RefPtr<CanvasGradient> createLinearGradient(float x0, float y0, float x1, float y1, ExceptionCode&);
RefPtr<CanvasGradient> createRadialGradient(float x0, float y0, float r0, float x1, float y1, float r1, ExceptionCode&);
RefPtr<CanvasPattern> createPattern(HTMLImageElement&, const String& repetitionType, ExceptionCode&);
RefPtr<CanvasPattern> createPattern(HTMLCanvasElement&, const String& repetitionType, ExceptionCode&);
#if ENABLE(VIDEO)
RefPtr<CanvasPattern> createPattern(HTMLVideoElement&, const String& repetitionType, ExceptionCode&);
#endif
RefPtr<ImageData> createImageData(RefPtr<ImageData>&&, ExceptionCode&) const;
RefPtr<ImageData> createImageData(float width, float height, ExceptionCode&) const;
RefPtr<ImageData> getImageData(float sx, float sy, float sw, float sh, ExceptionCode&) const;
RefPtr<ImageData> webkitGetImageDataHD(float sx, float sy, float sw, float sh, ExceptionCode&) const;
void putImageData(ImageData&, float dx, float dy, ExceptionCode&);
void putImageData(ImageData&, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight, ExceptionCode&);
void webkitPutImageDataHD(ImageData&, float dx, float dy, ExceptionCode&);
void webkitPutImageDataHD(ImageData&, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight, ExceptionCode&);
void drawFocusIfNeeded(Element*);
void drawFocusIfNeeded(DOMPath&, Element*);
float webkitBackingStorePixelRatio() const { return 1; }
void reset();
String font() const;
void setFont(const String&);
String textAlign() const;
void setTextAlign(const String&);
String textBaseline() const;
void setTextBaseline(const String&);
String direction() const;
void setDirection(const String&);
void fillText(const String& text, float x, float y, Optional<float> maxWidth = Nullopt);
void strokeText(const String& text, float x, float y, Optional<float> maxWidth = Nullopt);
Ref<TextMetrics> measureText(const String& text);
LineCap getLineCap() const { return state().lineCap; }
LineJoin getLineJoin() const { return state().lineJoin; }
bool imageSmoothingEnabled() const;
void setImageSmoothingEnabled(bool);
enum class ImageSmoothingQuality { Low, Medium, High };
ImageSmoothingQuality imageSmoothingQuality() const;
void setImageSmoothingQuality(ImageSmoothingQuality);
bool usesDisplayListDrawing() const { return m_usesDisplayListDrawing; };
void setUsesDisplayListDrawing(bool flag) { m_usesDisplayListDrawing = flag; };
bool tracksDisplayListReplay() const { return m_tracksDisplayListReplay; }
void setTracksDisplayListReplay(bool);
String displayListAsText(DisplayList::AsTextFlags) const;
String replayDisplayListAsText(DisplayList::AsTextFlags) const;
private:
enum class Direction {
Inherit,
RTL,
LTR
};
class FontProxy : public FontSelectorClient {
public:
FontProxy() = default;
virtual ~FontProxy();
FontProxy(const FontProxy&);
FontProxy& operator=(const FontProxy&);
bool realized() const { return m_font.fontSelector(); }
void initialize(FontSelector&, const RenderStyle&);
FontMetrics fontMetrics() const;
const FontCascadeDescription& fontDescription() const;
float width(const TextRun&) const;
void drawBidiText(GraphicsContext&, const TextRun&, const FloatPoint&, FontCascade::CustomFontNotReadyAction) const;
private:
void update(FontSelector&);
void fontsNeedUpdate(FontSelector&) override;
FontCascade m_font;
};
struct State final {
State();
State(const State&);
State& operator=(const State&);
String unparsedStrokeColor;
String unparsedFillColor;
CanvasStyle strokeStyle;
CanvasStyle fillStyle;
float lineWidth;
LineCap lineCap;
LineJoin lineJoin;
float miterLimit;
FloatSize shadowOffset;
float shadowBlur;
RGBA32 shadowColor;
float globalAlpha;
CompositeOperator globalComposite;
BlendMode globalBlend;
AffineTransform transform;
bool hasInvertibleTransform;
Vector<float> lineDash;
float lineDashOffset;
bool imageSmoothingEnabled;
ImageSmoothingQuality imageSmoothingQuality;
// Text state.
TextAlign textAlign;
TextBaseline textBaseline;
Direction direction;
String unparsedFont;
FontProxy font;
};
enum CanvasDidDrawOption {
CanvasDidDrawApplyNone = 0,
CanvasDidDrawApplyTransform = 1,
CanvasDidDrawApplyShadow = 1 << 1,
CanvasDidDrawApplyClip = 1 << 2,
CanvasDidDrawApplyAll = 0xffffffff
};
State& modifiableState() { ASSERT(!m_unrealizedSaveCount); return m_stateStack.last(); }
const State& state() const { return m_stateStack.last(); }
void applyLineDash() const;
void setShadow(const FloatSize& offset, float blur, RGBA32 color);
void applyShadow();
bool shouldDrawShadows() const;
void didDraw(const FloatRect&, unsigned options = CanvasDidDrawApplyAll);
void didDrawEntireCanvas();
void paintRenderingResultsToCanvas() override;
GraphicsContext* drawingContext() const;
void unwindStateStack();
void realizeSaves()
{
if (m_unrealizedSaveCount)
realizeSavesLoop();
}
void realizeSavesLoop();
void applyStrokePattern();
void applyFillPattern();
void drawTextInternal(const String& text, float x, float y, bool fill, Optional<float> maxWidth = Nullopt);
// The relationship between FontCascade and CanvasRenderingContext2D::FontProxy must hold certain invariants.
// Therefore, all font operations must pass through the State.
const FontProxy& fontProxy();
#if ENABLE(DASHBOARD_SUPPORT)
void clearPathForDashboardBackwardCompatibilityMode();
#endif
void beginCompositeLayer();
void endCompositeLayer();
void fillInternal(const Path&, WindingRule);
void strokeInternal(const Path&);
void clipInternal(const Path&, WindingRule);
bool isPointInPathInternal(const Path&, float x, float y, WindingRule);
bool isPointInStrokeInternal(const Path&, float x, float y);
void drawFocusIfNeededInternal(const Path&, Element*);
void clearCanvas();
Path transformAreaToDevice(const Path&) const;
Path transformAreaToDevice(const FloatRect&) const;
bool rectContainsCanvas(const FloatRect&) const;
template<class T> IntRect calculateCompositingBufferRect(const T&, IntSize*);
std::unique_ptr<ImageBuffer> createCompositingBuffer(const IntRect&);
void compositeBuffer(ImageBuffer&, const IntRect&, CompositeOperator);
void inflateStrokeRect(FloatRect&) const;
template<class T> void fullCanvasCompositedDrawImage(T&, const FloatRect&, const FloatRect&, CompositeOperator);
void prepareGradientForDashboard(CanvasGradient& gradient) const;
RefPtr<ImageData> getImageData(ImageBuffer::CoordinateSystem, float sx, float sy, float sw, float sh, ExceptionCode&) const;
void putImageData(ImageData&, ImageBuffer::CoordinateSystem, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight, ExceptionCode&);
bool is2d() const override { return true; }
bool isAccelerated() const override;
bool hasInvertibleTransform() const override { return state().hasInvertibleTransform; }
TextDirection toTextDirection(Direction, const RenderStyle** computedStyle = nullptr) const;
#if ENABLE(ACCELERATED_2D_CANVAS)
PlatformLayer* platformLayer() const override;
#endif
Vector<State, 1> m_stateStack;
unsigned m_unrealizedSaveCount { 0 };
bool m_usesCSSCompatibilityParseMode;
#if ENABLE(DASHBOARD_SUPPORT)
bool m_usesDashboardCompatibilityMode;
#endif
bool m_usesDisplayListDrawing { false };
bool m_tracksDisplayListReplay { false };
mutable std::unique_ptr<struct DisplayListDrawingContext> m_recordingContext;
};
} // namespace WebCore
SPECIALIZE_TYPE_TRAITS_CANVASRENDERINGCONTEXT(WebCore::CanvasRenderingContext2D, is2d())
|
Java
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "vm_strings.h"
#include <assert.h>
String *String_alloc(size_t length) {
String *p = (String *)calloc(1, sizeof(String) + (length+1) * sizeof(char));
p->length = length;
return p;
}
String *String_new(char *orig) {
String *s = String_alloc(strlen(orig));
strcpy(s->str, orig);
return s;
}
String *String_dup(String *orig) {
String *s = String_alloc(orig->length);
strcpy(s->str, orig->str);
return s;
}
String *String_from_char(char c) {
char buf[2] = {c, '\0'};
return String_new(buf);
}
String *String_from_int(int value) {
char buf[50];
sprintf(buf,"%d",value);
return String_new(buf);
}
int String_len(String *s) {
if (s == NULL) {
fprintf(stderr, "len() cannot be applied to NULL string object\n");
return -1;
}
return (int)s->length;
}
String *String_add(String *s, String *t) {
if ( s == NULL && t == NULL) {
fprintf(stderr, "Addition Operator cannot be applied to two NULL string objects\n");
return NIL_STRING;
}
if ( s == NULL ) return t; // don't REF/DEREF as we might free our return value
if ( t == NULL ) return s;
size_t n = strlen(s->str) + strlen(t->str);
String *u = String_alloc(n);
strcpy(u->str, s->str);
strcat(u->str, t->str);
return u;
}
bool String_eq(String *s, String *t) {
assert(s);
assert(t);
return strcmp(s->str, t->str) == 0;
}
bool String_neq(String *s, String *t) {
return !String_eq(s,t);
}
bool String_gt(String *s, String *t) {
assert(s);
assert(t);
return strcmp(s->str, t->str) > 0;
}
bool String_ge(String *s, String *t) {
assert(s);
assert(t);
return strcmp(s->str, t->str) >= 0;
}
bool String_lt(String *s, String *t) {
assert(s);
assert(t);
return strcmp(s->str, t->str) < 0;
}
bool String_le(String *s, String *t) {
assert(s);
assert(t);
return strcmp(s->str, t->str) <= 0;
}
|
Java
|
#!/usr/bin/env python
__author__ = 'Adam R. Smith, Michael Meisinger, Dave Foster <dfoster@asascience.com>'
import threading
import traceback
import gevent
from gevent import greenlet, Timeout
from gevent.event import Event, AsyncResult
from gevent.queue import Queue
from pyon.core import MSG_HEADER_ACTOR
from pyon.core.bootstrap import CFG
from pyon.core.exception import IonException, ContainerError
from pyon.core.exception import Timeout as IonTimeout
from pyon.core.thread import PyonThreadManager, PyonThread, ThreadManager, PyonThreadTraceback, PyonHeartbeatError
from pyon.datastore.postgresql.pg_util import init_db_stats, get_db_stats, clear_db_stats
from pyon.ion.service import BaseService
from pyon.util.containers import get_ion_ts, get_ion_ts_millis
from pyon.util.log import log
STAT_INTERVAL_LENGTH = 60000 # Interval time for process saturation stats collection
stats_callback = None
class OperationInterruptedException(BaseException):
"""
Interrupted exception. Used by external items timing out execution in the
IonProcessThread's control thread.
Derived from BaseException to specifically avoid try/except Exception blocks,
such as in Publisher's publish_event.
"""
pass
class IonProcessError(StandardError):
pass
class IonProcessThread(PyonThread):
"""
The control part of an ION process.
"""
def __init__(self, target=None, listeners=None, name=None, service=None, cleanup_method=None,
heartbeat_secs=10, **kwargs):
"""
Constructs the control part of an ION process.
Used by the container's IonProcessThreadManager, as part of spawn_process.
@param target A callable to run in the PyonThread. If None (typical), will use the target method
defined in this class.
@param listeners A list of listening endpoints attached to this thread.
@param name The name of this ION process.
@param service An instance of the BaseService derived class which contains the business logic for
the ION process.
@param cleanup_method An optional callable to run when the process is stopping. Runs after all other
notify_stop calls have run. Should take one param, this instance.
@param heartbeat_secs Number of seconds to wait in between heartbeats.
"""
self._startup_listeners = listeners or []
self.listeners = []
self._listener_map = {}
self.name = name
self.service = service
self._cleanup_method = cleanup_method
self.thread_manager = ThreadManager(failure_notify_callback=self._child_failed) # bubbles up to main thread manager
self._dead_children = [] # save any dead children for forensics
self._ctrl_thread = None
self._ctrl_queue = Queue()
self._ready_control = Event()
self._errors = []
self._ctrl_current = None # set to the AR generated by _routing_call when in the context of a call
# processing vs idle time (ms)
self._start_time = None
self._proc_time = 0 # busy time since start
self._proc_time_prior = 0 # busy time at the beginning of the prior interval
self._proc_time_prior2 = 0 # busy time at the beginning of 2 interval's ago
self._proc_interval_num = 0 # interval num of last record
# for heartbeats, used to detect stuck processes
self._heartbeat_secs = heartbeat_secs # amount of time to wait between heartbeats
self._heartbeat_stack = None # stacktrace of last heartbeat
self._heartbeat_time = None # timestamp of heart beat last matching the current op
self._heartbeat_op = None # last operation (by AR)
self._heartbeat_count = 0 # number of times this operation has been seen consecutively
self._log_call_exception = CFG.get_safe("container.process.log_exceptions", False)
self._log_call_dbstats = CFG.get_safe("container.process.log_dbstats", False)
self._warn_call_dbstmt_threshold = CFG.get_safe("container.process.warn_dbstmt_threshold", 0)
PyonThread.__init__(self, target=target, **kwargs)
def heartbeat(self):
"""
Returns a 3-tuple indicating everything is ok.
Should only be called after the process has been started.
Checks the following:
- All attached endpoints are alive + listening (this means ready)
- The control flow greenlet is alive + listening or processing
@return 3-tuple indicating (listeners ok, ctrl thread ok, heartbeat status). Use all on it for a
boolean indication of success.
"""
listeners_ok = True
for l in self.listeners:
if not (l in self._listener_map and not self._listener_map[l].proc.dead and l.get_ready_event().is_set()):
listeners_ok = False
ctrl_thread_ok = self._ctrl_thread.running
# are we currently processing something?
heartbeat_ok = True
if self._ctrl_current is not None:
st = traceback.extract_stack(self._ctrl_thread.proc.gr_frame)
if self._ctrl_current == self._heartbeat_op:
if st == self._heartbeat_stack:
self._heartbeat_count += 1 # we've seen this before! increment count
# we've been in this for the last X ticks, or it's been X seconds, fail this part of the heartbeat
if self._heartbeat_count > CFG.get_safe('container.timeout.heartbeat_proc_count_threshold', 30) or \
get_ion_ts_millis() - int(self._heartbeat_time) >= CFG.get_safe('container.timeout.heartbeat_proc_time_threshold', 30) * 1000:
heartbeat_ok = False
else:
# it's made some progress
self._heartbeat_count = 1
self._heartbeat_stack = st
self._heartbeat_time = get_ion_ts()
else:
self._heartbeat_op = self._ctrl_current
self._heartbeat_count = 1
self._heartbeat_time = get_ion_ts()
self._heartbeat_stack = st
else:
self._heartbeat_op = None
self._heartbeat_count = 0
#log.debug("%s %s %s", listeners_ok, ctrl_thread_ok, heartbeat_ok)
return (listeners_ok, ctrl_thread_ok, heartbeat_ok)
@property
def time_stats(self):
"""
Returns a 5-tuple of (total time, idle time, processing time, time since prior interval start,
busy since prior interval start), all in ms (int).
"""
now = get_ion_ts_millis()
running_time = now - self._start_time
idle_time = running_time - self._proc_time
cur_interval = now / STAT_INTERVAL_LENGTH
now_since_prior = now - (cur_interval - 1) * STAT_INTERVAL_LENGTH
if cur_interval == self._proc_interval_num:
proc_time_since_prior = self._proc_time-self._proc_time_prior2
elif cur_interval-1 == self._proc_interval_num:
proc_time_since_prior = self._proc_time-self._proc_time_prior
else:
proc_time_since_prior = 0
return (running_time, idle_time, self._proc_time, now_since_prior, proc_time_since_prior)
def _child_failed(self, child):
"""
Callback from gevent as set in the TheadManager, when a child greenlet fails.
Kills the ION process main greenlet. This propagates the error up to the process supervisor.
"""
# remove the child from the list of children (so we can shut down cleanly)
for x in self.thread_manager.children:
if x.proc == child:
self.thread_manager.children.remove(x)
break
self._dead_children.append(child)
# kill this process's main greenlet. This should be noticed by the container's proc manager
self.proc.kill(child.exception)
def add_endpoint(self, listener, activate=True):
"""
Adds a listening endpoint to be managed by this ION process.
Spawns the listen loop and sets the routing call to synchronize incoming messages
here. If this process hasn't been started yet, adds it to the list of listeners
to start on startup.
@param activate If True (default), start consuming from listener
"""
if self.proc:
listener.routing_call = self._routing_call
if self.name:
svc_name = "unnamed-service"
if self.service is not None and hasattr(self.service, 'name'):
svc_name = self.service.name
listen_thread_name = "%s-%s-listen-%s" % (svc_name, self.name, len(self.listeners)+1)
else:
listen_thread_name = "unknown-listener-%s" % (len(self.listeners)+1)
listen_thread = self.thread_manager.spawn(listener.listen, thread_name=listen_thread_name, activate=activate)
listen_thread.proc._glname = "ION Proc listener %s" % listen_thread_name
self._listener_map[listener] = listen_thread
self.listeners.append(listener)
else:
self._startup_listeners.append(listener)
def remove_endpoint(self, listener):
"""
Removes a listening endpoint from management by this ION process.
If the endpoint is unknown to this ION process, raises an error.
@return The PyonThread running the listen loop, if it exists. You are
responsible for closing it when appropriate.
"""
if listener in self.listeners:
self.listeners.remove(listener)
return self._listener_map.pop(listener)
elif listener in self._startup_listeners:
self._startup_listeners.remove(listener)
return None
else:
raise IonProcessError("Cannot remove unrecognized listener: %s" % listener)
def target(self, *args, **kwargs):
"""
Entry point for the main process greenlet.
Setup the base properties for this process (mainly the control thread).
"""
if self.name:
threading.current_thread().name = "%s-target" % self.name
# start time
self._start_time = get_ion_ts_millis()
self._proc_interval_num = self._start_time / STAT_INTERVAL_LENGTH
# spawn control flow loop
self._ctrl_thread = self.thread_manager.spawn(self._control_flow)
self._ctrl_thread.proc._glname = "ION Proc CL %s" % self.name
# wait on control flow loop, heartbeating as appropriate
while not self._ctrl_thread.ev_exit.wait(timeout=self._heartbeat_secs):
hbst = self.heartbeat()
if not all(hbst):
log.warn("Heartbeat status for process %s returned %s", self, hbst)
if self._heartbeat_stack is not None:
stack_out = "".join(traceback.format_list(self._heartbeat_stack))
else:
stack_out = "N/A"
#raise PyonHeartbeatError("Heartbeat failed: %s, stacktrace:\n%s" % (hbst, stack_out))
log.warn("Heartbeat failed: %s, stacktrace:\n%s", hbst, stack_out)
# this is almost a no-op as we don't fall out of the above loop without
# exiting the ctrl_thread, but having this line here makes testing much easier.
self._ctrl_thread.join()
def _routing_call(self, call, context, *callargs, **callkwargs):
"""
Endpoints call into here to synchronize across the entire IonProcess.
Returns immediately with an AsyncResult that can be waited on. Calls
are made by the loop in _control_flow. We pass in the calling greenlet so
exceptions are raised in the correct context.
@param call The call to be made within this ION processes' calling greenlet.
@param callargs The keyword args to pass to the call.
@param context Optional process-context (usually the headers of the incoming call) to be
set. Process-context is greenlet-local, and since we're crossing greenlet
boundaries, we must set it again in the ION process' calling greenlet.
"""
ar = AsyncResult()
if len(callargs) == 0 and len(callkwargs) == 0:
log.trace("_routing_call got no arguments for the call %s, check your call's parameters", call)
self._ctrl_queue.put((greenlet.getcurrent(), ar, call, callargs, callkwargs, context))
return ar
def has_pending_call(self, ar):
"""
Returns true if the call (keyed by the AsyncResult returned by _routing_call) is still pending.
"""
for _, qar, _, _, _, _ in self._ctrl_queue.queue:
if qar == ar:
return True
return False
def _cancel_pending_call(self, ar):
"""
Cancels a pending call (keyed by the AsyncResult returend by _routing_call).
@return True if the call was truly pending.
"""
if self.has_pending_call(ar):
ar.set(False)
return True
return False
def _interrupt_control_thread(self):
"""
Signal the control flow thread that it needs to abort processing, likely due to a timeout.
"""
self._ctrl_thread.proc.kill(exception=OperationInterruptedException, block=False)
def cancel_or_abort_call(self, ar):
"""
Either cancels a future pending call, or aborts the current processing if the given AR is unset.
The pending call is keyed by the AsyncResult returned by _routing_call.
"""
if not self._cancel_pending_call(ar) and not ar.ready():
self._interrupt_control_thread()
def _control_flow(self):
"""
Entry point for process control thread of execution.
This method is run by the control greenlet for each ION process. Listeners attached
to the process, either RPC Servers or Subscribers, synchronize calls to the process
by placing call requests into the queue by calling _routing_call.
This method blocks until there are calls to be made in the synchronized queue, and
then calls from within this greenlet. Any exception raised is caught and re-raised
in the greenlet that originally scheduled the call. If successful, the AsyncResult
created at scheduling time is set with the result of the call.
"""
svc_name = getattr(self.service, "name", "unnamed-service") if self.service else "unnamed-service"
proc_id = getattr(self.service, "id", "unknown-pid") if self.service else "unknown-pid"
if self.name:
threading.current_thread().name = "%s-%s" % (svc_name, self.name)
thread_base_name = threading.current_thread().name
self._ready_control.set()
for calltuple in self._ctrl_queue:
calling_gl, ar, call, callargs, callkwargs, context = calltuple
request_id = (context or {}).get("request-id", None)
if request_id:
threading.current_thread().name = thread_base_name + "-" + str(request_id)
#log.debug("control_flow making call: %s %s %s (has context: %s)", call, callargs, callkwargs, context is not None)
res = None
start_proc_time = get_ion_ts_millis()
self._record_proc_time(start_proc_time)
# check context for expiration
if context is not None and 'reply-by' in context:
if start_proc_time >= int(context['reply-by']):
log.info("control_flow: attempting to process message already exceeding reply-by, ignore")
# raise a timeout in the calling thread to allow endpoints to continue processing
e = IonTimeout("Reply-by time has already occurred (reply-by: %s, op start time: %s)" % (context['reply-by'], start_proc_time))
calling_gl.kill(exception=e, block=False)
continue
# If ar is set, means it is cancelled
if ar.ready():
log.info("control_flow: attempting to process message that has been cancelled, ignore")
continue
init_db_stats()
try:
# ******************************************************************
# ****** THIS IS WHERE THE RPC OPERATION/SERVICE CALL IS MADE ******
with self.service.push_context(context), \
self.service.container.context.push_context(context):
self._ctrl_current = ar
res = call(*callargs, **callkwargs)
# ****** END CALL, EXCEPTION HANDLING FOLLOWS ******
# ******************************************************************
except OperationInterruptedException:
# endpoint layer takes care of response as it's the one that caused this
log.debug("Operation interrupted")
pass
except Exception as e:
if self._log_call_exception:
log.exception("PROCESS exception: %s" % e.message)
# Raise the exception in the calling greenlet.
# Try decorating the args of the exception with the true traceback -
# this should be reported by ThreadManager._child_failed
exc = PyonThreadTraceback("IonProcessThread _control_flow caught an exception "
"(call: %s, *args %s, **kwargs %s, context %s)\n"
"True traceback captured by IonProcessThread' _control_flow:\n\n%s" % (
call, callargs, callkwargs, context, traceback.format_exc()))
e.args = e.args + (exc,)
if isinstance(e, (TypeError, IonException)):
# Pass through known process exceptions, in particular IonException
calling_gl.kill(exception=e, block=False)
else:
# Otherwise, wrap unknown, forward and hopefully we can continue on our way
self._errors.append((call, callargs, callkwargs, context, e, exc))
log.warn(exc)
log.warn("Attempting to continue...")
# Note: Too large exception string will crash the container (when passed on as msg header).
exception_str = str(exc)
if len(exception_str) > 10000:
exception_str = (
"Exception string representation too large. "
"Begin and end of the exception:\n"
+ exception_str[:2000] + "\n...\n" + exception_str[-2000:]
)
calling_gl.kill(exception=ContainerError(exception_str), block=False)
finally:
try:
# Compute statistics
self._compute_proc_stats(start_proc_time)
db_stats = get_db_stats()
if db_stats:
if self._warn_call_dbstmt_threshold > 0 and db_stats.get("count.all", 0) >= self._warn_call_dbstmt_threshold:
stats_str = ", ".join("{}={}".format(k, db_stats[k]) for k in sorted(db_stats.keys()))
log.warn("PROC_OP '%s.%s' EXCEEDED DB THRESHOLD. stats=%s", svc_name, call.__name__, stats_str)
elif self._log_call_dbstats:
stats_str = ", ".join("{}={}".format(k, db_stats[k]) for k in sorted(db_stats.keys()))
log.info("PROC_OP '%s.%s' DB STATS: %s", svc_name, call.__name__, stats_str)
clear_db_stats()
if stats_callback:
stats_callback(proc_id=proc_id, proc_name=self.name, svc=svc_name, op=call.__name__,
request_id=request_id, context=context,
db_stats=db_stats, proc_stats=self.time_stats, result=res, exc=None)
except Exception:
log.exception("Error computing process call stats")
self._ctrl_current = None
threading.current_thread().name = thread_base_name
# Set response in AsyncEvent of caller (endpoint greenlet)
ar.set(res)
def _record_proc_time(self, cur_time):
""" Keep the _proc_time of the prior and prior-prior intervals for stats computation
"""
cur_interval = cur_time / STAT_INTERVAL_LENGTH
if cur_interval == self._proc_interval_num:
# We're still in the same interval - no update
pass
elif cur_interval-1 == self._proc_interval_num:
# Record the stats from the prior interval
self._proc_interval_num = cur_interval
self._proc_time_prior2 = self._proc_time_prior
self._proc_time_prior = self._proc_time
elif cur_interval-1 > self._proc_interval_num:
# We skipped an entire interval - everything is prior2
self._proc_interval_num = cur_interval
self._proc_time_prior2 = self._proc_time
self._proc_time_prior = self._proc_time
def _compute_proc_stats(self, start_proc_time):
cur_time = get_ion_ts_millis()
self._record_proc_time(cur_time)
proc_time = cur_time - start_proc_time
self._proc_time += proc_time
def start_listeners(self):
"""
Starts all listeners in managed greenlets.
Usually called by the ProcManager, unless using IonProcess manually.
"""
try:
# disable normal error reporting, this method should only be called from startup
self.thread_manager._failure_notify_callback = None
# spawn all listeners in startup listeners (from initializer, or added later)
for listener in self._startup_listeners:
self.add_endpoint(listener)
with Timeout(seconds=CFG.get_safe('container.messaging.timeout.start_listener', 30)):
gevent.wait([x.get_ready_event() for x in self.listeners])
except Timeout:
# remove failed endpoints before reporting failure above
for listener, proc in self._listener_map.iteritems():
if proc.proc.dead:
log.info("removed dead listener: %s", listener)
self.listeners.remove(listener)
self.thread_manager.children.remove(proc)
raise IonProcessError("start_listeners did not complete in expected time")
finally:
self.thread_manager._failure_notify_callback = self._child_failed
def _notify_stop(self):
"""
Called when the process is about to be shut down.
Instructs all listeners to close, puts a StopIteration into the synchronized queue,
and waits for the listeners to close and for the control queue to exit.
"""
for listener in self.listeners:
try:
listener.close()
except Exception as ex:
tb = traceback.format_exc()
log.warn("Could not close listener, attempting to ignore: %s\nTraceback:\n%s", ex, tb)
self._ctrl_queue.put(StopIteration)
# wait_children will join them and then get() them, which may raise an exception if any of them
# died with an exception.
self.thread_manager.wait_children(30)
PyonThread._notify_stop(self)
# run the cleanup method if we have one
if self._cleanup_method is not None:
try:
self._cleanup_method(self)
except Exception as ex:
log.warn("Cleanup method error, attempting to ignore: %s\nTraceback: %s", ex, traceback.format_exc())
def get_ready_event(self):
"""
Returns an Event that is set when the control greenlet is up and running.
"""
return self._ready_control
class IonProcessThreadManager(PyonThreadManager):
def _create_thread(self, target=None, **kwargs):
return IonProcessThread(target=target, heartbeat_secs=self.heartbeat_secs, **kwargs)
# ---------------------------------------------------------------------------------------------------
# Process type variants
class StandaloneProcess(BaseService):
"""
A process is an ION process of type "standalone" that has an incoming messaging
attachment for the process and operations as defined in a service YML.
"""
process_type = "standalone"
class SimpleProcess(BaseService):
"""
A simple process is an ION process of type "simple" that has no incoming messaging
attachment.
"""
process_type = "simple"
class ImmediateProcess(BaseService):
"""
An immediate process is an ION process of type "immediate" that does its action in
the on_init and on_start hooks, and that it terminated immediately after completion.
Has no messaging attachment.
"""
process_type = "immediate"
class StreamProcess(BaseService):
"""
Base class for a stream process.
Such a process handles a sequence of otherwise unconstrained messages, resulting from a
subscription. There are no operations.
"""
process_type = "stream_process"
def call_process(self, message, stream_route, stream_id):
"""
Handles pre-processing of packet and process work
"""
self.process(message)
def process(self, message):
"""
Process a message as arriving based on a subscription.
"""
pass
# ---------------------------------------------------------------------------------------------------
# Process helpers
def get_ion_actor_id(process):
"""Given an ION process, return the ion-actor-id from the context, if set and present"""
ion_actor_id = None
if process:
ctx = process.get_context()
ion_actor_id = ctx.get(MSG_HEADER_ACTOR, None) if ctx else None
return ion_actor_id
def set_process_stats_callback(stats_cb):
""" Sets a callback function (hook) to push stats after a process operation call. """
global stats_callback
if stats_cb is None:
pass
elif stats_callback:
log.warn("Stats callback already defined")
stats_callback = stats_cb
|
Java
|
# 98Fmplayer (beta)
PC-98 FM driver emulation (very early version)




*If you are just annoyed by some specific bugs in PMDWin, [patched PMDWin](https://github.com/takamichih/pmdwinbuild) might have less bugs and more features than this.*
## Current status:
* Supported formats: PMD, FMP(PLAY6)
* PMD: FM, SSG, Rhythm, ADPCM, PPZ8(partially) supported; PPS, P86 not supported yet
* FMP: FM, SSG, Rhythm, ADPCM, PPZ8, PDZF supported
* This is just a byproduct of reverse-engineering formats, and its emulation is much worse than PMDWin, WinFMP
* FM always generated in 55467Hz (closest integer to 7987200 / 144), SSG always generated in 249600Hz and downsampled with sinc filter (Never linear interpolates harmonics-rich signal like square wave)
* FM generation bit-perfect with actual OPNA/OPN3 chip under limited conditions including stereo output when 4 <= ALG (Envelope is not bit-perfect yet, attack is bit-perfect only when AR >= 21)
* SSGEG, Hardware LFO not supported
* PPZ8: support nearest neighbor, linear and sinc interpolation
* ADPCM: inaccurate (actual YM2608 seems to decode ADPCM at lower samplerate/resolution than any YM2608 emulator around, but I still couldn't get my YM2608 work with the DRAM)
## Installation/Usage (not very usable yet)
### gtk
Uses gtk3, pulseaudio/jack/alsa
```
$ cd gtk
$ autoreconf -i
$ ./configure
$ make
$ ./98fmplayer
```
Reads drum sample from `$HOME/.local/share/98fmplayer/ym2608_adpcm_rom.bin` (same format as MAME).
### win32
Releases:
https://github.com/takamichih/fmplayer/releases/
Uses MinGW-w64 to compile.
```
$ cd win32/x86
$ make
```
Reads drum sample from the directory in which `98fmplayer.exe` is placed.
Uses DirectSound (WinMM if there is no DirectSound) to output sound. This works on Windows 2000, so it is theoretically possible to run this on a real PC-98. (But it was too heavy for my PC-9821V12 which only has P5 Pentium 120MHz, or on PC-9821Ra300 with P6 Mendocino Celeron 300MHz)
|
Java
|
# Author: Nick Raptis <airscorp@gmail.com>
"""
Module for listing commands and help.
"""
from basemodule import BaseModule, BaseCommandContext
from alternatives import _
class HelpContext(BaseCommandContext):
def cmd_list(self, argument):
"""List commands"""
arg = argument.lower()
index = self.bot.help_index
public = "public commands -- %s" % " ".join(index['public'])
private = "private commands -- %s" % " ".join(index['private'])
if 'all' in arg or 'both' in arg:
output = "\n".join((public, private))
elif 'pub' in arg or self.target.startswith('#'):
output = public
elif 'priv' in arg or not self.target.startswith('#'):
output = private
else:
# we shouldn't be here
self.logger.error("cmd_list")
return
self.send(self.target, output)
def cmd_modules(self, argument):
"""List active modules"""
index = self.bot.help_index
output = "active modules -- %s" % " ".join(index['modules'].keys())
self.send(self.target, output)
def cmd_help(self, argument):
"""Get help on a command or module"""
arg = argument.lower()
index = self.bot.help_index
target = self.target
args = arg.split()
if not args:
s = "usage: help <command> [public|private] / help module <module>"
self.send(target, s)
elif args[0] == 'module':
args.pop(0)
if not args:
self.send(target, "usage: help module <module>")
else:
help_item = index['modules'].get(args[0])
if help_item:
self.send(target, help_item['summary'])
else:
self.send(target, _("No help for %s"), args[0])
else:
args.append("")
cmd = args.pop(0)
cmd_type = args.pop(0)
if 'pu' in cmd_type or self.target.startswith('#'):
cmd_type = 'public'
elif 'pr' in cmd_type or not self.target.startswith('#'):
cmd_type = 'private'
else:
# we shouldn't be here
self.logger.error("cmd_list")
return
help_item = index[cmd_type].get(cmd)
if help_item:
self.send(target, index[cmd_type][cmd]['summary'])
else:
self.send(target, _("No help for %s"), cmd)
class HelpModule(BaseModule):
context_class = HelpContext
module = HelpModule
|
Java
|
Notebook with pandas in a container
===================================
Docker container for the IPython notebook (with pandas).
Usage
-----
docker run -i -t --rm -v `pwd`/notebooks:/notebooks -p 8888:8888 -e "PASSWORD=YOURPASSWORD" mlf4aiur/pandas
You'll now be able to access your notebook at https://localhost:8888 with password YOURPASSWORD.
**Using HTTP**
This docker image by default runs IPython notebook in HTTPS. If you'd like to run this in HTTP, you can use the USE_HTTP environment variable. Setting it to a non-zero value enables HTTP.
docker run -i -t --rm -v `pwd`/notebooks:/notebooks -p 8888:8888 -e "PASSWORD=YOURPASSWORD" -e "USE_HTTP=1" mlf4aiur/pandas
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.