code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
# An initializer like this can go into your Rails project's config/initializers/ folder # require 'arma_fixer' module ArmaFixer # APP = YourRailsAppName::Application # # Depending on which gem you are using for your attachments, you will need a your own criteria of what is a valid file. # ATTR_CHECKER = -> (attr) do # attr.present? && attr.path.present? && File.exist?(attr.path) # end # # You can pass a list of models with array or hash attributes: # For hash values, full paths of images must be provided # MODELS_HASH = { # 'User' => [:profile_image, :avatar], # 'Background' => [:image], # 'Blog' => { header: Rails.root.expand_path.join('app/assets/images/header.png').to_path, # footer: Rails.root.expand_path.join('app/assets/images/footer.png').to_path }, # 'RandomModel' => { attachment: footer: Rails.root.expand_path.join('app/assets/pdfs/file.pdf').to_path } # } # # If you have provided any array value to MODELS_HASH, you will need to specify a default image path: # DEFAULT_IMAGE_PATH = Rails.root.expand_path.join('app/assets/images/default.png').to_path # # ArmaFixer will skip validations when saving records, for better speeds. Thus it's your responsibility to ensure # that the files you provide in values are valid for the model attributes that you specify. end
humzashah/arma_fixer
samples/arma_fixer.rb
Ruby
mit
1,355
package test_locally.app; import com.slack.api.Slack; import com.slack.api.SlackConfig; import com.slack.api.app_backend.SlackSignature; import com.slack.api.app_backend.dialogs.response.Option; import com.slack.api.bolt.App; import com.slack.api.bolt.AppConfig; import com.slack.api.bolt.request.RequestHeaders; import com.slack.api.bolt.request.builtin.DialogSuggestionRequest; import com.slack.api.bolt.response.Response; import lombok.extern.slf4j.Slf4j; import org.junit.After; import org.junit.Before; import org.junit.Test; import util.AuthTestMockServer; import java.net.URLEncoder; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; @Slf4j public class DialogSuggestionTest { AuthTestMockServer server = new AuthTestMockServer(); SlackConfig config = new SlackConfig(); Slack slack = Slack.getInstance(config); @Before public void setup() throws Exception { server.start(); config.setMethodsEndpointUrlPrefix(server.getMethodsEndpointPrefix()); } @After public void tearDown() throws Exception { server.stop(); } final String secret = "foo-bar-baz"; final SlackSignature.Generator generator = new SlackSignature.Generator(secret); String realPayload = "{\n" + " \"type\": \"dialog_suggestion\",\n" + " \"token\": \"W3VDvuzi2nRLsiaDOsmJranO\",\n" + " \"action_ts\": \"1528203589.238335\",\n" + " \"team\": {\n" + " \"id\": \"T24BK35ML\",\n" + " \"domain\": \"hooli-hq\"\n" + " },\n" + " \"user\": {\n" + " \"id\": \"U900MV5U7\",\n" + " \"name\": \"gbelson\"\n" + " },\n" + " \"channel\": {\n" + " \"id\": \"C012AB3CD\",\n" + " \"name\": \"triage-platform\"\n" + " },\n" + " \"name\": \"external_data\",\n" + " \"value\": \"\",\n" + " \"callback_id\": \"bugs\"\n" + "}"; List<Option> options = Arrays.asList( Option.builder().label("label").value("value").build() ); @Test public void test() throws Exception { App app = buildApp(); app.dialogSuggestion("bugs", (req, ctx) -> ctx.ack(r -> r.options(options))); String requestBody = "payload=" + URLEncoder.encode(realPayload, "UTF-8"); Map<String, List<String>> rawHeaders = new HashMap<>(); String timestamp = String.valueOf(System.currentTimeMillis() / 1000); setRequestHeaders(requestBody, rawHeaders, timestamp); DialogSuggestionRequest req = new DialogSuggestionRequest(requestBody, realPayload, new RequestHeaders(rawHeaders)); Response response = app.run(req); assertEquals(200L, response.getStatusCode().longValue()); } @Test public void skipped() throws Exception { App app = buildApp(); app.dialogSuggestion("bugs-life", (req, ctx) -> ctx.ack(r -> r.options(options))); String requestBody = "payload=" + URLEncoder.encode(realPayload, "UTF-8"); Map<String, List<String>> rawHeaders = new HashMap<>(); String timestamp = String.valueOf(System.currentTimeMillis() / 1000); setRequestHeaders(requestBody, rawHeaders, timestamp); DialogSuggestionRequest req = new DialogSuggestionRequest(requestBody, realPayload, new RequestHeaders(rawHeaders)); Response response = app.run(req); assertEquals(404L, response.getStatusCode().longValue()); } App buildApp() { return new App(AppConfig.builder() .signingSecret(secret) .singleTeamBotToken(AuthTestMockServer.ValidToken) .slack(slack) .build()); } void setRequestHeaders(String requestBody, Map<String, List<String>> rawHeaders, String timestamp) { rawHeaders.put(SlackSignature.HeaderNames.X_SLACK_REQUEST_TIMESTAMP, Arrays.asList(timestamp)); rawHeaders.put(SlackSignature.HeaderNames.X_SLACK_SIGNATURE, Arrays.asList(generator.generate(timestamp, requestBody))); } }
seratch/jslack
bolt/src/test/java/test_locally/app/DialogSuggestionTest.java
Java
mit
4,212
<?php namespace App\Http\Controllers; use App\Manuales; use App\Manuales_servicios; use App\Servicios; use Illuminate\Http\Request; use Illuminate\Support\Facades\Redirect; class ManualServiciosController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create($id) { $manual = Manuales::findOrFail($id); $servicios = Servicios::where("estado", "Activo")->orderBy("cups")->get(); return view('administracion.manuales.servicios.create', compact('manual', 'servicios')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store($id_manual, Request $request) { $manual = Manuales::findOrFail($id_manual); $this->validate($request, [ 'id_servicio' => 'required|exists:servicios,id', 'codigosoat' => 'required', 'costo' => 'required|numeric|min:0', 'estado' => 'required' ]); $manual_servicio = Manuales_servicios::where("id_manual", $id_manual)->where("id_servicio", $request->id_servicio)->get(); if ($manual_servicio != "[]") { $manual_servicio = $manual_servicio[0]; if ($request->ajax()) { return response()->json([ 'error' => "EL servicio <a href='/manuales/$id_manual/servicios/$request->id_servicio/edit' target='_blank'><b>" . $manual_servicio->id_servicio->cups . "</b></a> ya se encuentra registrado en el manual <a href='/manuales/$id_manual' target='_blank'><b>" . $manual_servicio->id_manual->codigosoat . "</b></a>." ]); } else { flash("EL servicio <a href='/manuales/$id_manual/servicios/$request->id_servicio/edit' target='_blank'>" . $manual_servicio->id_servicio->cups . "</a> ya se encuentra registrado en el manual <a href='/manuales/$id_manual' target='_blank'>" . $manual_servicio->id_manual->codigosoat . "</a>.")->error(); return Redirect::to("/manuales/$id_manual/servicios/create"); } } else { $manual_servicio = Manuales_servicios::create([ 'id_servicio' => $request->id_servicio, 'id_manual' => $id_manual, 'codigosoat' => $request->codigosoat, 'costo' => $request->costo, 'estado' => $request->estado ]); if ($request->ajax()) { return response()->json([ 'success' => 'true', 'mensaje' => "El servicio <a href='/manuales/$id_manual/servicios/$request->id_servicio/edit' target='_blank'><b>" . $manual_servicio->id_servicio->cups . "</b></a> ha sido añadido al manual <a href='/manuales/$id_manual' target='_blank'><b>" . $manual_servicio->id_manual->codigosoat . "</b></a> con éxito!." ]); } else { flash("El servicio <a href='/manuales/$id_manual/servicios/$request->id_servicio/edit' target='_blank'>" . $manual_servicio->id_servicio->cups . "</a> ha sido añadido al manual <a href='/manuales/$id_manual' target='_blank'>" . $manual_servicio->id_manual->codigosoat . "</a> con éxito!.")->success(); return Redirect::to("/manuales/$id_manual"); } } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id_manual * @param int $id_manual_servicio * @param Request $request * @return \Illuminate\Http\Response */ public function edit($id_manual, $id_manual_servicio, Request $request) { $manual_servicio = Manuales_servicios::findOrFail($id_manual_servicio); if ($request->ajax()) { return response()->json([ 'success' => 'true', 'manual_servicio' => $manual_servicio ]); } else { $servicios = Servicios::where("estado", "Activo")->orderBy("cups")->get(); return view('administracion.manuales.servicios.edit', compact('manual_servicio', 'servicios')); } } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id_manual * @param int $id_manual_servicio * @return \Illuminate\Http\Response */ public function update(Request $request, $id_manual, $id_manual_servicio) { $this->validate($request, [ 'id_servicio' => 'required|exists:servicios,id', 'codigosoat' => 'required', 'costo' => 'required|numeric|min:0', 'codigosoat' => "required", 'estado' => 'required' ]); $servicio = Servicios::findOrfail($request->id_servicio); $manual = Manuales::findOrfail($id_manual); $manual_servicio = Manuales_servicios::findOrFail($id_manual_servicio); if ($request->id_servicio != $manual_servicio->id_servicio->id) { $servicios = Manuales_servicios::where("id_manual", $id_manual)->where("id_servicio", $request->id_servicio)->get(); if ($servicios != "[]") { $servicios = $servicios[0]; if ($request->ajax()) { return response()->json([ 'error' => "El servicio <a href='/manuales/$id_manual/servicios/$servicios->id/edit' target='_blank'><b>" . $servicio->cups . "</b></a> ya se encuentra registrado en el manual <a href='/manuales/$id_manual' target='_blank'><b>" . $manual->codigosoat . "</b></a>" ]); } else { flash("El servicio <a href='/manuales/$id_manual/servicios/$servicios->id/edit' target='_blank'><b>" . $servicio->cups . "</b></a> ya se encuentra registrado en el manual <a href='/manuales/$id_manual' target='_blank'><b>" . $manual->codigosoat . "</b></a>")->error(); return Redirect::to("/manuales/$id_manual/servicios/$id_manual_servicio/edit"); } } else { $manual_servicio->id_servicio = $request->id_servicio; $manual_servicio->costo = $request->costo; $manual_servicio->codigosoat = $request->codigosoat; $manual_servicio->estado = $request->estado; $manual_servicio->save(); } } else { $manual_servicio->codigosoat = $request->codigosoat; $manual_servicio->costo = $request->costo; $manual_servicio->estado = $request->estado; $manual_servicio->save(); } if ($request->ajax()) { return response()->json([ 'success' => 'true', 'mensaje' => "El servicio <a href='/manuales/$id_manual/servicios/$id_manual_servicio/edit' target='_blank'><b>" . $servicio->cups . "</b></a> ha sido actualizado con éxito!." ]); } else { flash("El servicio <a href='/manuales/$id_manual/servicios/$id_manual_servicio/edit' target='_blank'><b>" . $servicio->cups . "</b></a> ha sido actualizado con éxito!.")->success(); return Redirect::to("/manuales/$id_manual"); } } /** * Remove the specified resource from storage. * * @param int $id_manual * @param int $id_manual_servicio * @return \Illuminate\Http\Response */ public function destroy($id_manual, $id_manual_servicio,Request $request) { $manual_servicio = Manuales_servicios::findOrFail($id_manual_servicio); $cups = $manual_servicio->id_servicio->cups; if($manual_servicio->delete()){ if ($request->ajax()) { return response()->json([ 'success' => 'true', 'mensaje' => "EL servicio <b>$cups</b> ha sido eliminado con éxito!" ]); } else { flash("EL servicio <b>$cups</b> ha sido eliminado con éxito!")->success(); return Redirect::to("/manuales/$id_manual"); } }else{ if ($request->ajax()) { return response()->json([ 'error' => "Error al eliminar el servicio <b>$cups</b>." ]); } else { flash("Error al eliminar el servicio <b>$cups</b>.")->error(); return Redirect::to("/manuales/$id_manual"); } } } }
Smiithx/facturacion
app/Http/Controllers/ManualServiciosController.php
PHP
mit
8,987
/* * Farseer Physics Engine: * Copyright (c) 2012 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #pragma warning disable 0162 using System.Diagnostics; namespace TrueSync.Physics2D { // 1-D rained system // m (v2 - v1) = lambda // v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass. // x2 = x1 + h * v2 // 1-D mass-damper-spring system // m (v2 - v1) + h * d * v2 + h * k * // C = norm(p2 - p1) - L // u = (p2 - p1) / norm(p2 - p1) // Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1)) // J = [-u -cross(r1, u) u cross(r2, u)] // K = J * invM * JT // = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2 /// <summary> /// A distance joint rains two points on two bodies /// to remain at a fixed distance from each other. You can view /// this as a massless, rigid rod. /// </summary> public class DistanceJoint : Joint2D { // Solver shared private FP _bias; private FP _gamma; private FP _impulse; // Solver temp private int _indexA; private int _indexB; private TSVector2 _u; private TSVector2 _rA; private TSVector2 _rB; private TSVector2 _localCenterA; private TSVector2 _localCenterB; private FP _invMassA; private FP _invMassB; private FP _invIA; private FP _invIB; private FP _mass; internal DistanceJoint() { JointType = JointType.Distance; } /// <summary> /// This requires defining an /// anchor point on both bodies and the non-zero length of the /// distance joint. If you don't supply a length, the local anchor points /// is used so that the initial configuration can violate the constraint /// slightly. This helps when saving and loading a game. /// Warning Do not use a zero or short length. /// </summary> /// <param name="bodyA">The first body</param> /// <param name="bodyB">The second body</param> /// <param name="anchorA">The first body anchor</param> /// <param name="anchorB">The second body anchor</param> /// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param> public DistanceJoint(Body bodyA, Body bodyB, TSVector2 anchorA, TSVector2 anchorB, bool useWorldCoordinates = false) : base(bodyA, bodyB) { JointType = JointType.Distance; if (useWorldCoordinates) { LocalAnchorA = bodyA.GetLocalPoint(ref anchorA); LocalAnchorB = bodyB.GetLocalPoint(ref anchorB); Length = (anchorB - anchorA).magnitude; } else { LocalAnchorA = anchorA; LocalAnchorB = anchorB; Length = (BodyB.GetWorldPoint(ref anchorB) - BodyA.GetWorldPoint(ref anchorA)).magnitude; } } /// <summary> /// The local anchor point relative to bodyA's origin. /// </summary> public TSVector2 LocalAnchorA { get; set; } /// <summary> /// The local anchor point relative to bodyB's origin. /// </summary> public TSVector2 LocalAnchorB { get; set; } public override sealed TSVector2 WorldAnchorA { get { return BodyA.GetWorldPoint(LocalAnchorA); } set { Debug.Assert(false, "You can't set the world anchor on this joint type."); } } public override sealed TSVector2 WorldAnchorB { get { return BodyB.GetWorldPoint(LocalAnchorB); } set { Debug.Assert(false, "You can't set the world anchor on this joint type."); } } /// <summary> /// The natural length between the anchor points. /// Manipulating the length can lead to non-physical behavior when the frequency is zero. /// </summary> public FP Length { get; set; } /// <summary> /// The mass-spring-damper frequency in Hertz. A value of 0 /// disables softness. /// </summary> public FP Frequency { get; set; } /// <summary> /// The damping ratio. 0 = no damping, 1 = critical damping. /// </summary> public FP DampingRatio { get; set; } /// <summary> /// Get the reaction force given the inverse time step. Unit is N. /// </summary> /// <param name="invDt"></param> /// <returns></returns> public override TSVector2 GetReactionForce(FP invDt) { TSVector2 F = (invDt * _impulse) * _u; return F; } /// <summary> /// Get the reaction torque given the inverse time step. /// Unit is N*m. This is always zero for a distance joint. /// </summary> /// <param name="invDt"></param> /// <returns></returns> public override FP GetReactionTorque(FP invDt) { return 0.0f; } internal override void InitVelocityConstraints(ref SolverData data) { _indexA = BodyA.IslandIndex; _indexB = BodyB.IslandIndex; _localCenterA = BodyA._sweep.LocalCenter; _localCenterB = BodyB._sweep.LocalCenter; _invMassA = BodyA._invMass; _invMassB = BodyB._invMass; _invIA = BodyA._invI; _invIB = BodyB._invI; TSVector2 cA = data.positions[_indexA].c; FP aA = data.positions[_indexA].a; TSVector2 vA = data.velocities[_indexA].v; FP wA = data.velocities[_indexA].w; TSVector2 cB = data.positions[_indexB].c; FP aB = data.positions[_indexB].a; TSVector2 vB = data.velocities[_indexB].v; FP wB = data.velocities[_indexB].w; Rot qA = new Rot(aA), qB = new Rot(aB); _rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA); _rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB); _u = cB + _rB - cA - _rA; // Handle singularity. FP length = _u.magnitude; if (length > Settings.LinearSlop) { _u *= 1.0f / length; } else { _u = TSVector2.zero; } FP crAu = MathUtils.Cross(_rA, _u); FP crBu = MathUtils.Cross(_rB, _u); FP invMass = _invMassA + _invIA * crAu * crAu + _invMassB + _invIB * crBu * crBu; // Compute the effective mass matrix. _mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; if (Frequency > 0.0f) { FP C = length - Length; // Frequency FP omega = 2.0f * Settings.Pi * Frequency; // Damping coefficient FP d = 2.0f * _mass * DampingRatio * omega; // Spring stiffness FP k = _mass * omega * omega; // magic formulas FP h = data.step.dt; _gamma = h * (d + h * k); _gamma = _gamma != 0.0f ? 1.0f / _gamma : 0.0f; _bias = C * h * k * _gamma; invMass += _gamma; _mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; } else { _gamma = 0.0f; _bias = 0.0f; } if (Settings.EnableWarmstarting) { // Scale the impulse to support a variable time step. _impulse *= data.step.dtRatio; TSVector2 P = _impulse * _u; vA -= _invMassA * P; wA -= _invIA * MathUtils.Cross(_rA, P); vB += _invMassB * P; wB += _invIB * MathUtils.Cross(_rB, P); } else { _impulse = 0.0f; } data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; data.velocities[_indexB].v = vB; data.velocities[_indexB].w = wB; } internal override void SolveVelocityConstraints(ref SolverData data) { TSVector2 vA = data.velocities[_indexA].v; FP wA = data.velocities[_indexA].w; TSVector2 vB = data.velocities[_indexB].v; FP wB = data.velocities[_indexB].w; // Cdot = dot(u, v + cross(w, r)) TSVector2 vpA = vA + MathUtils.Cross(wA, _rA); TSVector2 vpB = vB + MathUtils.Cross(wB, _rB); FP Cdot = TSVector2.Dot(_u, vpB - vpA); FP impulse = -_mass * (Cdot + _bias + _gamma * _impulse); _impulse += impulse; TSVector2 P = impulse * _u; vA -= _invMassA * P; wA -= _invIA * MathUtils.Cross(_rA, P); vB += _invMassB * P; wB += _invIB * MathUtils.Cross(_rB, P); data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; data.velocities[_indexB].v = vB; data.velocities[_indexB].w = wB; } internal override bool SolvePositionConstraints(ref SolverData data) { if (Frequency > 0.0f) { // There is no position correction for soft distance constraints. return true; } TSVector2 cA = data.positions[_indexA].c; FP aA = data.positions[_indexA].a; TSVector2 cB = data.positions[_indexB].c; FP aB = data.positions[_indexB].a; Rot qA = new Rot(aA), qB = new Rot(aB); TSVector2 rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA); TSVector2 rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB); TSVector2 u = cB + rB - cA - rA; FP length = u.magnitude; u.Normalize(); FP C = length - Length; C = MathUtils.Clamp(C, -Settings.MaxLinearCorrection, Settings.MaxLinearCorrection); FP impulse = -_mass * C; TSVector2 P = impulse * u; cA -= _invMassA * P; aA -= _invIA * MathUtils.Cross(rA, P); cB += _invMassB * P; aB += _invIB * MathUtils.Cross(rB, P); data.positions[_indexA].c = cA; data.positions[_indexA].a = aA; data.positions[_indexB].c = cB; data.positions[_indexB].a = aB; return FP.Abs(C) < Settings.LinearSlop; } } }
Xaer033/YellowSign
YellowSignUnity/Assets/ThirdParty/Networking/TrueSync/Physics/Farseer/Dynamics/Joints/DistanceJoint.cs
C#
mit
11,561
<?php namespace keeko\tools\generator\serializer; use gossi\codegen\model\PhpClass; use gossi\codegen\model\PhpMethod; use gossi\codegen\model\PhpParameter; use keeko\framework\utils\NameUtils; use gossi\codegen\model\PhpProperty; class TypeInferencerGenerator extends AbstractSerializerGenerator { public function generate() { $namespace = $this->factory->getNamespaceGenerator()->getSerializerNamespace(); $className = $namespace . '\\TypeInferencer'; $class = new PhpClass($className); $class->addInterface('TypeInferencerInterface'); $class->addUseStatement('keeko\framework\model\TypeInferencerInterface'); $this->generateSingleton($class); $this->generateTypes($class); $this->generateGetModelClass($class); $this->generateGetQueryClass($class); return $class; } protected function generateSingleton(PhpClass $class) { $class->setProperty(PhpProperty::create('instance') ->setStatic(true) ->setVisibility(PhpProperty::VISIBILITY_PRIVATE) ); $class->setMethod(PhpMethod::create('getInstance') ->setStatic(true) ->setBody($this->twig->render('getInstance.twig')) ); $class->setMethod(PhpMethod::create('__construct') ->setVisibility(PhpMethod::VISIBILITY_PRIVATE) ); } protected function generateTypes(PhpClass $class) { $package = $this->packageService->getPackage(); $types = []; foreach ($this->modelService->getModels() as $model) { $type = sprintf('%s/%s', $package->getKeeko()->getModule()->getSlug(), NameUtils::dasherize($model->getOriginCommonName())); $types[$type] = [ 'modelClass' => $model->getNamespace() . '\\' . $model->getPhpName(), 'queryClass' => $model->getNamespace() . '\\' . $model->getPhpName() . 'Query', ]; $types[NameUtils::pluralize($type)] = [ 'modelClass' => $model->getNamespace() . '\\' . $model->getPhpName(), 'queryClass' => $model->getNamespace() . '\\' . $model->getPhpName() . 'Query', ]; } $out = ''; foreach ($types as $type => $data) { $out .= sprintf("\t'$type' => [\n\t\t'modelClass' => '%s',\n\t\t'queryClass' => '%s'\n\t],\n", $data['modelClass'], $data['queryClass']); } $out = rtrim($out, ",\n"); $out = "[\n$out\n]"; $class->setProperty(PhpProperty::create('types') ->setExpression($out) ->setVisibility(PhpProperty::VISIBILITY_PRIVATE) ); } protected function generateGetModelClass(PhpClass $class) { $class->setMethod(PhpMethod::create('getModelClass') ->addParameter(PhpParameter::create('type')) ->setBody($this->twig->render('getModelClass.twig')) ); } protected function generateGetQueryClass(PhpClass $class) { $class->setMethod(PhpMethod::create('getQueryClass') ->addParameter(PhpParameter::create('type')) ->setBody($this->twig->render('getQueryClass.twig')) ); } }
keeko/tools
src/generator/serializer/TypeInferencerGenerator.php
PHP
mit
2,783
var moduleName = "ngApp.controllers"; import timeCtrl from './controller/time-controller.js'; // import yourCtrlHere from './controller/your-controller'; var ctrls = Array.from([ //yourCtrlHere, timeCtrl ]); var app = angular.module(moduleName, []); for(var ctrl of ctrls){ app.controller(ctrl.name, ctrl.def); } export default moduleName;
hiramsoft/es6-ng-twbs-gulp-start
src/main/es6/controllers.js
JavaScript
mit
356
import pandas as pd df_ab = pd.DataFrame({'a': ['a_1', 'a_2', 'a_3'], 'b': ['b_1', 'b_2', 'b_3']}) df_ac = pd.DataFrame({'a': ['a_1', 'a_2', 'a_4'], 'c': ['c_1', 'c_2', 'c_4']}) print(df_ab) # a b # 0 a_1 b_1 # 1 a_2 b_2 # 2 a_3 b_3 print(df_ac) # a c # 0 a_1 c_1 # 1 a_2 c_2 # 2 a_4 c_4 print(pd.merge(df_ab, df_ac)) # a b c # 0 a_1 b_1 c_1 # 1 a_2 b_2 c_2 print(df_ab.merge(df_ac)) # a b c # 0 a_1 b_1 c_1 # 1 a_2 b_2 c_2 print(pd.merge(df_ab, df_ac, on='a')) # a b c # 0 a_1 b_1 c_1 # 1 a_2 b_2 c_2 df_ac_ = df_ac.rename(columns={'a': 'a_'}) print(df_ac_) # a_ c # 0 a_1 c_1 # 1 a_2 c_2 # 2 a_4 c_4 print(pd.merge(df_ab, df_ac_, left_on='a', right_on='a_')) # a b a_ c # 0 a_1 b_1 a_1 c_1 # 1 a_2 b_2 a_2 c_2 print(pd.merge(df_ab, df_ac_, left_on='a', right_on='a_').drop(columns='a_')) # a b c # 0 a_1 b_1 c_1 # 1 a_2 b_2 c_2 print(pd.merge(df_ab, df_ac, on='a', how='inner')) # a b c # 0 a_1 b_1 c_1 # 1 a_2 b_2 c_2 print(pd.merge(df_ab, df_ac, on='a', how='left')) # a b c # 0 a_1 b_1 c_1 # 1 a_2 b_2 c_2 # 2 a_3 b_3 NaN print(pd.merge(df_ab, df_ac, on='a', how='right')) # a b c # 0 a_1 b_1 c_1 # 1 a_2 b_2 c_2 # 2 a_4 NaN c_4 print(pd.merge(df_ab, df_ac, on='a', how='outer')) # a b c # 0 a_1 b_1 c_1 # 1 a_2 b_2 c_2 # 2 a_3 b_3 NaN # 3 a_4 NaN c_4 print(pd.merge(df_ab, df_ac, on='a', how='inner', indicator=True)) # a b c _merge # 0 a_1 b_1 c_1 both # 1 a_2 b_2 c_2 both print(pd.merge(df_ab, df_ac, on='a', how='outer', indicator=True)) # a b c _merge # 0 a_1 b_1 c_1 both # 1 a_2 b_2 c_2 both # 2 a_3 b_3 NaN left_only # 3 a_4 NaN c_4 right_only print(pd.merge(df_ab, df_ac, on='a', how='outer', indicator='indicator')) # a b c indicator # 0 a_1 b_1 c_1 both # 1 a_2 b_2 c_2 both # 2 a_3 b_3 NaN left_only # 3 a_4 NaN c_4 right_only df_ac_b = df_ac.rename(columns={'c': 'b'}) print(df_ac_b) # a b # 0 a_1 c_1 # 1 a_2 c_2 # 2 a_4 c_4 print(pd.merge(df_ab, df_ac_b, on='a')) # a b_x b_y # 0 a_1 b_1 c_1 # 1 a_2 b_2 c_2 print(pd.merge(df_ab, df_ac_b, on='a', suffixes=['_left', '_right'])) # a b_left b_right # 0 a_1 b_1 c_1 # 1 a_2 b_2 c_2 df_abx = df_ab.assign(x=['x_2', 'x_2', 'x_3']) df_acx = df_ac.assign(x=['x_1', 'x_2', 'x_2']) print(df_abx) # a b x # 0 a_1 b_1 x_2 # 1 a_2 b_2 x_2 # 2 a_3 b_3 x_3 print(df_acx) # a c x # 0 a_1 c_1 x_1 # 1 a_2 c_2 x_2 # 2 a_4 c_4 x_2 print(pd.merge(df_abx, df_acx)) # a b x c # 0 a_2 b_2 x_2 c_2 print(pd.merge(df_abx, df_acx, on=['a', 'x'])) # a b x c # 0 a_2 b_2 x_2 c_2 print(pd.merge(df_abx, df_acx, on='a')) # a b x_x c x_y # 0 a_1 b_1 x_2 c_1 x_1 # 1 a_2 b_2 x_2 c_2 x_2 df_acx_ = df_acx.rename(columns={'x': 'x_'}) print(df_acx_) # a c x_ # 0 a_1 c_1 x_1 # 1 a_2 c_2 x_2 # 2 a_4 c_4 x_2 print(pd.merge(df_abx, df_acx_, left_on=['a', 'x'], right_on=['a', 'x_'])) # a b x c x_ # 0 a_2 b_2 x_2 c_2 x_2 print(pd.merge(df_abx, df_acx, on=['a', 'x'], how='inner')) # a b x c # 0 a_2 b_2 x_2 c_2 print(pd.merge(df_abx, df_acx, on=['a', 'x'], how='left')) # a b x c # 0 a_1 b_1 x_2 NaN # 1 a_2 b_2 x_2 c_2 # 2 a_3 b_3 x_3 NaN print(pd.merge(df_abx, df_acx, on=['a', 'x'], how='right')) # a b x c # 0 a_2 b_2 x_2 c_2 # 1 a_1 NaN x_1 c_1 # 2 a_4 NaN x_2 c_4 print(pd.merge(df_abx, df_acx, on=['a', 'x'], how='outer')) # a b x c # 0 a_1 b_1 x_2 NaN # 1 a_2 b_2 x_2 c_2 # 2 a_3 b_3 x_3 NaN # 3 a_1 NaN x_1 c_1 # 4 a_4 NaN x_2 c_4 print(pd.merge(df_abx, df_acx, on=['a', 'x'], how='outer', sort=True)) # a b x c # 0 a_1 NaN x_1 c_1 # 1 a_1 b_1 x_2 NaN # 2 a_2 b_2 x_2 c_2 # 3 a_3 b_3 x_3 NaN # 4 a_4 NaN x_2 c_4 df_ac_i = df_ac.set_index('a') print(df_ac_i) # c # a # a_1 c_1 # a_2 c_2 # a_4 c_4 print(pd.merge(df_ab, df_ac_i, left_on='a', right_index=True)) # a b c # 0 a_1 b_1 c_1 # 1 a_2 b_2 c_2 df_ab_i = df_ab.set_index('a') print(df_ab_i) # b # a # a_1 b_1 # a_2 b_2 # a_3 b_3 print(pd.merge(df_ab_i, df_ac_i, left_index=True, right_index=True)) # b c # a # a_1 b_1 c_1 # a_2 b_2 c_2 print(df_ab_i) # b # a # a_1 b_1 # a_2 b_2 # a_3 b_3 print(df_ac_i) # c # a # a_1 c_1 # a_2 c_2 # a_4 c_4 print(df_ab_i.join(df_ac_i)) # b c # a # a_1 b_1 c_1 # a_2 b_2 c_2 # a_3 b_3 NaN print(df_ab_i.join(df_ac_i, how='inner')) # b c # a # a_1 b_1 c_1 # a_2 b_2 c_2 print(df_ab) # a b # 0 a_1 b_1 # 1 a_2 b_2 # 2 a_3 b_3 print(df_ab.join(df_ac_i, on='a')) # a b c # 0 a_1 b_1 c_1 # 1 a_2 b_2 c_2 # 2 a_3 b_3 NaN df_ad_i = pd.DataFrame({'a': ['a_1', 'a_4', 'a_5'], 'd': ['d_1', 'd_4', 'd_5']}).set_index('a') print(df_ad_i) # d # a # a_1 d_1 # a_4 d_4 # a_5 d_5 print(df_ab_i.join([df_ac_i, df_ad_i])) # b c d # a # a_1 b_1 c_1 d_1 # a_2 b_2 c_2 NaN # a_3 b_3 NaN NaN print(df_ac_i.join([df_ad_i, df_ab_i])) # c d b # a # a_1 c_1 d_1 b_1 # a_2 c_2 NaN b_2 # a_4 c_4 d_4 NaN
nkmk/python-snippets
notebook/pandas_merge_join.py
Python
mit
5,590
package me.alb_i986.hbs.utils; import java.util.*; public class Utility { public static List<String> stringToList(String input){ List<String> list = new ArrayList<String>(); for(String element : input.split("-")) { list.add(element); } return list; } }
alb-i986/HorseBettingSystem
src/main/java/me/alb_i986/hbs/utils/Utility.java
Java
mit
309
import { SearchFunction, GetSrcPageFunction, handleNoResult, handleNetWorkError } from '../helpers' import axios, { AxiosResponse } from 'axios' export const getSrcPage: GetSrcPageFunction = async text => { const suggests = await getSuggests(text).catch(() => null) if (suggests) { const tarId = suggests.searchResults && suggests.searchResults[0] && suggests.searchResults[0].tarId if (tarId) { return `https://www.mojidict.com/details/${tarId}` } } return 'https://www.mojidict.com' } interface FetchWordResult { details?: Array<{ objectId: string title: string wordId: string }> examples?: Array<{ objectId: string subdetailsId: string title: string trans: string wordId: string }> subdetails?: Array<{ detailsId: string objectId: string title: string wordId: string }> word?: { accent: string objectId: string pron: string spell: string tts: string } } interface SuggestsResult { originalSearchText: string searchResults?: Array<{ objectId: string searchText: string tarId: string }> words?: Array<{ accent: string excerpt: string objectId: string pron: string romaji: string spell: string }> } interface FetchTtsResult { result: { code: number result?: { text: string url: string identity: string existed: boolean msg: string } } } export interface MojidictResult { word?: { tarId: string spell: string pron: string tts?: string } details?: Array<{ objectId: string title: string subdetails?: Array<{ objectId: string title: string examples?: Array<{ objectId: string title: string trans: string }> }> }> releated?: Array<{ title: string excerpt: string }> } export const search: SearchFunction<MojidictResult> = async ( text, config, profile, payload ) => { const suggests = await getSuggests(text) const tarId = suggests.searchResults?.[0]?.tarId if (!tarId) { return handleNoResult() } const { data: { result: wordResult } }: AxiosResponse<{ result: FetchWordResult }> = await axios({ method: 'post', url: 'https://api.mojidict.com/parse/functions/fetchWord_v2', headers: { 'content-type': 'text/plain' }, data: requestPayload({ wordId: tarId }) }) const result: MojidictResult = {} if (wordResult && (wordResult.details || wordResult.word)) { if (wordResult.word) { result.word = { tarId, spell: wordResult.word.spell, pron: `${wordResult.word.pron || ''} ${wordResult.word.accent || ''}` } } if (wordResult.details) { result.details = wordResult.details.map(detail => ({ objectId: detail.objectId, title: detail.title, subdetails: wordResult?.subdetails ?.filter(subdetail => subdetail.detailsId === detail.objectId) .map(subdetail => ({ objectId: subdetail.objectId, title: subdetail.title, examples: wordResult?.examples?.filter( example => example.subdetailsId === subdetail.objectId ) })) })) } if (suggests.words && suggests?.words.length > 1) { result.releated = suggests.words .map(word => ({ title: `${word.spell} | ${word.pron || ''} ${word.accent || ''}`, excerpt: word.excerpt })) .slice(1) } if (result.word && config.autopron.cn.dict === 'mojidict') { result.word.tts = await getTTS(tarId, 102) return { result, audio: { py: result.word.tts } } } return { result } } return handleNoResult() } async function getSuggests(text: string): Promise<SuggestsResult> { try { const { data: { result } }: AxiosResponse<{ result?: SuggestsResult }> = await axios({ method: 'post', url: 'https://api.mojidict.com/parse/functions/search_v3', headers: { 'content-type': 'text/plain' }, data: requestPayload({ langEnv: 'zh-CN_ja', needWords: true, searchText: text }) }) return result || handleNoResult() } catch (e) { return handleNetWorkError() } } /** * @param tarId word id * @param tarType 102 word, 103 sentence */ export async function getTTS( tarId: string, tarType: 102 | 103 ): Promise<string> { try { const { data }: AxiosResponse<FetchTtsResult> = await axios({ method: 'post', url: 'https://api.mojidict.com/parse/functions/fetchTts_v2', headers: { 'content-type': 'text/plain' }, data: requestPayload({ tarId, tarType }) }) return data.result?.result?.url || '' } catch (e) { if (process.env.DEBUG) { console.error(e) } } return '' } export type GetTTS = typeof getTTS function requestPayload(data: object) { return JSON.stringify({ _ApplicationId: process.env.MOJI_ID, _ClientVersion: 'js2.12.0', _InstallationId: getInstallationId(), ...data }) } function getInstallationId() { return s() + s() + '-' + s() + '-' + s() + '-' + s() + '-' + s() + s() + s() } function s() { return Math.floor(65536 * (1 + Math.random())) .toString(16) .substring(1) }
Crimx/crx-saladict
src/components/dictionaries/mojidict/engine.ts
TypeScript
mit
5,361
using System; using System.Collections.Generic; using Xamarin.Forms; namespace Combinado { public partial class PurchaseOrderPage : ContentPage { private List<Product> products; private List<Client> clients; public PurchaseOrderPage () { Title = "Pedido"; InitializeComponents ().ConfigureAwait(false); } async void OrderButton_Clicked (object sender, EventArgs e) { PurchaseOrder order = new PurchaseOrder () { UnitPrice = float.Parse(priceEntry.Text), Quantity = float.Parse(quantityStepper.Text), Details = detailsEditor.Text, Timestamp = DateTime.Now }; order.Product = products[ productPicker.SelectedIndex ]; order.Client = clients [clientPicker.SelectedIndex]; // Falta agregar location con una Dependency bool result = await PurchaseOrderService.Instance.Create( order ); if( result ) { await DisplayAlert ("Combinado", "Orden agregada", "OK"); Navigation.PopAsync (); } else { DisplayAlert ("Combinado", "Error", "OK"); } } } }
nchicas/Combinado
Combinado/Pages/PurchaseOrderPage.cs
C#
mit
1,030
require 'thor' module CodeclimateCi class CLI < Thor method_option :codeclimate_api_token, required: true method_option :repo_id, required: true method_option :branch_name method_option :retry_count method_option :sleep_time desc('check', 'Check code quality with CodeClimate') def check CodeclimateCi.configuration.load_from_options(options) ExceptionsCheck.new( api_requester: api_requester, branch_name: branch_name ).perform if compare_gpa.worse?(branch_name) exit_worse_code! else exit_good_code! end end default_task :check private def compare_gpa @compare_gpa ||= CompareGpa.new(api_requester) end def api_requester @api_requester ||= ApiRequester.new( CodeclimateCi.configuration.codeclimate_api_token, CodeclimateCi.configuration.repo_id ) end def diff compare_gpa.diff(branch_name) end def branch_name CodeclimateCi.configuration.branch_name end def exit_worse_code! Report.worse_code(diff) exit(1) end def exit_good_code! Report.good_code(diff) exit(0) end end end
fs/codeclimate_ci
lib/codeclimate_ci/cli.rb
Ruby
mit
1,219
''' Created on Apr 28, 2011 @author: Bartosz Alchimowicz ''' ############################ # Collection # ############################ class ScreenSpec(object): def __init__(self): self.children = [] def append(self, screen): assert isinstance(screen, Screen) self.children.append(screen) return self ############################ # Header # ############################ class Screen(object): def __init__(self, name, children = None): assert isinstance(name, basestring) self.name = name self.children = [] if children: assert isinstance(children, list) for child in children: self.append(child) def append(self, child): assert isinstance(child, Component) self.children.append(child) return self ############################ # Component # ############################ class Component(object): def __init__(self, identifier, name): assert identifier is not None self.identifier = identifier self.name = name class ComoundComponent(Component): def __init__(self, identifier, name): Component.__init__(self, identifier, name) self.children = [] def append(self, child): assert isinstance(child, Component) self.children.append(child) return self class StaticValueContainer(object): def __init__(self): self._static_values = None def _set_static_values(self, values): raise Exception("Please overwrite") def _get_static_values(self): return self._static_values class ComoundValuesContainer(object): def __init__(self): self._grid = None # 2d lisl ############################ # Basic Components # ############################ class Entity(Component): def __init__(self, identifier): Component.__init__(self, identifier, None) class Button(Component, StaticValueContainer): def __init__(self, identifier): Component.__init__(self, identifier, "BUTTON") StaticValueContainer.__init__(self) def _set_static_values(self, values): if len(values) != 1: raise Exception("Wrong number of static values") self._static_values = values static_values = property(StaticValueContainer._get_static_values, _set_static_values) class Link(Component, StaticValueContainer): def __init__(self, identifier): Component.__init__(self, identifier, "LINK") StaticValueContainer.__init__(self) def _set_static_values(self, values): if len(values) != 1: raise Exception("Wrong number of static values") self._static_values = values static_values = property(StaticValueContainer._get_static_values, _set_static_values) class Image(Component): def __init__(self, identifier): Component.__init__(self, identifier, "IMAGE") class StaticText(Component, StaticValueContainer): def __init__(self, identifier): Component.__init__(self, identifier, "STATIC_TEXT") StaticValueContainer.__init__(self) def _set_static_values(self, values): if len(values) != 1: raise Exception("Wrong number of static values") self._static_values = values static_values = property(StaticValueContainer._get_static_values, _set_static_values) class DynamicText(Component): def __init__(self, identifier): Component.__init__(self, identifier, "DYNAMIC_TEXT") class EditBox(Component, StaticValueContainer): def __init__(self, identifier): Component.__init__(self, identifier, "EDIT_BOX") StaticValueContainer.__init__(self) def _set_static_values(self, values): if len(values) != 1: raise Exception("Wrong number of static values") self._static_values = values static_values = property(StaticValueContainer._get_static_values, _set_static_values) class CheckBox(Component): def __init__(self, identifier): Component.__init__(self, identifier, "CHECK_BOX") class RadioButton(Component): def __init__(self, identifier): Component.__init__(self, identifier, "RADIO_BUTTON") class TextArea(Component, StaticValueContainer): def __init__(self, identifier): Component.__init__(self, identifier, "TEXT_AREA") StaticValueContainer.__init__(self) def _set_static_values(self, values): if len(values) == 0: raise Exception("Wrong number of static values") self._static_values = values static_values = property(StaticValueContainer._get_static_values, _set_static_values) class Password(Component): def __init__(self, identifier): Component.__init__(self, identifier, "PASSWORD") class Custom(Component): def __init__(self, identifier): assert False and "Modify screenspec.parser to add custom components" ############################ # Semi-Compound Components # ############################ class ComboBox(ComoundComponent, StaticValueContainer): def __init__(self, identifier): ComoundComponent.__init__(self, identifier, "COMBO_BOX") StaticValueContainer.__init__(self) def _set_static_values(self, values): if len(values) == 0: raise Exception("Wrong number of static values") self._static_values = values static_values = property(StaticValueContainer._get_static_values, _set_static_values) class ListBox(ComoundComponent, StaticValueContainer): def __init__(self, identifier): ComoundComponent.__init__(self, identifier, "LIST_BOX") StaticValueContainer.__init__(self) def _set_static_values(self, values): if len(values) == 0: raise Exception("Wrong number of static values") self._static_values = values static_values = property(StaticValueContainer._get_static_values, _set_static_values) class RadioButtons(ComoundComponent, StaticValueContainer): def __init__(self, identifier): ComoundComponent.__init__(self, identifier, "RADIO_BUTTONS") StaticValueContainer.__init__(self) def _set_static_values(self, values): if len(values) == 0: raise Exception("Wrong number of static values") self._static_values = values static_values = property(StaticValueContainer._get_static_values, _set_static_values) class CheckBoxes(ComoundComponent, StaticValueContainer): def __init__(self, identifier): ComoundComponent.__init__(self, identifier, "CHECK_BOXES") StaticValueContainer.__init__(self) def _set_static_values(self, values): if len(values) == 0: raise Exception("Wrong number of static values") self._static_values = values static_values = property(StaticValueContainer._get_static_values, _set_static_values) ############################ # Compound Components # ############################ class Simple(ComoundComponent, ComoundValuesContainer): def __init__(self, identifier): ComoundComponent.__init__(self, identifier, "SIMPLE") ComoundValuesContainer.__init__(self) class List(ComoundComponent, ComoundValuesContainer): def __init__(self, identifier): ComoundComponent.__init__(self, identifier, "LIST") ComoundValuesContainer.__init__(self) class Table(ComoundComponent, ComoundValuesContainer): def __init__(self, identifier): ComoundComponent.__init__(self, identifier, "TABLE") ComoundValuesContainer.__init__(self) ############################ # StaticValues # ############################ class StaticValue(object): def __init__(self, value, selected = False): assert value != None self.value = value self.selected = selected
perfidia/screensketch
src/screensketch/screenspec/model.py
Python
mit
7,161
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="en"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About StarCoin</source> <translation>About StarCoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;StarCoin&lt;/b&gt; version</source> <translation>&lt;b&gt;StarCoin&lt;/b&gt; version</translation> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The StarCoin developers</source> <translation type="unfinished"></translation> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Address Book</translation> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Double-click to edit address or label</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Create a new address</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copy the currently selected address to the system clipboard</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;New Address</translation> </message> <message> <location line="-46"/> <source>These are your StarCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>These are your StarCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</translation> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation>&amp;Copy Address</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Show &amp;QR Code</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a StarCoin address</source> <translation>Sign a message to prove you own a StarCoin address</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation></translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation></translation> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified StarCoin address</source> <translation>Verify a message to ensure it was signed with a specified StarCoin address</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Verify Message</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Delete</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>Copy &amp;Label</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>&amp;Edit</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation>Export Address Book Data</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Error exporting</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Could not write to file %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Label</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Address</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(no label)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Passphrase Dialog</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Enter passphrase</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>New passphrase</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Repeat new passphrase</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"></translation> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Encrypt wallet</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>This operation needs your wallet passphrase to unlock the wallet.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Unlock wallet</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>This operation needs your wallet passphrase to decrypt the wallet.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Decrypt wallet</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Change passphrase</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Enter the old and new passphrase to the wallet.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Confirm wallet encryption</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Are you sure you wish to encrypt your wallet?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation></translation> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Warning: The Caps Lock key is on!</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>Wallet encrypted</translation> </message> <message> <location line="-58"/> <source>StarCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation>StarCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Wallet encryption failed</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>The supplied passphrases do not match.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>Wallet unlock failed</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>The passphrase entered for the wallet decryption was incorrect.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Wallet decryption failed</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Wallet passphrase was successfully changed.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+282"/> <source>Sign &amp;message...</source> <translation>Sign &amp;message...</translation> </message> <message> <location line="+251"/> <source>Synchronizing with network...</source> <translation>Synchronizing with network...</translation> </message> <message> <location line="-319"/> <source>&amp;Overview</source> <translation>&amp;Overview</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Show general overview of wallet</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Transactions</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Browse transaction history</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation>&amp;Address Book</translation> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation>Edit the list of stored addresses and labels</translation> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation>&amp;Receive coins</translation> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation>Show the list of addresses for receiving payments</translation> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation>&amp;Send coins</translation> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation>E&amp;xit</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Quit application</translation> </message> <message> <location line="+6"/> <source>Show information about StarCoin</source> <translation>Show information about StarCoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>About &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Show information about Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Options...</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Encrypt Wallet...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup Wallet...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Change Passphrase...</translation> </message> <message numerus="yes"> <location line="+259"/> <source>~%n block(s) remaining</source> <translation> <numerusform>~%n block remaining</numerusform> <numerusform>~%n blocks remaining</numerusform> </translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation>Downloaded %1 of %2 blocks of transaction history (%3% done).</translation> </message> <message> <location line="-256"/> <source>&amp;Export...</source> <translation>&amp;Export...</translation> </message> <message> <location line="-64"/> <source>Send coins to a StarCoin address</source> <translation>Send coins to a StarCoin address</translation> </message> <message> <location line="+47"/> <source>Modify configuration options for StarCoin</source> <translation>Modify configuration options for StarCoin</translation> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation>Export the data in the current tab to a file</translation> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation>Encrypt or decrypt wallet</translation> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation>Backup wallet to another location</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Change the passphrase used for wallet encryption</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation>&amp;Debug window</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Open debugging and diagnostic console</translation> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>&amp;Verify message...</translation> </message> <message> <location line="-202"/> <source>StarCoin</source> <translation>StarCoin</translation> </message> <message> <location line="+0"/> <source>Wallet</source> <translation>Wallet</translation> </message> <message> <location line="+180"/> <source>&amp;About StarCoin</source> <translation>&amp;About StarCoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Show / Hide</translation> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation type="unfinished">Unlock wallet</translation> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"></translation> </message> <message> <location line="+35"/> <source>&amp;File</source> <translation>&amp;File</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;Settings</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;Help</translation> </message> <message> <location line="+12"/> <source>Tabs toolbar</source> <translation>Tabs toolbar</translation> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation>Actions toolbar</translation> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+0"/> <location line="+60"/> <source>StarCoin client</source> <translation>StarCoin client</translation> </message> <message numerus="yes"> <location line="+75"/> <source>%n active connection(s) to StarCoin network</source> <translation> <numerusform>%n active connection to StarCoin network</numerusform> <numerusform>%n active connections to StarCoin network</numerusform> </translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation>Downloaded %1 blocks of transaction history.</translation> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation></translation> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation></translation> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation></translation> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation></translation> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation></translation> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation> <numerusform>%n second ago</numerusform> <numerusform>%n seconds ago</numerusform> </translation> </message> <message> <location line="-312"/> <source>About StarCoin card</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>Show information about StarCoin card</source> <translation type="unfinished"></translation> </message> <message> <location line="+18"/> <source>&amp;Unlock Wallet...</source> <translation></translation> </message> <message numerus="yes"> <location line="+297"/> <source>%n minute(s) ago</source> <translation> <numerusform>%n minute ago</numerusform> <numerusform>%n minutes ago</numerusform> </translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation> <numerusform>%n hour ago</numerusform> <numerusform>%n hours ago</numerusform> </translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation> <numerusform>%n day ago</numerusform> <numerusform>%n days ago</numerusform> </translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation>Up to date</translation> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation>Catching up...</translation> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation>Last received block was generated %1.</translation> </message> <message> <location line="+59"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation></translation> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation>Confirm transaction fee</translation> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>Sent transaction</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>Incoming transaction</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Date: %1 Amount: %2 Type: %3 Address: %4 </translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation>URI handling</translation> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid StarCoin address or malformed URI parameters.</source> <translation>URI can not be parsed! This can be caused by an invalid StarCoin address or malformed URI parameters.</translation> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</translation> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</translation> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation>Backup Wallet</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Wallet Data (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Backup Failed</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>There was an error trying to save the wallet data to the new location.</translation> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation> <numerusform>%n second</numerusform> <numerusform>%n seconds</numerusform> </translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation> <numerusform>%n minute</numerusform> <numerusform>%n minutes</numerusform> </translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation> <numerusform>%n hour</numerusform> <numerusform>%n hours</numerusform> </translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation> <numerusform>%n day</numerusform> <numerusform>%n days</numerusform> </translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoin.cpp" line="+109"/> <source>A fatal error occurred. StarCoin can no longer continue safely and will quit.</source> <translation>A fatal error occurred. StarCoin can no longer continue safely and will quit.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation>Network Alert</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"></translation> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"></translation> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation type="unfinished"></translation> </message> <message> <location line="+48"/> <source>Amount:</source> <translation type="unfinished">Amount:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"></translation> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"></translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"></translation> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"></translation> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"></translation> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"></translation> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"></translation> </message> <message> <location line="+45"/> <source>Amount</source> <translation type="unfinished">Amount</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished">Label</translation> </message> <message> <location line="+5"/> <source>Address</source> <translation type="unfinished">Address</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation type="unfinished">Date</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"></translation> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation type="unfinished">Confirmed</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"></translation> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation type="unfinished">Copy address</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished">Copy label</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation type="unfinished">Copy amount</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished">Copy transaction ID</translation> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation type="unfinished"></translation> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"></translation> </message> <message> <location line="+317"/> <source>highest</source> <translation></translation> </message> <message> <location line="+1"/> <source>high</source> <translation></translation> </message> <message> <location line="+1"/> <source>medium-high</source> <translation></translation> </message> <message> <location line="+1"/> <source>medium</source> <translation></translation> </message> <message> <location line="+4"/> <source>low-medium</source> <translation></translation> </message> <message> <location line="+1"/> <source>low</source> <translation></translation> </message> <message> <location line="+1"/> <source>lowest</source> <translation></translation> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"></translation> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"></translation> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"></translation> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation type="unfinished">(no label)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Edit Address</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Label</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>The label associated with this address book entry</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Address</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>The address associated with this address book entry. This can only be modified for sending addresses.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation>New receiving address</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>New sending address</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Edit receiving address</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Edit sending address</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>The entered address &quot;%1&quot; is already in the address book.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid StarCoin address.</source> <translation>The entered address &quot;%1&quot; is not a valid StarCoin address.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Could not unlock wallet.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>New key generation failed.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>StarCoin-Qt</source> <translation>StarCoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>version</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Usage:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>command-line options</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>UI options</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Set language, for example &quot;de_DE&quot; (default: system locale)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Start minimized</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Show splash screen on startup (default: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Options</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Main</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Pay transaction &amp;fee</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation></translation> </message> <message> <location line="+15"/> <source>Reserve</source> <translation></translation> </message> <message> <location line="+31"/> <source>Automatically start StarCoin after logging in to the system.</source> <translation>Automatically start StarCoin after logging in to the system.</translation> </message> <message> <location line="+3"/> <source>&amp;Start StarCoin on system login</source> <translation>&amp;Start StarCoin on system login</translation> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</translation> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation>&amp;Detach databases at shutdown</translation> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>&amp;Network</translation> </message> <message> <location line="+6"/> <source>Automatically open the StarCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automatically open the StarCoin client port on the router. This only works when your router supports UPnP and it is enabled.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Map port using &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the StarCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Connect to the StarCoin network through a SOCKS proxy (e.g. when connecting through Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Connect through SOCKS proxy:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;IP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP address of the proxy (e.g. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Port:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Port of the proxy (e.g. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Version:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>SOCKS version of the proxy (e.g. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Window</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Show only a tray icon after minimizing the window.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimize to the tray instead of the taskbar</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimize on close</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Display</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>User Interface &amp;language:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting StarCoin.</source> <translation>The user interface language can be set here. This setting will take effect after restarting StarCoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unit to show amounts in:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Choose the default subdivision unit to show in the interface and when sending coins.</translation> </message> <message> <location line="+9"/> <source>Whether to show StarCoin addresses in the transaction list or not.</source> <translation>Whether to show StarCoin addresses in the transaction list or not.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Display addresses in transaction list</translation> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation></translation> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation></translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Cancel</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Apply</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation>default</translation> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation>Warning</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting StarCoin.</source> <translation>This setting will take effect after restarting StarCoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>The supplied proxy address is invalid.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Form</translation> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the StarCoin network after a connection is established, but this process has not completed yet.</source> <translation>The displayed information may be out of date. Your wallet automatically synchronizes with the StarCoin network after a connection is established, but this process has not completed yet.</translation> </message> <message> <location line="-160"/> <source>Stake:</source> <translation>Stake:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Unconfirmed:</translation> </message> <message> <location line="-107"/> <source>Wallet</source> <translation>Wallet</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"></translation> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"></translation> </message> <message> <location line="+71"/> <source>Immature:</source> <translation>Immature:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Mined balance that has not yet matured</translation> </message> <message> <location line="+20"/> <source>Total:</source> <translation type="unfinished"></translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"></translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Recent transactions&lt;/b&gt;</translation> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</translation> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation>Total of coins that was staked, and do not yet count toward the current balance</translation> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation>out of sync</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR Code Dialog</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Request Payment</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Amount:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Label:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Message:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Save As...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Error encoding URI into QR Code.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>The entered amount is invalid, please check.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Resulting URI too long, try to reduce the text for label / message.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Save QR Code</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG Images (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Client name</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+348"/> <source>N/A</source> <translation>N/A</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Client version</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Information</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Using OpenSSL version</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Startup time</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Network</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Number of connections</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>On testnet</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Block chain</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Current number of blocks</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Estimated total blocks</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Last block time</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Open</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Command-line options</translation> </message> <message> <location line="+7"/> <source>Show the StarCoin-Qt help message to get a list with possible StarCoin command-line options.</source> <translation>Show the StarCoin-Qt help message to get a list with possible StarCoin command-line options.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Show</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Console</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Build date</translation> </message> <message> <location line="-104"/> <source>StarCoin - Debug window</source> <translation>StarCoin - Debug window</translation> </message> <message> <location line="+25"/> <source>StarCoin Core</source> <translation>StarCoin Core</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Debug log file</translation> </message> <message> <location line="+7"/> <source>Open the StarCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Open the StarCoin debug log file from the current data directory. This can take a few seconds for large log files.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Clear console</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the StarCoin RPC console.</source> <translation>Welcome to the StarCoin RPC console.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Send Coins</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"></translation> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"></translation> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"></translation> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"></translation> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"></translation> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"></translation> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation type="unfinished"></translation> </message> <message> <location line="+51"/> <source>Amount:</source> <translation type="unfinished">Amount:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 hack</source> <translation type="unfinished">123.456 hack {0.00 ?}</translation> </message> <message> <location line="-191"/> <source>Priority:</source> <translation type="unfinished"></translation> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"></translation> </message> <message> <location line="+32"/> <source>Fee:</source> <translation type="unfinished"></translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"></translation> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"></translation> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"></translation> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"></translation> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"></translation> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>Send to multiple recipients at once</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"></translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Remove all transaction fields</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Clear &amp;All</translation> </message> <message> <location line="+28"/> <source>Balance:</source> <translation>Balance:</translation> </message> <message> <location line="+16"/> <source>123.456 hack</source> <translation>123.456 hack</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Confirm the send action</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"></translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a StarCoin address (e.g. StarCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Enter a StarCoin address (e.g. StarCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation></translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copy amount</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation></translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation></translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation></translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation></translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation></translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation></translation> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Confirm send coins</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Are you sure you want to send %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> and </translation> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation>The recipient address is not valid, please recheck.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>The amount to pay must be larger than 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>The amount exceeds your balance.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>The total exceeds your balance when the %1 transaction fee is included.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Duplicate address found, can only send to each address once per send operation.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation>Error: Transaction creation failed.</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</translation> </message> <message> <location line="+251"/> <source>WARNING: Invalid StarCoin address</source> <translation></translation> </message> <message> <location line="+13"/> <source>(no label)</source> <translation type="unfinished">(no label)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation></translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Form</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>A&amp;mount:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Pay &amp;To:</translation> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation>Enter a label for this address to add it to your address book</translation> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation>&amp;Label:</translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. StarCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation></translation> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation>Choose address from address book</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Paste address from clipboard</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Remove this recipient</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a StarCoin address (e.g. StarCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Enter a StarCoin address (e.g. StarCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Signatures - Sign / Verify a Message</translation> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>&amp;Sign Message</translation> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. StarCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>The address to sign the message with (e.g. StarCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation>Choose an address from the address book</translation> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Paste address from clipboard</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Enter the message you want to sign here</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation>Copy the current signature to the system clipboard</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this StarCoin address</source> <translation>Sign the message to prove you own this StarCoin address</translation> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation>Reset all sign message fields</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Clear &amp;All</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>&amp;Verify Message</translation> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. StarCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>The address the message was signed with (e.g. StarCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified StarCoin address</source> <translation>Verify the message to ensure it was signed with the specified StarCoin address</translation> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation>Reset all verify message fields</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a StarCoin address (e.g. StarCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Enter a StarCoin address (e.g. StarCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Click &quot;Sign Message&quot; to generate signature</translation> </message> <message> <location line="+3"/> <source>Enter StarCoin signature</source> <translation>Enter StarCoin signature</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>The entered address is invalid.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Please check the address and try again.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>The entered address does not refer to a key.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Wallet unlock was cancelled.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Private key for the entered address is not available.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Message signing failed.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Message signed.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>The signature could not be decoded.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Please check the signature and try again.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>The signature did not match the message digest.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Message verification failed.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Message verified.</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation>Open until %1</translation> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation> <numerusform>Open for %n block</numerusform> <numerusform>Open for %n blocks</numerusform> </translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation></translation> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/unconfirmed</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 confirmations</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation> <numerusform>, broadcast through %n node</numerusform> <numerusform>, broadcast through %n nodes</numerusform> </translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Date</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Source</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generated</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>From</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>To</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>own address</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>label</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Credit</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation> <numerusform>matures in %n more block</numerusform> <numerusform>matures in %n more blocks</numerusform> </translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>not accepted</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debit</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Transaction fee</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Net amount</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Message</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Comment</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Transaction ID</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Debug information</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transaction</translation> </message> <message> <location line="+5"/> <source>Inputs</source> <translation>Inputs</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Amount</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>true</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>false</translation> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation>, has not been successfully broadcast yet</translation> </message> <message> <location line="+35"/> <source>unknown</source> <translation>unknown</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Transaction details</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>This pane shows a detailed description of the transaction</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation>Date</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Type</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Address</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Amount</translation> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation>Open until %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>Confirmed (%1 confirmations)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation> <numerusform>Open for %n more block</numerusform> <numerusform>Open for %n more blocks</numerusform> </translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation></translation> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation></translation> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation></translation> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation></translation> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation></translation> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>This block was not received by any other nodes and will probably not be accepted!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generated but not accepted</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>Received with</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Received from</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Sent to</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Payment to yourself</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Mined</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Transaction status. Hover over this field to show number of confirmations.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Date and time that the transaction was received.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Type of transaction.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Destination address of transaction.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Amount removed from or added to balance.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation>All</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Today</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>This week</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>This month</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Last month</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>This year</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Range...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Received with</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Sent to</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>To yourself</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Mined</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Other</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Enter address or label to search</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Min amount</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copy address</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copy label</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copy amount</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Copy transaction ID</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Edit label</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Show transaction details</translation> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation>Export Transaction Data</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confirmed</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Date</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Type</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Label</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Address</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Amount</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Error exporting</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Could not write to file %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Range:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>to</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation>Sending...</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+33"/> <source>StarCoin version</source> <translation>StarCoin version</translation> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>Usage:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or StarCoind</source> <translation>Send command to -server or StarCoind</translation> </message> <message> <location line="+1"/> <source>List commands</source> <translation>List commands</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>Get help for a command</translation> </message> <message> <location line="+2"/> <source>Options:</source> <translation>Options:</translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: StarCoin.conf)</source> <translation>Specify configuration file (default: StarCoin.conf)</translation> </message> <message> <location line="+1"/> <source>Specify pid file (default: StarCoind.pid)</source> <translation>Specify pid file (default: StarCoind.pid)</translation> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation>Specify wallet file (within data directory)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Specify data directory</translation> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Set database cache size in megabytes (default: 25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation>Set database disk log size in megabytes (default: 100)</translation> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</translation> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Maintain at most &lt;n&gt; connections to peers (default: 125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Connect to a node to retrieve peer addresses, and disconnect</translation> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation>Specify your own public address</translation> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation>Bind to given address. Use [host]:port notation for IPv6</translation> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation></translation> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Threshold for disconnecting misbehaving peers (default: 100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</translation> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation></translation> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation>Detach block and address databases. Increases shutdown time (default: 0)</translation> </message> <message> <location line="+109"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation></translation> </message> <message> <location line="-5"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation></translation> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation></translation> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation>Accept command line and JSON-RPC commands</translation> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation></translation> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation></translation> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation></translation> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation></translation> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation>Run in the background as a daemon and accept commands</translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>Use the test network</translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accept connections from outside (default: 1 if no -proxy or -connect)</translation> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation></translation> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation></translation> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</translation> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</translation> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong StarCoin will not work properly.</source> <translation>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong StarCoin will not work properly.</translation> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</translation> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</translation> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Attempt to recover private keys from a corrupt wallet.dat</translation> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation>Block creation options:</translation> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation>Connect only to the specified node(s)</translation> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Discover own IP address (default: 1 when listening and no -externalip)</translation> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Failed to listen on any port. Use -listen=0 if you want this.</translation> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation>Find peers using DNS lookup (default: 1)</translation> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation>Sync checkpoints policy (default: strict)</translation> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Invalid -tor address: &apos;%s&apos;</translation> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation></translation> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</translation> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</translation> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Output extra debugging information. Implies all other -debug* options</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Output extra network debugging information</translation> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation>Prepend debug output with timestamp</translation> </message> <message> <location line="+35"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</translation> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Select the version of socks proxy to use (4-5, default: 5)</translation> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Send trace/debug info to console instead of debug.log file</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Send trace/debug info to debugger</translation> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Set maximum block size in bytes (default: 250000)</translation> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Set minimum block size in bytes (default: 0)</translation> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Shrink debug.log file on client startup (default: 1 when no -debug)</translation> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Specify connection timeout in milliseconds (default: 5000)</translation> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation></translation> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Use UPnP to map the listening port (default: 0)</translation> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Use UPnP to map the listening port (default: 1 when listening)</translation> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Use proxy to reach tor hidden services (default: same as -proxy)</translation> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation>Username for JSON-RPC connections</translation> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation></translation> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation></translation> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation>Warning: Disk space is low!</translation> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Warning: This version is obsolete, upgrade required!</translation> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation></translation> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation>Password for JSON-RPC connections</translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=StarCoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;StarCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"></translation> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished">Find peers using internet relay chat (default: 1) {0)?}</translation> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"></translation> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation></translation> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Allow JSON-RPC connections from specified IP address</translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</translation> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Execute command when the best block changes (%s in cmd is replaced by block hash)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</translation> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation></translation> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation></translation> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"></translation> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>Upgrade wallet to latest format</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Set key pool size to &lt;n&gt; (default: 100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Rescan the block chain for missing wallet transactions</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation>How many blocks to check at startup (default: 2500, 0 = all)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation>How thorough the block verification is (0-6, default: 1)</translation> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation>Imports blocks from external blk000?.dat file</translation> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Use OpenSSL (https) for JSON-RPC connections</translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>Server certificate file (default: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Server private key (default: server.pem)</translation> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"></translation> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation></translation> </message> <message> <location line="-158"/> <source>This help message</source> <translation>This help message</translation> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation>Wallet %s resides outside data directory %s.</translation> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. StarCoin is probably already running.</source> <translation>Cannot obtain a lock on data directory %s. StarCoin is probably already running.</translation> </message> <message> <location line="-98"/> <source>StarCoin</source> <translation>StarCoin</translation> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Unable to bind to %s on this computer (bind returned error %d, %s)</translation> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation>Connect through socks proxy</translation> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Allow DNS lookups for -addnode, -seednode and -connect</translation> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation>Loading addresses...</translation> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation>Error loading blkindex.dat</translation> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Error loading wallet.dat: Wallet corrupted</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of StarCoin</source> <translation>Error loading wallet.dat: Wallet requires newer version of StarCoin</translation> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart StarCoin to complete</source> <translation>Wallet needed to be rewritten: restart StarCoin to complete</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>Error loading wallet.dat</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Invalid -proxy address: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Unknown network specified in -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Unknown -socks proxy version requested: %i</translation> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Cannot resolve -bind address: &apos;%s&apos;</translation> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Cannot resolve -externalip address: &apos;%s&apos;</translation> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation>Error: could not start node</translation> </message> <message> <location line="+11"/> <source>Sending...</source> <translation>Sending...</translation> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>Invalid amount</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>Insufficient funds</translation> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation>Loading block index...</translation> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Add a node to connect to and attempt to keep the connection open</translation> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. StarCoin is probably already running.</source> <translation>Unable to bind to %s on this computer. StarCoin is probably already running.</translation> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation>Fee per KB to add to transactions you send</translation> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation></translation> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation>Loading wallet...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>Cannot downgrade wallet</translation> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation>Cannot initialize keypool</translation> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>Cannot write default address</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>Rescanning...</translation> </message> <message> <location line="+5"/> <source>Done loading</source> <translation>Done loading</translation> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation>To use the %s option</translation> </message> <message> <location line="+14"/> <source>Error</source> <translation>Error</translation> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</translation> </message> </context> </TS>
coinstar/star
src/qt/locale/bitcoin_en.ts
TypeScript
mit
124,082
/* * Created by SharpDevelop. * User: lexli * Date: 2008-12-14 * Time: 14:08 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Windows.Forms; using Lextm.SharpSnmpLib.Messaging; using Lextm.SharpSnmpLib.Objects; using Lextm.SharpSnmpLib.Pipeline; using Lextm.SharpSnmpLib.Security; using RemObjects.Mono.Helpers; namespace Lextm.SharpSnmpLib.Agent { /// <summary> /// Description of MainForm. /// </summary> public partial class MainForm : Form { private readonly SnmpEngine _engine; private const string StrAllUnassigned = "All Unassigned"; public MainForm() { // TODO: this is a hack. review it later. var store = new ObjectStore(); store.Add(new SysDescr()); store.Add(new SysObjectId()); store.Add(new SysUpTime()); store.Add(new SysContact()); store.Add(new SysName()); store.Add(new SysLocation()); store.Add(new SysServices()); store.Add(new SysORLastChange()); store.Add(new SysORTable()); store.Add(new IfNumber()); store.Add(new IfTable()); var users = new UserRegistry(); users.Add(new OctetString("neither"), DefaultPrivacyProvider.DefaultPair); users.Add(new OctetString("authen"), new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication")))); users.Add(new OctetString("privacy"), new DESPrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication")))); var getv1 = new GetV1MessageHandler(); var getv1Mapping = new HandlerMapping("v1", "GET", getv1); var getv23 = new GetMessageHandler(); var getv23Mapping = new HandlerMapping("v2,v3", "GET", getv23); var setv1 = new SetV1MessageHandler(); var setv1Mapping = new HandlerMapping("v1", "SET", setv1); var setv23 = new SetMessageHandler(); var setv23Mapping = new HandlerMapping("v2,v3", "SET", setv23); var getnextv1 = new GetNextV1MessageHandler(); var getnextv1Mapping = new HandlerMapping("v1", "GETNEXT", getnextv1); var getnextv23 = new GetNextMessageHandler(); var getnextv23Mapping = new HandlerMapping("v2,v3", "GETNEXT", getnextv23); var getbulk = new GetBulkMessageHandler(); var getbulkMapping = new HandlerMapping("v2,v3", "GETBULK", getbulk); var v1 = new Version1MembershipProvider(new OctetString("public"), new OctetString("public")); var v2 = new Version2MembershipProvider(new OctetString("public"), new OctetString("public")); var v3 = new Version3MembershipProvider(); var membership = new ComposedMembershipProvider(new IMembershipProvider[] { v1, v2, v3 }); var handlerFactory = new MessageHandlerFactory(new[] { getv1Mapping, getv23Mapping, setv1Mapping, setv23Mapping, getnextv1Mapping, getnextv23Mapping, getbulkMapping }); var pipelineFactory = new SnmpApplicationFactory(new RollingLogger(), store, membership, handlerFactory); _engine = new SnmpEngine(pipelineFactory, new Listener { Users = users }, new EngineGroup()); _engine.ExceptionRaised += (sender, e) => MessageBox.Show(e.Exception.ToString()); InitializeComponent(); if (PlatformSupport.Platform == PlatformType.Windows) { // FIXME: work around a Mono WinForms issue. Icon = Properties.Resources.network_server; } actEnabled.Image = Properties.Resources.media_playback_start; tstxtPort.Text = @"161"; tscbIP.Items.Add(StrAllUnassigned); foreach (IPAddress address in Dns.GetHostEntry(string.Empty).AddressList.Where(address => !address.IsIPv6LinkLocal)) { tscbIP.Items.Add(address); } tscbIP.SelectedIndex = 0; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions")] private void StartListeners() { _engine.Listener.ClearBindings(); int port = int.Parse(tstxtPort.Text, CultureInfo.InvariantCulture); if (tscbIP.Text == StrAllUnassigned) { #if !__MonoCS__ if (Socket.OSSupportsIPv4) { _engine.Listener.AddBinding(new IPEndPoint(IPAddress.Any, port)); } #endif if (Socket.OSSupportsIPv6) { _engine.Listener.AddBinding(new IPEndPoint(IPAddress.IPv6Any, port)); } _engine.Start(); return; } IPAddress address = IPAddress.Parse(tscbIP.Text); if (address.AddressFamily == AddressFamily.InterNetwork) { #if !__MonoCS__ if (!Socket.OSSupportsIPv4) { MessageBox.Show(Listener.ErrorIPv4NotSupported); return; } #endif _engine.Listener.AddBinding(new IPEndPoint(address, port)); _engine.Start(); return; } if (!Socket.OSSupportsIPv6) { MessageBox.Show(Listener.ErrorIPv6NotSupported); return; } _engine.Listener.AddBinding(new IPEndPoint(address, port)); _engine.Start(); } private void StopListeners() { _engine.Stop(); } private void BtnTrapClick(object sender, EventArgs e) { IPAddress ip = IPAddress.Parse(txtIP.Text); Messenger.SendTrapV1( new IPEndPoint(ip, int.Parse(txtPort.Text, CultureInfo.InvariantCulture)), IPAddress.Loopback, // here should be IP of the current machine. new OctetString("public"), new ObjectIdentifier(new uint[] { 1, 3, 6 }), GenericCode.ColdStart, 0, 0, new List<Variable>()); } private void BtnTrap2Click(object sender, EventArgs e) { IPAddress ip = IPAddress.Parse(txtIP.Text); Messenger.SendTrapV2( 0, VersionCode.V2, new IPEndPoint(ip, int.Parse(txtPort.Text, CultureInfo.InvariantCulture)), new OctetString("public"), new ObjectIdentifier(new uint[] { 1, 3, 6 }), 0, new List<Variable>()); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions")] private void BtnInformV2Click(object sender, EventArgs e) { IPAddress ip = IPAddress.Parse(txtIP.Text); try { Messenger.SendInform( 0, VersionCode.V2, new IPEndPoint(ip, int.Parse(txtPort.Text, CultureInfo.InvariantCulture)), new OctetString("public"), new ObjectIdentifier(new uint[] { 1, 3, 6 }), 0, new List<Variable>(), 2000, null, null); } catch (SnmpException ex) { MessageBox.Show(ex.ToString()); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions")] private void BtnInformV3Click(object sender, EventArgs e) { IPAddress ip = IPAddress.Parse(txtIP.Text); try { IPEndPoint receiver = new IPEndPoint(ip, int.Parse(txtPort.Text, CultureInfo.InvariantCulture)); Discovery discovery = Messenger.GetNextDiscovery(SnmpType.InformRequestPdu); ReportMessage report = discovery.GetResponse(2000, receiver); Messenger.SendInform( 0, VersionCode.V3, receiver, new OctetString("neither"), new ObjectIdentifier(new uint[] { 1, 3, 6 }), 0, new List<Variable>(), 2000, DefaultPrivacyProvider.DefaultPair, report); } catch (SnmpException ex) { MessageBox.Show(ex.ToString()); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions")] private void ActEnabledExecute(object sender, EventArgs e) { if (_engine.Active) { StopListeners(); return; } if (SnmpMessageExtension.IsRunningOnMono && PlatformSupport.Platform != PlatformType.Windows && Mono.Unix.Native.Syscall.getuid() != 0 && int.Parse(txtPort.Text, CultureInfo.InvariantCulture) < 1024) { MessageBox.Show(@"On Linux this application must be run as root for port < 1024."); return; } try { StartListeners(); } catch (PortInUseException ex) { MessageBox.Show(@"Port is already in use: " + ex.Endpoint, @"Error"); } } private void MainFormLoad(object sender, EventArgs e) { Text = string.Format(CultureInfo.CurrentUICulture, "{0} (Version: {1})", Text, Assembly.GetExecutingAssembly().GetName().Version); } private void ActEnabledAfterExecute(object sender, EventArgs e) { actEnabled.Text = _engine.Listener.Active ? @"Stop Listening" : @"Start Listening"; actEnabled.Image = _engine.Listener.Active ? Properties.Resources.media_playback_stop : Properties.Resources.media_playback_start; tscbIP.Enabled = !_engine.Listener.Active; tstxtPort.Enabled = !_engine.Listener.Active; } } }
yonglehou/sharpsnmplib
snmpd/MainForm.cs
C#
mit
11,042
<?php /* * 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. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. */ namespace RoaveTest\DeveloperTools\Inspection; use Roave\DeveloperTools\Inspection\TimeInspection; /** * Tests for {@see \Roave\DeveloperTools\Inspection\TimeInspection} * * @covers \Roave\DeveloperTools\Inspection\TimeInspection */ class TimeInspectionTest extends AbstractInspectionTest { /** * {@inheritDoc} */ protected function getInspection() { return new TimeInspection(123, 456); } public function testGetData() { $inspection = $this->getInspection(); $data = $inspection->getInspectionData(); $this->assertEquals(123, $data[TimeInspection::PARAM_START]); $this->assertEquals(456, $data[TimeInspection::PARAM_END]); } }
Roave/RoaveDeveloperTools
test/RoaveTest/DeveloperTools/Inspection/TimeInspectionTest.php
PHP
mit
1,640
<?php defined('SYSPATH') or die('No direct script access.'); /** * Forum Topic model * * @package Forum * @author Antti Qvickström * @copyright (c) 2010-2013 Antti Qvickström * @license http://www.opensource.org/licenses/mit-license.php MIT license */ class Anqh_Model_Forum_Topic extends AutoModeler_ORM implements Permission_Interface { /** * Permission to post reply to topic */ const PERMISSION_POST = 'post'; /** Normal topic */ const STATUS_NORMAL = 0; /** Locked topic */ const STATUS_LOCKED = 1; /** Sunk topic, don't update last posted */ const STATUS_SINK = 2; /** Normal topic */ const STICKY_NORMAL = 0; /** Sticky topic */ const STICKY_STICKY = 1; protected $_table_name = 'forum_topics'; protected $_data = array( 'id' => null, 'forum_area_id' => null, 'bind_id' => null, 'type' => null, 'status' => self::STATUS_NORMAL, 'sticky' => self::STATUS_NORMAL, 'read_only' => null, 'votes' => null, 'points' => null, 'name' => null, 'old_name' => null, 'author_id' => null, 'author_name' => null, 'first_post_id' => null, 'last_post_id' => null, 'last_posted' => null, 'last_poster' => null, 'read_count' => 0, 'post_count' => 0, ); protected $_has_many = array( 'posts' ); protected $_rules = array( 'forum_area_id' => array('not_empty', 'digit'), 'status' => array('in_array' => array(':value', array(self::STATUS_LOCKED, self::STATUS_SINK, self::STATUS_NORMAL))), 'sticky' => array('in_array' => array(':value', array(self::STICKY_NORMAL, self::STICKY_STICKY))), 'name' => array('not_empty', 'max_length' => array(':value', 128)), 'first_post_id' => array('digit'), 'last_post_id' => array('digit'), ); /** @var Model_Forum_Post|Model_Forum_Private_Post */ public $unsaved_post; /** * Magic setter * * @param string $key * @param mixed $value */ public function __set($key, $value) { switch ($key) { // Legacy status <-> type case 'status': if ($value == self::STATUS_LOCKED && $this->type < 10) { $this->type += 10; } else if ($value !== self::STATUS_LOCKED && $this->type >= 10) { $this->type -= 10; } break; } parent::__set($key, $value); } /** * Get topic area * * @return Model_Forum_Area */ public function area() { return new Model_Forum_Area($this->forum_area_id); } /** * Bind model to topic. * * @param Model $bind_model * @param string $bind_name * @return boolean success */ public function bind(Model $bind_model, $bind_name = null) { // Get correct bind config $config = false; if (!$bind_name) { $model = Model::model_name($bind_model); foreach (Model_Forum_Area::get_binds(false) as $bind_name => $bind_config) { if ($bind_config['model'] == $model) { $config = $bind_config; break; } } } else { $config = Model_Forum_Area::get_binds($bind_name); } if ($config) { // Get area $area = Model_Forum_Area::factory(); $area = $area->load( DB::select_array($area->fields()) ->where('area_type', '=', Model_Forum_Area::TYPE_BIND) ->where('status', '=', Model_Forum_Area::STATUS_NORMAL) ->where('bind', '=', $bind_name) ); if ($area->loaded()) { $this->forum_area_id = $area->id; $this->bind_id = $bind_model->id(); return true; } } return false; } /** * Get bound model. * * @return Model */ public function bind_model() { if ($bind_config = $this->area()->bind_config()) { $model = AutoModeler::factory($bind_config['model'], $this->bind_id); return $model && $model->loaded() ? $model : null; } return null; } /** * Add a post to topic. * * @param string $content * @param Model_User|array $author * @return Model_Forum_Post|Model_Forum_Private_Post */ public function create_post($content, $author) { $this->unsaved_post = $post = $this instanceof Model_Forum_Private_Topic ? new Model_Forum_Private_Post() : new Model_Forum_Post(); $post->post = $content; if (is_array($author)) { $post->author_id = $author['id']; $post->author_name = $author['username']; } else if (is_object($author)) { $post->author_id = $author->id; $post->author_name = $author->username; } $post->author_ip = Request::$client_ip; $post->author_host = Request::host_name(); $post->created = time(); $post->forum_topic_id = $this->id; $post->forum_area_id = $this->forum_area_id; return $post; } /** * Find active topics. * * @param integer $limit * @return Model_Forum_Topic[] */ public function find_active($limit = 10) { return $this->load( DB::select_array($this->fields()) ->order_by('last_posted', 'DESC'), $limit ); } /** * Load topic by bound model * * @static * @param Model $bind_model Bound model * @param string $bind_name Bind config if multiple binds per model * @return Model_Forum_Topic */ public static function find_by_bind(Model $bind_model, $bind_name = null) { // Get correct bind config $config = false; if (!$bind_name) { $model = Model::model_name($bind_model); foreach (Model_Forum_Area::get_binds(false) as $bind_name => $bind_config) { if ($bind_config['model'] == $model) { $config = $bind_config; break; } } } else { $config = Model_Forum_Area::get_binds($bind_name); } if ($config) { // Get area $area = Model_Forum_Area::factory(); $area = $area->load( DB::select_array($area->fields()) ->where('area_type', '=', Model_Forum_Area::TYPE_BIND) ->where('status', '=', Model_Forum_Area::STATUS_NORMAL) ->where('bind', '=', $bind_name) ); if ($area->loaded()) { // Get topic $topic = Model_Forum_Topic::factory(); $topic = $topic->load( DB::select_array($topic->fields()) ->where('forum_area_id', '=', $area->id) ->where('bind_id', '=', $bind_model->id()) ); // If topic found, go there! if ($topic->loaded()) { return $topic; } } } return null; } /** * Find latest topics * * @param integer $limit * @return Model_Forum_Topic[] */ public function find_by_latest_post($limit = 10) { return $this->load( DB::select_array($this->fields()) ->order_by('last_posted', 'DESC'), $limit ); } /** * Find new topics * * @param integer $limit * @return Model_Forum_Topic[] */ public function find_new($limit = 10) { return $this->load( DB::select_array($this->fields()) ->order_by('id', 'DESC'), $limit ); } /** * Find news topics, i.e. latest topics from readonly areas. * * @param integer $limit * @return Model_Forum_Topic[] */ public function find_news($limit = 10) { $news_config = Kohana::$config->load('site.news'); if (!$news_config['forum_area_id'] || !$news_config['author_id']) { return null; } return $this->load( DB::select_array($this->fields()) ->where('forum_area_id', '=', $news_config['forum_area_id']) ->and_where('author_id', '=', $news_config['author_id']) ->order_by('id', 'DESC'), $limit ); } /** * Find a post's number in topic. * * @param integer $post_id * @return integer */ public function get_post_number($post_id) { return (int)DB::select(array(DB::expr('COUNT(id)'), 'posts')) ->from(Model_Forum_Post::factory()->get_table_name()) ->where('forum_topic_id', '=', $this->id) ->where('id', '<', (int)$post_id) ->execute($this->_db) ->get('posts'); } /** * Check permission * * @param string $permission * @param Model_User $user * @return boolean */ public function has_permission($permission, $user) { switch ($permission) { case self::PERMISSION_DELETE: return $user && $user->has_role(array('admin', 'forum moderator')); case self::PERMISSION_POST: return $user && ($this->status != self::STATUS_LOCKED); case self::PERMISSION_READ: return Permission::has($this->area(), Model_Forum_Area::PERMISSION_READ, $user); case self::PERMISSION_UPDATE: return $user && (($this->status != self::STATUS_LOCKED && $user->id == $this->author_id) || $user->has_role(array('admin', 'forum moderator'))); } return false; } /** * Get topic last post. * * @return Model_Forum_Post */ public function last_post() { return Model_Forum_Post::factory($this->last_post_id); } /** * Find topic posts by page. * * @param integer $offset * @param integer $limit * @return Model_Forum_Post[] */ public function posts($offset, $limit) { $post = Model_Forum_Post::factory(); $query = DB::select_array($post->fields()) ->where('forum_topic_id', '=', $this->id) ->order_by('created', 'ASC'); if ($offset || $limit) { return $post->load($query->offset($offset), $limit); } else { return $post->load($query, null); } } /** * Refresh topic foreign values * * @param boolean $save */ public function refresh($save = true) { if (!$this->loaded()) { return false; } // Get all posts for current topic $posts = $this->posts(); $this->post_count = count($posts); // First post $this->first_post_id = $posts[0]->id; // Last post $last_post = $posts[$this->post_count - 1]; $this->last_post_id = $last_post->id; $this->last_posted = $last_post->created; $this->last_poster = $last_post->author_name; if ($save) { $this->save(); } return true; } /** * Save topic and handle stats updated. * * @return boolean */ public function save_post() { if ($this->unsaved_post) { $this->unsaved_post->is_valid(); $area = $this->area(); if (!$this->id) { // New topic $this->save(); $this->unsaved_post->forum_topic_id = $this->id; $this->unsaved_post->save(); $this->created = $this->unsaved_post->created; $this->first_post_id = $this->unsaved_post->id; $area->topic_count++; } else { // Old topic $this->unsaved_post->save(); } // Topic stats $this->last_post_id = $this->unsaved_post->id; $this->last_poster = $this->unsaved_post->author_name; $this->last_posted = $this->unsaved_post->created; $this->post_count++; $this->save(); // Area stats $area->last_topic_id = $this->id; $area->post_count++; $area->save(); return true; } return false; } }
anqh/anqh
modules/forum/classes/anqh/model/forum/topic.php
PHP
mit
10,580
<?php /** * @author Tim Gunter <tim@vanillaforums.com> * @copyright 2016 Tim Gunter * @license MIT */ namespace Kaecyra\AppCommon\Log; /** * A logger that writes to the filesystem. * * @package app-common * @since 1.0 */ class FilesystemLogger extends BaseLogger { /** * File path * @var string */ private $file; /** * File pointer * @var Resource */ private $fr; /** * Config * @var array */ private $extra = []; public function __construct($workingDir, array $options = []) { $this->extra = $options; $this->extra['dir'] = $workingDir; $this->file = $this->extra['file']; if (substr($this->file, 0, 1) !== '/') { $this->file = rtrim($workingDir, '/') .'/'. $this->file; } $this->openLog(); } public function __destruct() { $this->closeLog(); } /** * Open log file for writing * * Also closes currently open log file if needed. * * @return void */ public function openLog() { if ($this->file) { $logDir = dirname($this->file); if (!is_dir($logDir) || !file_exists($logDir)) { @mkdir($logDir, 0755, true); } if (!file_exists($this->file)) { $touched = touch($this->file); if (!$touched) { throw new \Exception("Unable to open log file '{$this->file}', could not create"); } } if (!is_writable($this->file)) { throw new \Exception("Unable to open log file '{$this->file}', not writable"); } $this->fr = fopen($this->file, 'a'); } } /** * Close file pointer */ protected function closeLog() { fclose($this->fr); } /** * Rotate log file, closing and re-opening * * @throws \Exception */ public function rotate() { $this->closeLog(); $this->openLog(); } /** * Extract known columns and save the rest as attributes. * * @param mixed $level * @param string $message * @param array $context * @return null|void */ public function log($level, $message, array $context = []) { $realMessage = rtrim(static::interpolate($message, $context), "\n"); $levelC = strtoupper(substr($level,0,1)); $realMessage = sprintf("[ %1s ] %s\n", $levelC, $realMessage); fwrite($this->fr, $realMessage); } }
kaecyra/app-common
src/Log/FilesystemLogger.php
PHP
mit
2,570
package com.mygdx.game.entites.entitiycomponents; import com.badlogic.ashley.core.Component; import com.badlogic.gdx.graphics.g2d.Sprite; public class SpriteComponent implements Component { public Sprite sprite; public SpriteComponent(Sprite sprite){ this.sprite = sprite; } }
JoakimRW/ExamensArbeteTD
core/src/com/mygdx/game/entites/entitiycomponents/SpriteComponent.java
Java
mit
286
class Image < ActiveRecord::Base has_many :pages has_attachment :content_type => :image, :storage => :file_system, :path_prefix => 'public/system/images', :processor => 'Rmagick', :thumbnails => ((((thumbnails = RefinerySetting.find_or_set(:image_thumbnails, {})).is_a?(Hash) ? thumbnails : (RefinerySetting[:image_thumbnails] = {}))) rescue {}), :max_size => 5.megabytes acts_as_indexed :fields => [:title] def validate errors.add_to_base("You must choose a file to upload") unless self.filename unless self.filename.nil? [:size].each do |attr_name| enum = attachment_options[attr_name] errors.add_to_base("Files should be smaller than 50 MB in size") unless enum.nil? || enum.include?(send(attr_name)) end end end def title self.filename.gsub(/\.\w+$/, '').titleize end def self.per_page(dialog = false) size = (dialog ? 18 : 20) end def self.last_page(images, dialog=false) page = unless images.size <= self.per_page(dialog) (images.size / self.per_page(dialog).to_f).ceil else nil # this must be nil, it can't be 0 as there apparently isn't a 0th page. end end def self.thumbnails find(:all, :conditions => "parent_id not null") end def self.originals find_all_by_parent_id(nil) end end
aunderwo/sobc-refinery
vendor/plugins/images/app/models/image.rb
Ruby
mit
1,414
<?php /** * Created by PhpStorm. * User: brian * Date: 8/18/14 * Time: 11:19 AM */ namespace FzyAuth\Validator; use Zend\Validator\Identical; class PasswordIdentical extends Identical { /** * Error messages * @var array */ protected $messageTemplates = array( self::NOT_SAME => "The two passwords do not match", self::MISSING_TOKEN => 'No password was provided to match against', ); }
fousheezy/auth
module/FzyAuth/src/FzyAuth/Validator/PasswordIdentical.php
PHP
mit
441
class Sonnet < Formula desc "Spelling framework for Qt" homepage "https://github.com/KDE/sonnet" url "https://github.com/KDE/sonnet/archive/v5.28.0.tar.gz" sha256 "08a5cd2aabfb2513f09e67d9f7a2569aa642af4456a14902a22f19cb1b070db0" depends_on "cmake" => :build depends_on "extra-cmake-modules" => :build depends_on "qt5" depends_on "aspell" => :optional depends_on "encahnt" => :optional depends_on "hspell" => :optional depends_on "hunspell" => :optional depends_on "libvoikko" => :optional def install system "cmake", ".", *std_cmake_args system "make", "install" end test do # `test do` will create, run in and delete a temporary directory. # # This test will fail and we won't accept that! It's enough to just replace # "false" with the main program this formula installs, but it'd be nice if you # were more thorough. Run the test with `brew test sonnet`. Options passed # to `brew install` such as `--HEAD` also need to be provided to `brew test`. # # The installed folder is not in the path, so use the entire path to any # executables being tested: `system "#{bin}/program", "do", "something"`. system "false" end end
muellermartin/homebrew-kde
sonnet.rb
Ruby
mit
1,207
/* * The MIT License (MIT) * * Copyright (c) 2017 Comapi (trading name of Dynmark International Limited) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.comapi.internal.network; import android.support.annotation.Nullable; import com.comapi.internal.Parser; import com.google.gson.annotations.SerializedName; import java.util.List; import retrofit2.Response; /** * Comapi service response result. * * @author Marcin Swierczek * @since 1.0.0 */ public class ComapiResult<T> { private T result; private final String eTag; private final boolean isSuccessful; private final int code; private String errorBody; private final String message; /** * Constructor for testing purpose. * * @param result Call result body. * @param isSuccessful True if the call was successful. * @param eTag ETag for tracking remote data version. * @param code Code of the service response. * @param message Message in the response. * @param errorBody Error details. */ protected ComapiResult(T result, boolean isSuccessful, String eTag, int code, String message, String errorBody) { this.result = result; this.eTag = eTag; this.isSuccessful = isSuccessful; this.code = code; this.message = message; this.errorBody = errorBody; } /** * Recommended constructor. Translates Retrofit to Comapi service response. * * @param response Retrofit service response. */ ComapiResult(Response<T> response) { result = response.body(); eTag = response.headers().get("ETag"); isSuccessful = response.isSuccessful(); code = response.code(); message = response.message(); try { if (response.errorBody() != null) { errorBody = response.errorBody().string(); } } catch (Exception e) { e.printStackTrace(); } } /** * Copy constructor. * * @param result Comapi result to copy from. */ @SuppressWarnings("unchecked") ComapiResult(ComapiResult<T> result) { eTag = result.getETag(); isSuccessful = result.isSuccessful(); code = result.getCode(); message = result.getMessage(); errorBody = result.errorBody; this.result = result.getResult(); } /** * Copy constructor replacing result object with new one. * * @param result Comapi result with values to copy to a new instance. * @param resultReplacement Result object that should replace the one from old Comapi result. */ @SuppressWarnings("unchecked") public ComapiResult(ComapiResult result, T resultReplacement) { this.result = resultReplacement; eTag = result.getETag(); isSuccessful = result.isSuccessful(); code = result.getCode(); message = result.getMessage(); errorBody = result.errorBody; } /** * The deserialized response body of a {@linkplain #isSuccessful() successful} response. */ public T getResult() { return result; } /** * Returns true if {@link #getCode()} ()} is in the range [200..300). */ public boolean isSuccessful() { return isSuccessful; } /** * HTTP status code. */ public int getCode() { return code; } /** * ETag describing version of the data. */ public String getETag() { return eTag; } /** * HTTP status message or null if unknown. */ public String getMessage() { return message; } /** * Gets service call error details. * * @return Service call error details. */ public String getErrorBody() { return errorBody; } /** * Get API call validation failures details. * * @return List of validation failures returned from services. Can be null. */ public @Nullable List<ComapiValidationFailure> getValidationFailures() { if (errorBody != null && !errorBody.isEmpty()) { ComapiValidationFailures failures = null; try { failures = new Parser().parse(errorBody, ComapiValidationFailures.class); } catch (Exception e) { return null; } return failures.validationFailures; } return null; } class ComapiValidationFailures { @SerializedName("validationFailures") private List<ComapiValidationFailure> validationFailures; public List<ComapiValidationFailure> getValidationFailures() { return validationFailures; } } public class ComapiValidationFailure { @SerializedName("paramName") private String paramName; @SerializedName("message") private String message; /** * Name of the JSON parameter that failed the check on the server side. * * @return Name of the JSON parameter. */ public String getParamName() { return paramName; } /** * Cause of API call validation failure returned from the services. * * @return Cause of API call validation failure. */ public String getMessage() { return message; } } }
comapi/comapi-sdk-android
COMAPI/foundation/src/main/java/com/comapi/internal/network/ComapiResult.java
Java
mit
6,459
import xRay from 'x-ray' const xray = xRay() import { map, slice, compose } from 'ramda' import { writeFile } from 'fs' import routeNames from '../resources/routes.json' import { getNameFromMatchedObject } from '../js/core' import { convertStopData } from '../../server/controllers/helpers' export const addRouteName = (route) => { return { ...route, routeName: getNameFromMatchedObject(route.route)(routeNames) } } const convertDataList = map(compose(addRouteName, convertStopData)) // import mongoose from 'mongoose' // mongoose.Promise = require('bluebird') // import Stop from '../../server/models/stop' // import Route from '../../server/models/route' const routeID = process.argv[2] const direction = process.argv[3] console.log(`Getting StopID data for route: ${routeID}, heading in the ${direction} direction`) // async function saveEachResult (obj) { // const data = convertData(obj) // const routeObject = await Route.findOne({ 'ID': data.route }, 'name').exec() // Stop.findOneAndUpdate( // {'stop': data.stop}, // search by unique London bus stopsID // {...data, routeName: routeObject.name}, // spread data and then add routeName // {upsert: true} // create new doc if non exist // ).exec() // .then(function saveSuccess () { // console.log(`StopID ${data.stop} saved`) // }) // .catch(function errorHandler (error) { // console.log(error) // }) // } xray(`http://www.ltconline.ca/webwatch/MobileAda.aspx?r=${routeID}&d=${direction}`, 'a', [{ name: '@html', link: '@href' }] )(function handleXrayResult (err, result) { if (err) { throw err } // gets rid of the back link, Mobile Live Arrival Times and WebWatch Home result = slice(0, result.length - 3, result) /* MongoDb version */ // map(saveEachResult, result) /** * Write to File version */ const toFile = `app/resources/Stops/${routeID}-${direction}.json` writeFile( toFile, JSON.stringify(convertDataList(result), null, 4), () => { console.log(`Done with ${toFile}`) } ) // setTimeout(() => { // mongoose.connection.close() // }, 5000) }) // require('dotenv').load() // mongoose.connect(process.env.MONGO_URI) // .then(function connectHandler () { // console.log('Connected to mongoDB via mongoose: Local') // }) // .catch(function errorHandler (error) { // throw error // })
natac13/london-ontario-data
app/utils/scrapStops.js
JavaScript
mit
2,405
try: __version__ = __import__('pkg_resources').require('booleanOperations')[0].version except Exception: __version__ = 'unknown'
moyogo/booleanoperations
Lib/booleanOperations/version.py
Python
mit
137
'use strict'; const Rx = require('rxjs/Rx'); const counter = Rx.Observable.interval(100); const subscriptionA = counter.subscribe(i => console.log(`A ${i}`)); const subscriptionB = counter.subscribe(i => console.log(`B ${i}`)); setTimeout(() => { console.log(`Cancelling subscriptionB`); subscriptionB.unsubscribe(); }, 500);
miguelmota/rxjs-examples
examples/unsubscribe.js
JavaScript
mit
333
package com.isel.lteshakedownapp.testUnity; public class SignalStrTest extends AbstractTest { @Override public boolean isNative() { return false; } @Override public TestType getType() { return TestType.STATIONARY; } @Override public TestResult runTest() { TestResult ret = new TestResult(); ret.originalTest = this; return ret; } @Override public String getDescription() { return "Measures the mobile signal strenght"; } @Override public String getName() { return "Signal Strenght Test"; } }
isel-31612/NetworkShakedownApp
sources/LteShakeDownApp/src/com/isel/lteshakedownapp/testUnity/SignalStrTest.java
Java
mit
528
/* * RPC2Rest.cpp * * Created on: 14. 1. 2016 * Author: ondra */ #include "RPC2Rest.h" #include <lightspeed/base/text/textstream.tcc> #include <lightspeed/utils/json/jsonexception.h> #include "lightspeed/utils/json/jsonbuilder.h" #include "../httpserver/queryParser.h" #include "lightspeed/base/streams/fileio.h" #include "lightspeed/base/containers/map.tcc" #include "ijsonrpc.h" namespace jsonsrv { RPC2Rest::RPC2Rest(IJsonRpc &jsonrpc,IJsonRpcLogObject *logobject):jsonrpc(jsonrpc),logobject(logobject) { } void RPC2Rest::addMethod(ConstStrA methodName, ConstStrA argMapping) { addMethod(methodName,"GET",methodName,argMapping); } void RPC2Rest::addMethod(ConstStrA vpath, ConstStrA httpMethod, ConstStrA methodName, ConstStrA argMapping) { restMap.insert(Key(StringKey<StringA>(StringA(vpath)), StringKey<StringA>(StringA(httpMethod))) ,Mapping(methodName,argMapping)); } static JSON::Value createValue(JSON::PFactory &json, ConstStrA value, bool forceStr) { if (forceStr) return json->newValue(value); else return json->fromString(value); } static void storeToObject(JSON::PFactory &json, JSON::Value toObj, ConstStrA fldName, ConstStrA value, bool isArray, bool forceStr) { try { natural p = fldName.find('.'); if (p != naturalNull) { ConstStrA subName = fldName.offset(p+1); ConstStrA thisName = fldName.head(p); JSON::Value subobj = json->newClass(); toObj->add(thisName,subobj); storeToObject(json,subobj,subName,value,isArray,forceStr); } else { JSON::Value data; if (isArray) { data = json->array(); for(ConstStrA::SplitIterator iter = value.split(','); iter.hasItems();) { data->add(createValue(json, iter.getNext(),forceStr)); } } else { data = createValue(json, value, forceStr); } toObj->add(fldName,data); } } catch (Exception &e) { throw RPC2Rest::CannotParseMemberException(THISLOCATION, fldName) << e; } } static void sendError(BredyHttpSrv::IHttpRequest &r, const Exception &e) { r.status(400); r.header(BredyHttpSrv::IHttpRequest::fldContentType,"text/plain;charset=utf-8"); SeqFileOutput out(&r); SeqTextOutW txtout(out); txtout.blockWrite(e.getMessageWithReason(),true); } natural RPC2Rest::onRequest(BredyHttpSrv::IHttpRequest& request, ConstStrA vpath) { try { RestMap::Iterator iter = restMap.seek(Key( StringKey<StringA>(vpath), StringKey<StringA>(request.getMethod())) ); bool again; do { again = false; if (!iter.hasItems()) return 404; const Key &k = iter.peek().key; if (k.method != request.getMethod()) return 404; if (vpath.head(k.vpath.length()) != k.vpath) return 404; ConstStrA newpath = vpath.offset(k.vpath.length()); const Mapping &m = iter.peek().value; if (newpath.empty()) { if (!m.argMapping.empty()) return 404; newpath = "/"; } else if (newpath[0] != '/') { iter.skip(); again = true; } else { JSON::PFactory json = JSON::create(); JSON::Value args = json->array(); AutoArray<ConstStrA> pathArgs; BredyHttpSrv::QueryParser parser(newpath); newpath = parser.getPath().offset(1); for(ConstStrA::SplitIterator iter = newpath.split('/'); iter.hasItems();) pathArgs.add(iter.getNext()); JSON::Value queryObj = json->object(); while (parser.hasItems()) { const BredyHttpSrv::QueryField &fld = parser.getNext(); ConstStrA field = fld.name; bool isarray = false; bool forceString = false; if (field.tail(2) == ConstStrA("[]")) { isarray = true; field = field.crop(0,2); } if (field.tail(1) == ConstStrA("$")) { forceString = true; field = field.crop(0,1); } storeToObject(json, queryObj, field, fld.value, isarray, forceString); } JSON::Value bodyObject = json->newNullNode(); if (request.getMethod() == "POST" || request.getMethod() == "PUT") { SeqFileInput in(&request); bodyObject = json->fromStream(in); } JSON::Value context = json->newNullNode(); HeaderValue hv = request.getHeaderField("X-Context"); if (hv.defined) { StringA fullCtx = ConstStrA("{")+hv+ConstStrA("}"); context = json->fromString(fullCtx); } JSON::Value id = json->newValue(request.getIfc<BredyHttpSrv::IHttpPeerInfo>().getPeerRealAddr()); natural argpos = 0; for(StringA::Iterator iter = m.argMapping.getFwIter(); iter.hasItems();) { char mp = iter.getNext(); switch(mp) { case 'b':args->add(bodyObject);break; case 'q':args->add(queryObj);break; default: { if (argpos >= pathArgs.length()) { continue; } ConstStrA a = pathArgs[argpos]; switch(mp) { case 's': args->add(json->newValue(a));break; case 'n': args->add(json->fromString(a));break; default: return 404; } argpos++; break; } } } request.header(BredyHttpSrv::IHttpRequest::fldContentType,"application/json"); IJsonRpc::CallResult res = jsonrpc.callMethod(&request,m.methodName,args,context,id); if (logobject) logobject->logMethod(request, m.methodName, args, context, res.logOutput); if (!res.error->isNull()) { JSON::Value status = res.error->getPtr("status"); if (status != nil) { ConstStrA msg; JSON::Value stmsg = res.error->getPtr("statusMessage"); if (stmsg != nil) msg = stmsg->getStringUtf8(); request.status(status->getUInt(), msg); } SeqFileOutput out(&request); json->toStream(*res.error,out); } else { if (res.newContext != nil) { ConstStrA ctx = json->toString(*res.newContext); ctx = ctx.crop(1,1); request.header("X-Context", ctx); } if (res.result->isBool() && res.result->getBool()) { request.status(stCreated); request.sendHeaders(); } else { SeqFileOutput out(&request); json->toStream(*res.result,out); } } } } while (again); } catch (CannotParseMemberException &e) { sendError(request,e); } catch (JSON::ParseError_t &e) { sendError(request,e); } return 0; } bool RPC2Rest::CmpKeys::operator ()(const Key& a, const Key& b) const { StrCmpCI<char> cmp; CompareResult res = cmp(a.method, b.method); if (res == cmpResultEqual) { return cmp(a.vpath,b.vpath) != cmpResultLess; } else { return res != cmpResultLess; } } const char *RPC2Rest::cantParseMember= "Cannot parse member: %1"; } /* namespace jsonsrv */
ondra-novak/jsonrpcserver
jsonrpc/RPC2Rest.cpp
C++
mit
6,452
<?php namespace AppBundle\Document\Paciente; use Gedmo\Mapping\Annotation as Gedmo; use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; /** * Documento para mapear las citas * * @ODM\EmbeddedDocument */ class PacienteCitas { /** * @ODM\Id */ protected $id; /** * @ODM\String */ protected $consultorio; /** * @ODM\String */ protected $medico; /** * @ODM\Date */ protected $fecha; /** * Set consultorio * * @param string $consultorio * @return self */ public function setConsultorio($consultorio) { $this->consultorio = $consultorio; return $this; } /** * Get consultorio * * @return string $consultorio */ public function getConsultorio() { return $this->consultorio; } /** * Set medico * * @param string $medico * @return self */ public function setMedico($medico) { $this->medico = $medico; return $this; } /** * Get medico * * @return string $medico */ public function getMedico() { return $this->medico; } /** * Set fecha * * @param date $fecha * @return self */ public function setFecha($fecha) { $this->fecha = $fecha; return $this; } /** * Get fecha * * @return date $fecha */ public function getFecha() { return $this->fecha; } /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id) { $this->id = $id; } }
Adriwr/Clinica
src/AppBundle/Document/Paciente/PacienteCitas.php
PHP
mit
1,744
import numpy import chainer from chainer.backends import cuda from chainer import function_node from chainer.utils import type_check def _as_mat(x): if x.ndim == 2: return x return x.reshape(len(x), -1) def _ij_ik_il_to_jkl(a, b, c): ab = chainer.functions.matmul(a[:, :, None], b[:, None, :]) # ijk return chainer.functions.matmul(_as_mat(ab).T, c).reshape( a.shape[1], b.shape[1], c.shape[1]) def _ij_ik_jkl_to_il(a, b, c): ab = chainer.functions.matmul(a[:, :, None], b[:, None, :]) # ijk c = c.reshape(-1, c.shape[-1]) # [jk]l return chainer.functions.matmul(_as_mat(ab), c) def _ij_il_jkl_to_ik(a, b, c): return _ij_ik_jkl_to_il(a, b, chainer.functions.swapaxes(c, 1, 2)) def _ik_il_jkl_to_ij(a, b, c): return _ij_ik_jkl_to_il(a, b, chainer.functions.rollaxis(c, 0, c.ndim)) class BilinearFunction(function_node.FunctionNode): def check_type_forward(self, in_types): n_in = type_check.eval(in_types.size()) if n_in != 3 and n_in != 6: raise type_check.InvalidType( '{0} or {1}'.format( in_types.size() == 3, in_types.size() == 6), '{0} == {1}'.format(in_types.size(), n_in)) e1_type, e2_type, W_type = in_types[:3] type_check_prod = type_check.make_variable(numpy.prod, 'prod') type_check.expect( e1_type.dtype == numpy.float32, e1_type.ndim >= 2, e2_type.dtype == numpy.float32, e2_type.ndim >= 2, e1_type.shape[0] == e2_type.shape[0], W_type.dtype == numpy.float32, W_type.ndim == 3, type_check_prod(e1_type.shape[1:]) == W_type.shape[0], type_check_prod(e2_type.shape[1:]) == W_type.shape[1], ) if n_in == 6: out_size = W_type.shape[2] V1_type, V2_type, b_type = in_types[3:] type_check.expect( V1_type.dtype == numpy.float32, V1_type.ndim == 2, V1_type.shape[0] == W_type.shape[0], V1_type.shape[1] == out_size, V2_type.dtype == numpy.float32, V2_type.ndim == 2, V2_type.shape[0] == W_type.shape[1], V2_type.shape[1] == out_size, b_type.dtype == numpy.float32, b_type.ndim == 1, b_type.shape[0] == out_size, ) def forward(self, inputs): self.retain_inputs(tuple(range(len(inputs)))) e1 = _as_mat(inputs[0]) e2 = _as_mat(inputs[1]) W = inputs[2] xp = cuda.get_array_module(*inputs) # optimize: y = xp.einsum('ij,ik,jkl->il', e1, e2, W) y = xp.tensordot(xp.einsum('ij,ik->ijk', e1, e2), W, axes=2) if len(inputs) == 6: V1, V2, b = inputs[3:] y += e1.dot(V1) y += e2.dot(V2) y += b return y, def backward(self, indexes, grad_outputs): inputs = self.get_retained_inputs() e1, e2, W = inputs[:3] gy, = grad_outputs if len(inputs) == 6: V1, V2 = inputs[3], inputs[4] return BilinearFunctionGrad().apply((e1, e2, W, V1, V2, gy)) return BilinearFunctionGrad().apply((e1, e2, W, gy)) class BilinearFunctionGrad(function_node.FunctionNode): def forward(self, inputs): self.retain_inputs(tuple(range(len(inputs)))) e1 = _as_mat(inputs[0]) e2 = _as_mat(inputs[1]) W, gy = inputs[2], inputs[-1] xp = cuda.get_array_module(*inputs) # optimize: gW = xp.einsum('ij,ik,il->jkl', e1, e2, gy) gW = xp.einsum('ij,ik->jki', e1, e2).dot(gy) gy_W = xp.tensordot(gy, W, axes=(1, 2)) # 'il,jkl->ijk' # optimize: ge1 = xp.einsum('ik,jkl,il->ij', e2, W, gy) ge1 = xp.einsum('ik,ijk->ij', e2, gy_W) # optimize: ge2 = xp.einsum('ij,jkl,il->ik', e1, W, gy) ge2 = xp.einsum('ij,ijk->ik', e1, gy_W) ret = ge1.reshape(inputs[0].shape), ge2.reshape(inputs[1].shape), gW if len(inputs) == 6: V1, V2 = inputs[3], inputs[4] gV1 = e1.T.dot(gy) gV2 = e2.T.dot(gy) gb = gy.sum(0) ge1 += gy.dot(V1.T) ge2 += gy.dot(V2.T) ret += gV1, gV2, gb return ret def backward(self, indexes, grad_outputs): inputs = self.get_retained_inputs() e1 = _as_mat(inputs[0]) e2 = _as_mat(inputs[1]) W, gy = inputs[2], inputs[-1] gge1 = _as_mat(grad_outputs[0]) gge2 = _as_mat(grad_outputs[1]) ggW = grad_outputs[2] dge1_de2 = _ij_il_jkl_to_ik(gge1, gy, W) dge1_dW = _ij_ik_il_to_jkl(gge1, e2, gy) dge1_dgy = _ij_ik_jkl_to_il(gge1, e2, W) dge2_de1 = _ik_il_jkl_to_ij(gge2, gy, W) dge2_dW = _ij_ik_il_to_jkl(e1, gge2, gy) dge2_dgy = _ij_ik_jkl_to_il(e1, gge2, W) dgW_de1 = _ik_il_jkl_to_ij(e2, gy, ggW) dgW_de2 = _ij_il_jkl_to_ik(e1, gy, ggW) dgW_dgy = _ij_ik_jkl_to_il(e1, e2, ggW) ge1 = dgW_de1 + dge2_de1 ge2 = dgW_de2 + dge1_de2 gW = dge1_dW + dge2_dW ggy = dgW_dgy + dge1_dgy + dge2_dgy if len(inputs) == 6: V1, V2 = inputs[3], inputs[4] ggV1, ggV2, ggb = grad_outputs[3:] gV1 = chainer.functions.matmul(gge1, gy, transa=True) gV2 = chainer.functions.matmul(gge2, gy, transa=True) ge1 += chainer.functions.matmul(gy, ggV1, transb=True) ge2 += chainer.functions.matmul(gy, ggV2, transb=True) ggy += chainer.functions.matmul(gge1, V1) ggy += chainer.functions.matmul(gge2, V2) ggy += chainer.functions.matmul(e1, ggV1) ggy += chainer.functions.matmul(e2, ggV2) ggy += chainer.functions.broadcast_to(ggb, ggy.shape) ge1 = ge1.reshape(inputs[0].shape) ge2 = ge2.reshape(inputs[1].shape) if len(inputs) == 6: return ge1, ge2, gW, gV1, gV2, ggy return ge1, ge2, gW, ggy def bilinear(e1, e2, W, V1=None, V2=None, b=None): """Applies a bilinear function based on given parameters. This is a building block of Neural Tensor Network (see the reference paper below). It takes two input variables and one or four parameters, and outputs one variable. To be precise, denote six input arrays mathematically by :math:`e^1\\in \\mathbb{R}^{I\\cdot J}`, :math:`e^2\\in \\mathbb{R}^{I\\cdot K}`, :math:`W\\in \\mathbb{R}^{J \\cdot K \\cdot L}`, :math:`V^1\\in \\mathbb{R}^{J \\cdot L}`, :math:`V^2\\in \\mathbb{R}^{K \\cdot L}`, and :math:`b\\in \\mathbb{R}^{L}`, where :math:`I` is mini-batch size. In this document, we call :math:`V^1`, :math:`V^2`, and :math:`b` linear parameters. The output of forward propagation is calculated as .. math:: y_{il} = \\sum_{jk} e^1_{ij} e^2_{ik} W_{jkl} + \\ \\sum_{j} e^1_{ij} V^1_{jl} + \\sum_{k} e^2_{ik} V^2_{kl} + b_{l}. Note that V1, V2, b are optional. If these are not given, then this function omits the last three terms in the above equation. .. note:: This function accepts an input variable ``e1`` or ``e2`` of a non-matrix array. In this case, the leading dimension is treated as the batch dimension, and the other dimensions are reduced to one dimension. .. note:: In the original paper, :math:`J` and :math:`K` must be equal and the author denotes :math:`[V^1 V^2]` (concatenation of matrices) by :math:`V`. Args: e1 (~chainer.Variable): Left input variable. e2 (~chainer.Variable): Right input variable. W (~chainer.Variable): Quadratic weight variable. V1 (~chainer.Variable): Left coefficient variable. V2 (~chainer.Variable): Right coefficient variable. b (~chainer.Variable): Bias variable. Returns: ~chainer.Variable: Output variable. See: `Reasoning With Neural Tensor Networks for Knowledge Base Completion <https://papers.nips.cc/paper/5028-reasoning-with-neural-tensor- networks-for-knowledge-base-completion>`_ [Socher+, NIPS2013]. """ flags = [V1 is None, V2 is None, b is None] if any(flags): if not all(flags): raise ValueError('All coefficients and bias for bilinear() must ' 'be None, if at least one of them is None.') return BilinearFunction().apply((e1, e2, W))[0] return BilinearFunction().apply((e1, e2, W, V1, V2, b))[0]
rezoo/chainer
chainer/functions/connection/bilinear.py
Python
mit
8,648
package org.openkoala.gqc.infra.util; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 数据库工具类 * @author zyb * @since 2013-7-9 上午9:41:00 */ public class DatabaseUtils { /** * 获取数据库下的所有表 * @param conn * @return */ public static List<String> getTables(Connection conn) { ResultSet rs = null; PreparedStatement pstmt = null; List<String> result = new ArrayList<String>(); try { if (getDatabaseMetaData(conn).getDatabaseProductName().equalsIgnoreCase("oracle")) { pstmt = conn.prepareStatement("select table_name from user_tables"); rs = pstmt.executeQuery(); while (rs.next()) { result.add(rs.getString("TABLE_NAME")); } return result; } rs = getDatabaseMetaData(conn).getTables(null, null, null, new String[] { "TABLE" }); while (rs.next()) { result.add(rs.getString("TABLE_NAME")); } } catch (Exception e) { throw new RuntimeException("查询表异常"); } finally { try { if(rs != null){ rs.close(); } if (pstmt != null) { pstmt.close(); } if(conn != null){ conn.close(); } } catch (SQLException e) { throw new RuntimeException("查询表异常"); } } return result; } /** * 获取表下的所有列 * @param conn * @param tableName * @return */ public static Map<String, Integer> getColumns(Connection conn, String tableName) { ResultSet rs = null; Map<String, Integer> result = new HashMap<String, Integer>(); try { rs = getDatabaseMetaData(conn).getColumns(null, null, tableName, null); while (rs.next()) { result.put(rs.getString("COLUMN_NAME"), rs.getInt("DATA_TYPE")); } } catch (SQLException e) { } finally { try { if(rs != null){ rs.close(); } } catch (SQLException e) { } } return result; } /** * 获取数据库类型 * @param conn * @return */ public static String getDatabaseType(Connection conn) { try { return getDatabaseMetaData(conn).getDatabaseProductName(); } catch (SQLException e) { } return null; } /** * 获取数据库元数据 * @param conn * @return * @throws SQLException */ private static DatabaseMetaData getDatabaseMetaData(Connection conn) throws SQLException { return conn.getMetaData(); } }
guokaijava/YGCMS
ygcms-infra/src/main/java/org/openkoala/gqc/infra/util/DatabaseUtils.java
Java
mit
2,621
Rails.application.routes.draw do # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" root 'ship_labels#index' resources :ship_labels # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
ganeshkbalaji/dot-bo-challenge
config/routes.rb
Ruby
mit
1,629
default[:logstash][:version] = "1.4"
foxycoder/chef-logstash
attributes/default.rb
Ruby
mit
37
<?php namespace Midnight\Crawler\Plugin\TestData; class RakuenTestData extends AbstractTestData { /** * @var string **/ protected $rss_name = 'rakuen.xml'; /** * @var array **/ protected $html_paths = array( 'rakuen/880.html', 'rakuen/error.html', 'rakuen/error2.html' ); }
app2641/AdultMidnight
src/Midnight/Crawler/Plugin/TestData/RakuenTestData.php
PHP
mit
341
var NexSportsFrScraper, Xray = require('x-ray'), Datastore = require('nedb'), bunyan = require('bunyan'); var NexSportsFrScraper = (function(){ var X = Xray(); X.delay(500, 1000); var log = bunyan.createLogger({name: 'scraperlogger'}); var BASE_URL = "http://www.sports.fr"; var CLUBS_LIGUE_1_URI = "/football/ligue-1/clubs.html"; var CLUBS_LIGUE_1_URL = BASE_URL+CLUBS_LIGUE_1_URI; var db = {}; db.scrapeLog = new Datastore({ filename: __dirname+'/scrape.db' }); db.league = new Datastore({ filename: __dirname+'/league.db' }); db.scrapeLog.loadDatabase(); db.league.loadDatabase(); var SCRAPE_TYPE = { LEAGUE: "LEAGUE", TEAM: "TEAM", PLAYER: "PLAYER", STATS: "STATS" }; return { db: db, registerScrape: function(type, options){ log.info(options, 'Registring a scrape of type '+ type); options = options || {}; db.scrapeLog.insert({ type: type, time: (new Date()).toJSON(), options: options }, function(err, newDoc){ if(!err){ }else{ log.error(err, 'Error while registring scrape'); } }); }, getAndSaveTeams: function(next, errorCallback){ log.info('Starting Team retrieval'); var that = this; this.getListTeamsLigue1(function(teams){ if (!!teams) log.info('Retrieved '+teams.length+' teams'); if (!teams) log.info('No teams retrieved'); teams.forEach(function(team, index, teams){ db.league.findOne({name: team.name}, function(err, foundTeam){ var i = index; var length = teams.length; if(!err && !!foundTeam){ db.league.update({name: foundTeam.name}, {$set: foundTeam}, {}, function(err, numReplaced){ log.info({team: foundTeam}, 'Team updated'); that.registerScrape(SCRAPE_TYPE.LEAGUE); if (next && (i == (length - 1))) next(); }); }else if(!err){ db.league.insert(team, function(err, newTeam){ log.info({team: newTeam}, 'Team created'); that.registerScrape(SCRAPE_TYPE.LEAGUE); if (next && (i == (length - 1))) next(); }); }else{ log.error(err, 'Error while saving team'); if(errorCallback) errorCallback(err); if (next && (i == (length - 1))) next(); } }); }); }, function(err){ log.error('Eror while retrieving teams'); if(errorCallback) errorCallback(err); }); }, getAndSaveTeamPlayers: function(teamUrl, next, errorCallback){ log.info('Retrieving team players'); var that = this; this.getListPlayersForTeam(teamUrl, function(players){ if (!!players) log.info('Retrieved '+players.length+' players'); if (!players) log.info('No players retrieved'); var iterFunc = function(i, length){ if (i<length){ var url = players[i].url; that.getPlayerProfile(url, function(player){ player.teamUrl = teamUrl; db.league.findOne({url: url}, function(err, playerFound){ if (!err && !!playerFound){ db.league.update({url: playerFound.url}, {$set: player}, {}, function(err, numReplaced){ log.info({playerFound: playerFound}, 'Player updated'); that.registerScrape(SCRAPE_TYPE.PLAYER, {url: playerFound.url}); iterFunc(i+1, length); }); }else if(!err){ db.league.insert(player, function(err, newPlayer){ log.info({newPlayer: newPlayer}, 'Player created'); that.registerScrape(SCRAPE_TYPE.PLAYER, {url: newPlayer.url}); iterFunc(i+1, length); }); }else{ log.error(err, 'Error while saving player'); if (errorCallback) errorCallback(err); iterFunc(i+1, length); } }); }, function(err){ log.error(err, 'Error while retrieving player'); if (errorCallback) errorCallback(err); iterFunc(i+1, length); }); }else{ that.registerScrape(SCRAPE_TYPE.TEAM, {url: teamUrl}); if (next) next(); } }; iterFunc(0, players.length); }, function(err){ log.error(err, 'Error while retrieving player list for team'); if (errorCallback) errorCallback(err); }); }, getAndSavePlayerStats: function(statsUrl, next, errorCallback){ log.info('Starting Stats retrieval'); var that = this; that.getPlayerStats(statsUrl, function(stats){ if (!!stats) log.info('Retrieved '+stats.length+' lines of statistics'); if (!stats) log.info('No statistics retrieved'); var iterFunc = function(i, length, stats){ var stat = stats[i]; if (i<length){ db.league.findOne({url: stat.url, fixture: stat.fixture}, function(err, statsFound){ if (!err && !!statsFound){ log.info({fixture: statsFound}, 'Line of Statistics already created'); iterFunc(i+1, length, stats); }else if(!err){ db.league.insert(stat, function(err, newStat){ log.info({newStat: newStat}, 'Line of statistics created'); that.registerScrape(SCRAPE_TYPE.STATS, {url: newStat.url}); iterFunc(i+1, length, stats); }); }else{ log.error(err, 'Error while saving statistics'); if (errorCallback) errorCallback(err); iterFunc(i+1, length, stats); } }); }else{ if (next) next(); } }; iterFunc(0, stats.length, stats); },function(err){ log.error( err, 'Error while retrieving player stats'); if (errorCallback) errorCallback(err); }); }, // HTML -> JSON getListPlayersForTeam: function(teamUrl, successCallback, errorCallback){ X(teamUrl, "#col2 > div.nwTable > table > tbody > tr td:nth-child(2) a", [{ url: "@href" }])(function(err, results){ if(!err){ if(successCallback) successCallback(results); }else{ if(errorCallback) errorCallback(err); } }); }, getPlayerProfile: function(playerUrl, successCallback, errorCallback){ X(playerUrl, "#main-content > div.nwTable.nwFiche.nwJoueur", { image: "img@src", lastName: "div.nwIdentity ul > li:nth-child(1) > span > b", firstName: "div.nwIdentity ul > li:nth-child(2) > span > b", birthday: "div.nwIdentity ul > li:nth-child(3) > span > b", birthplace: "div.nwIdentity ul > li:nth-child(5) > span > b", nationality: "div.nwIdentity ul > li:nth-child(6) > span > b", height: "div.nwIdentity ul > li:nth-child(7) > span > b", weight: "div.nwIdentity ul > li:nth-child(8) > span > b", position: "div.nwIdentity ul > li:nth-child(9) > span > b", number: "div.nwIdentity ul > li:nth-child(10) > span > b", statsUrl: "div.nwStat > table > tfoot > tr > td > a@href", type: SCRAPE_TYPE.PLAYER })(function(err, player){ if(!err){ player.url = playerUrl; player.nationality = player.nationality.match(/\S+/g)[0]; player.height = parseInt(player.height.match(/\d+/g).join("")); player.weight = parseInt(player.weight.match(/\d+/g).join("")); player.number = parseInt(player.number); player.type= SCRAPE_TYPE.PLAYER; if(successCallback) successCallback(player); }else{ if(errorCallback) errorCallback(err); } }); }, getPlayerStats: function(playerStatsUrl, successCallback, errorCallback){ X(playerStatsUrl, "#main-content > div.nwTable.nwDetailSaison > table:nth-child(3) > tbody tr", [{ date: "td:nth-child(1)", homeTeam: "td:nth-child(2) img@alt", awayTeam: "td:nth-child(4) img@alt", fixture: "td:nth-child(5) a", homeTeamScore: "td:nth-child(6) a", awayTeamScore: "td:nth-child(6) a", status: "td:nth-child(7)", timePlayed: "td:nth-child(8)", review:"td:nth-child(9)", goals: "td:nth-child(10)", yellowCards: "td:nth-child(11)", redCards: "td:nth-child(12)", type: SCRAPE_TYPE.STATS }])(function(err, playerStats){ if(!err){ var cleanTimeFromScore = function(inputStr){ if(inputStr == "-") return 0; inputStr = inputStr.split('(')[0]; inputStr = parseInt(inputStr); return inputStr; }; [].forEach.call(playerStats, function(element, index, array){ var score = element.homeTeamScore; element.statsUrl = playerStatsUrl; element.fixture = parseInt(element.fixture.match(/\d+/g)[0]); element.homeTeamScore = parseInt(score.match(/\S+/g)[0].split("-")[0]); element.awayTeamScore = parseInt(score.match(/\S+/g)[0].split("-")[1]); element.timePlayed = parseInt(element.timePlayed); element.review = parseFloat(element.review); if(isNaN(element.review)) element.review = -1; element.yellowCards = cleanTimeFromScore(element.yellowCards); element.redCards = cleanTimeFromScore(element.redCards); element.goals = cleanTimeFromScore(element.goals); element.type= SCRAPE_TYPE.STATS; }); if(successCallback) successCallback(playerStats); }else{ if(errorCallback) errorCallback(err); } }); }, getListTeamsLigue1: function(successCallback, errorCallback){ X(CLUBS_LIGUE_1_URL, '#main-content > div.nwTable.nwClub > ul li', [{ name: 'div > h2 > a', image: 'div > span > img@src', url: 'div > h2 > a@href' }])(function(err, result){ if(!err){ [].forEach.call(result, function(element, index, array){ element.name = element.name.match(/\S+/g)[0]; element.type= SCRAPE_TYPE.TEAM; }); if(successCallback) successCallback(result); }else{ if(errorCallback) errorCallback(err); } }); } }; })(); module.exports = NexSportsFrScraper;
Boussadia/NexFootballStatistics
NexSportsFrScraper.js
JavaScript
mit
9,732
/** * Manages state for the `browse` page */ import R from 'ramda'; import { SORT, SET_SORT, ADD_COMPOSITIONS } from 'src/actions/browse'; const initialState = { loadedCompositions: [], totalCompositions: 100, selectedSort: 'NEWEST', }; export default (state=initialState, action={}) => { switch(action.type) { case SET_SORT: { if(action.sort !== state.selectedSort) { return {...state, loadedCompositions: [], selectedSort: action.sort, }; } else { return state; } } case ADD_COMPOSITIONS: { return {...state, loadedCompositions: R.union(state.loadedCompositions, action.compositions)} } default: { return state; } } };
Ameobea/noise-asmjs
src/reducers/browseReducer.js
JavaScript
mit
707
<!doctype html> <html class="no-js" lang=""> <head> <title>Zabuun - Learn Egyptian Arabic for English speakers</title> <meta name="description" content=""> <?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?> </head> <body> <?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?> <?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?> <div class="content"> <?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?> <div class="main"> <div class="location"> <p class="breadcrumbs">Essays > Summer Job</p> <p class="expandcollapse"> <a href="">Expand All</a> | <a href="">Collapse All</a> </p> </div> <!-- begin essay --> <h1>Summer Job</h1> <p>When they got to the Burger Hut, David put on his sweater and his hat. He sat down in the far corner of the restaurant, and tried to hide himself from his co-workers and his boss. When his friends got their food, they went to sit down with David. Michael came out and saw David. He went up to him and said, "You just can't get enough of this place, huh, David?" Michael chuckled and then left. David's friends took a bite out of their burgers, and looked at David. "You work here?" One of David's friend asked. His another friend looked at him and said, "Can you get me a job?" David smiled and nervously said, "I'll try."</p> <!-- end essay --> </div> </div> <?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?> <?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?> </body> </html>
javanigus/zabuun
essay/2328-summer-job.php
PHP
mit
1,554
/** * Created by santhoshkumar on 17/09/15. * * Find the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum. Kadane’s Algorithm: Initialize: max_so_far = 0 max_ending_here = 0 Loop for each element of the array (a) max_ending_here = max_ending_here + a[i] (b) if(max_ending_here < 0) max_ending_here = 0 (c) if(max_so_far < max_ending_here) max_so_far = max_ending_here return max_so_far Explanation: Simple idea of the Kadane's algorithm is to look for all positive contiguous segments of the array (max_ending_here is used for this). And keep track of maximum sum contiguous segment among all positive segments (max_so_far is used for this). Each time we get a positive sum compare it with max_so_far and update max_so_far if it is greater than max_so_far Lets take the example: {-2, -3, 4, -1, -2, 1, 5, -3} max_so_far = max_ending_here = 0 for i=0, a[0] = -2 max_ending_here = max_ending_here + (-2) Set max_ending_here = 0 because max_ending_here < 0 for i=1, a[1] = -3 max_ending_here = max_ending_here + (-3) Set max_ending_here = 0 because max_ending_here < 0 for i=2, a[2] = 4 max_ending_here = max_ending_here + (4) max_ending_here = 4 max_so_far is updated to 4 because max_ending_here greater than max_so_far which was 0 till now for i=3, a[3] = -1 max_ending_here = max_ending_here + (-1) max_ending_here = 3 for i=4, a[4] = -2 max_ending_here = max_ending_here + (-2) max_ending_here = 1 for i=5, a[5] = 1 max_ending_here = max_ending_here + (1) max_ending_here = 2 for i=6, a[6] = 5 max_ending_here = max_ending_here + (5) max_ending_here = 7 max_so_far is updated to 7 because max_ending_here is greater than max_so_far for i=7, a[7] = -3 max_ending_here = max_ending_here + (-3) max_ending_here = 4 max_so_far = 7 * */ function maxSumSubArray(arr){ var maxEndingHere = 0; var maxSoFar = 0; for(var i=1; i< arr.length; i++){ maxEndingHere = maxEndingHere+arr[i]; if(maxEndingHere < 0){ maxEndingHere = 0; }else if(maxEndingHere > maxSoFar){ maxSoFar = maxEndingHere; } } return maxSoFar; } var a = [-2, -3, 4, -1, -2, 1, 5, -3]; console.log("Array: "+ a); console.log("Max sum subarray: "+maxSumSubArray(a));
skcodeworks/dp-algo-in-js
js/largestsumcontiguoussubarray.js
JavaScript
mit
2,369
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.hatapp.comandas.entity; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author ivan */ @Entity @Table(name = "atributosclientes") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Atributosclientes.findAll", query = "SELECT a FROM Atributosclientes a"), @NamedQuery(name = "Atributosclientes.findById", query = "SELECT a FROM Atributosclientes a WHERE a.id = :id"), @NamedQuery(name = "Atributosclientes.findByNombre", query = "SELECT a FROM Atributosclientes a WHERE a.nombre = :nombre")}) public class Atributosclientes implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "id") private Integer id; @Basic(optional = false) @NotNull @Size(min = 1, max = 45) @Column(name = "nombre") private String nombre; @JoinTable(name = "clientes_has_atributos", joinColumns = { @JoinColumn(name = "AtributosClientes_id", referencedColumnName = "id")}, inverseJoinColumns = { @JoinColumn(name = "Clientes_id", referencedColumnName = "id")}) @ManyToMany private List<Clientes> clientesList; public Atributosclientes() { } public Atributosclientes(Integer id) { this.id = id; } public Atributosclientes(Integer id, String nombre) { this.id = id; this.nombre = nombre; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } @XmlTransient public List<Clientes> getClientesList() { return clientesList; } public void setClientesList(List<Clientes> clientesList) { this.clientesList = clientesList; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Atributosclientes)) { return false; } Atributosclientes other = (Atributosclientes) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "com.hatapp.comandas.entity.Atributosclientes[ id=" + id + " ]"; } }
ivanbanos/SistemaComandasYInventarioRestaurantes
SistemaComandas/SistemaComandas-api/src/main/java/com/hatapp/comandas/entity/Atributosclientes.java
Java
mit
3,447
<?php namespace Nekland\Bundle\FeedBundle\Item; interface ItemInterface { /* * Return the title of your rss, something like "My blog rss" * @return string */ public function getFeedTitle(); /* * Return the description of your rss, something like "This is the rss of my blog about foo and bar" * @return string */ public function getFeedDescription(); /* * Return the route of your item * @return array with * [0] * => * ['route'] * => * [0] => 'route_name' * [1] => array of params of the route * => * ['other parameter'] => 'content' (you can use for atom) * [1] * => * ['url'] => 'http://mywebsite.com' * => * ['other parameter'] => 'content' (you can use for atom) */ public function getFeedRoutes(); /** * @return unique identifier (for editing) */ public function getFeedId(); /** * @abstract * @return \DateTime */ public function getFeedDate(); }
Nekland/FeedBundle
Item/ItemInterface.php
PHP
mit
1,114
require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require require "spik" module Dummy class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' end end
gazay/spik
test/dummy/config/application.rb
Ruby
mit
1,786
(function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([root], factory); } else { // Browser globals root.slugify = factory(root); } }(this, function (window) { var from = 'àáäãâèéëêìíïîòóöôõùúüûñç·/_,:;', to = 'aaaaaeeeeiiiiooooouuuunc------'; return function slugify(str){ var i = 0, len = from.length; str = str.toLowerCase(); for( ; i < len; i++ ){ str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i)); } return str.replace(/^\s+|\s+$/g, '') //trim .replace(/[^-a-zA-Z0-9\s]+/ig, '') .replace(/\s/gi, "-"); }; }));
LeandroLovisolo/MyDataStructures
website/bower_components/slugify/slugify.js
JavaScript
mit
795
<?php /* * Copyright 2015 Sven Sanzenbacher * * This file is part of the naucon package. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Naucon\File; /** * File Writer Interface * * @abstract * @package File * @author Sven Sanzenbacher */ interface FileWriterInterface { /** * write string to file * * @param string $string file content * @return FileWriterInterface */ public function write($string); /** * add string to file * * @param string $string file content * @return FileWriterInterface */ public function writeLine($string); /** * clear file */ public function clear(); /** * truncates file to a given length (in bytes) * * @param int $bytes length in bytes */ public function truncates($bytes); }
naucon/File
src/FileWriterInterface.php
PHP
mit
994
package com.wj.caidengmi2; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; public class SqlHelper { public static final String DB_NAME = "data/data/com.game.zhongqiuguess/databases/dengmi.db"; public void Insert(Context context,String table, ContentValues values){ SQLiteDatabase db=SQLiteDatabase.openOrCreateDatabase(DB_NAME, null); try{ db.insert(table, null, values); }catch(Exception e){ e.getStackTrace(); } db.close(); } public void CreateTable(Context context,String table){ SQLiteDatabase db=SQLiteDatabase.openOrCreateDatabase( DB_NAME, null); String sql="CREATE TABLE " + table + " ( id text not null, type text not null, score text not null);"; try{ db.execSQL(sql); }catch(Exception e){ e.getStackTrace(); } db.close(); } public void Update(Context context,String table, ContentValues values, String whereClause, String[] whereArgs){ SQLiteDatabase db=SQLiteDatabase.openOrCreateDatabase(DB_NAME, null); try{ db.update(table, values, whereClause, whereArgs); }catch(Exception e){ e.getStackTrace(); } db.close(); } public Cursor Query(Context context,String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy){ SQLiteDatabase db=SQLiteDatabase.openOrCreateDatabase(DB_NAME, null); Cursor cursor = null ; try{ cursor=db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy); Log.i("wordroid=", "query"); Log.i("countofcursor=",""+cursor.getCount()); }catch(Exception e){ e.getStackTrace(); } db.close(); return cursor; } public void Delete(Context context,String table, String whereClause, String[] whereArgs){ SQLiteDatabase db=SQLiteDatabase.openOrCreateDatabase( DB_NAME, null); try{ db.delete(table, whereClause, whereArgs); Log.i("wordroid=", "delete"); } catch(Exception e){ e.getStackTrace(); } db.close(); } public void DeleteTable(Context context,String table){ SQLiteDatabase db=SQLiteDatabase.openOrCreateDatabase( DB_NAME, null); String sql="drop table " + table; try{ db.execSQL(sql); Log.i("wordroid=", sql); } catch(Exception e){ e.getStackTrace(); } db.close(); } }
JeffreyWei/caidengming
src/com/wj/caidengmi2/SqlHelper.java
Java
mit
2,463
package cmd import ( "fmt" "github.com/spf13/cobra" "os" ) const ( bashCompletionFunc = ` __todoist_select_one() { fzf } __todoist_select_multi() { fzf -m } __todoist_filter_ids() { COMPREPLY=( $(todoist filter list | __todoist_select_multi | awk '{print $1}' | tr '\n' ' ') ) } __todoist_item_id() { COMPREPLY=( $(todoist item list | __todoist_select_one | awk '{print $1}') ) } __todoist_item_ids() { COMPREPLY=( $(todoist item list | __todoist_select_multi | awk '{print $1}' | tr '\n' ' ') ) } __todoist_label_id() { COMPREPLY=( $(todoist label list | __todoist_select_one | awk '{print $1}') ) } __todoist_labels_ids() { COMPREPLY=( $(todoist label list | __todoist_select_multi | awk '{print $1}' | tr '\n' ' ') ) } __todoist_project_id() { COMPREPLY=( $(todoist project list | __todoist_select_one | awk '{print $1}') ) } __todoist_project_ids() { COMPREPLY=( $(todoist project list | __todoist_select_multi | awk '{print $1}' | tr '\n' ' ') ) } __todoist_custom_func() { case ${last_command} in todoist_filter_update | todoist_filter_delete) __todoist_filter_ids return ;; todoist_item_update | todoist_item_delete | todoist_item_move | todoist_item_complete | todoist_item_uncomplete) __todoist_item_ids return ;; todoist_label_update | todoist_label_delete) __todoist_label_id return ;; todoist_project_update | todoist_project_delete | todoist_project_archive | todoist_project_unarchive) __todoist_project_id return ;; *) ;; esac } ` ) // completionCmd represents the completion command var completionCmd = &cobra.Command{ Use: "completion", Short: "generate completion script", } var completionBashCmd = &cobra.Command{ Use: "bash", Short: "generate bash completion script", Run: func(cmd *cobra.Command, args []string) { RootCmd.GenBashCompletion(os.Stdout) }, } // Refs // - https://github.com/kubernetes/kubernetes/blob/master/pkg/kubectl/cmd/completion.go // - https://github.com/spf13/cobra/issues/107#issuecomment-270140429 var completionZshCmd = &cobra.Command{ Use: "zsh", Short: "generate zsh completion script", Run: func(cmd *cobra.Command, args []string) { zshHead := "#compdef todoist" zshInitialization := ` __todoist_bash_source() { alias shopt=':' alias _expand=_bash_expand alias _complete=_bash_comp emulate -L sh setopt kshglob noshglob braceexpand source "$@" } __todoist_type() { # -t is not supported by zsh if [ "$1" == "-t" ]; then shift # fake Bash 4 to disable "complete -o nospace". Instead # "compopt +-o nospace" is used in the code to toggle trailing # spaces. We don't support that, but leave trailing spaces on # all the time if [ "$1" = "__todoist_compopt" ]; then echo builtin return 0 fi fi type "$@" } __todoist_compgen() { local completions w completions=( $(compgen "$@") ) || return $? # filter by given word as prefix while [[ "$1" = -* && "$1" != -- ]]; do shift shift done if [[ "$1" == -- ]]; then shift fi for w in "${completions[@]}"; do if [[ "${w}" = "$1"* ]]; then echo "${w}" fi done } __todoist_compopt() { true # don't do anything. Not supported by bashcompinit in zsh } __todoist_ltrim_colon_completions() { if [[ "$1" == *:* && "$COMP_WORDBREAKS" == *:* ]]; then # Remove colon-word prefix from COMPREPLY items local colon_word=${1%${1##*:}} local i=${#COMPREPLY[*]} while [[ $((--i)) -ge 0 ]]; do COMPREPLY[$i]=${COMPREPLY[$i]#"$colon_word"} done fi } __todoist_get_comp_words_by_ref() { cur="${COMP_WORDS[COMP_CWORD]}" prev="${COMP_WORDS[${COMP_CWORD}-1]}" words=("${COMP_WORDS[@]}") cword=("${COMP_CWORD[@]}") } __todoist_filedir() { local RET OLD_IFS w qw __todoist_debug "_filedir $@ cur=$cur" if [[ "$1" = \~* ]]; then # somehow does not work. Maybe, zsh does not call this at all eval echo "$1" return 0 fi OLD_IFS="$IFS" IFS=$'\n' if [ "$1" = "-d" ]; then shift RET=( $(compgen -d) ) else RET=( $(compgen -f) ) fi IFS="$OLD_IFS" IFS="," __todoist_debug "RET=${RET[@]} len=${#RET[@]}" for w in ${RET[@]}; do if [[ ! "${w}" = "${cur}"* ]]; then continue fi if eval "[[ \"\${w}\" = *.$1 || -d \"\${w}\" ]]"; then qw="$(__todoist_quote "${w}")" if [ -d "${w}" ]; then COMPREPLY+=("${qw}/") else COMPREPLY+=("${qw}") fi fi done } __todoist_quote() { if [[ $1 == \'* || $1 == \"* ]]; then # Leave out first character printf %q "${1:1}" else printf %q "$1" fi } autoload -U +X bashcompinit && bashcompinit # use word boundary patterns for BSD or GNU sed LWORD='[[:<:]]' RWORD='[[:>:]]' if sed --help 2>&1 | grep -q GNU; then LWORD='\<' RWORD='\>' fi __todoist_convert_bash_to_zsh() { sed \ -e 's/declare -F/whence -w/' \ -e 's/_get_comp_words_by_ref "\$@"/_get_comp_words_by_ref "\$*"/' \ -e 's/local \([a-zA-Z0-9_]*\)=/local \1; \1=/' \ -e 's/flags+=("\(--.*\)=")/flags+=("\1"); two_word_flags+=("\1")/' \ -e 's/must_have_one_flag+=("\(--.*\)=")/must_have_one_flag+=("\1")/' \ -e "s/${LWORD}_filedir${RWORD}/__todoist_filedir/g" \ -e "s/${LWORD}_get_comp_words_by_ref${RWORD}/__todoist_get_comp_words_by_ref/g" \ -e "s/${LWORD}__ltrim_colon_completions${RWORD}/__todoist_ltrim_colon_completions/g" \ -e "s/${LWORD}compgen${RWORD}/__todoist_compgen/g" \ -e "s/${LWORD}compopt${RWORD}/__todoist_compopt/g" \ -e "s/${LWORD}declare${RWORD}/builtin declare/g" \ -e "s/\\\$(type${RWORD}/\$(__todoist_type/g" \ <<'BASH_COMPLETION_EOF' ` zshTail := ` BASH_COMPLETION_EOF } __todoist_bash_source <(__todoist_convert_bash_to_zsh) _complete todoist 2>/dev/null ` fmt.Println(zshHead) fmt.Print(zshInitialization) RootCmd.GenBashCompletion(os.Stdout) fmt.Print(zshTail) }, } func init() { RootCmd.AddCommand(completionCmd) completionCmd.AddCommand(completionBashCmd) completionCmd.AddCommand(completionZshCmd) }
kobtea/go-todoist
cmd/todoist/cmd/completion.go
GO
mit
5,866
<?php namespace AerialShip\SamlSPBundle\Error; class EmptySamlResponseException extends \RuntimeException { }
HearstCorp/SamlSPBundle
src/AerialShip/SamlSPBundle/Error/EmptySamlResponseException.php
PHP
mit
112
package org.penguin.kayako.domain; import org.junit.Test; import org.penguin.kayako.UnmarshallerFactory; import org.penguin.kayako.domain.NoteCollection; import org.penguin.kayako.util.ContentLoader; import javax.xml.bind.Unmarshaller; import java.io.StringReader; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class NoteCollectionTests { @Test public void testNotesUnmarshall() throws Exception { // arrange String xml = ContentLoader.loadXMLFromFileInClassPath("/example_xml_notes.xml"); Unmarshaller unmarshaller = UnmarshallerFactory.getMapper(NoteCollection.class); // act NoteCollection notes = (NoteCollection) unmarshaller.unmarshal(new StringReader(xml)); // assert assertNotNull(notes); assertEquals(1, notes.getNotes().size()); } }
penguinboy/kayako-api
src/test/java/org/penguin/kayako/domain/NoteCollectionTests.java
Java
mit
878
__author__ = 'Emil E Nielsen' start = 1 end = 17 for i in range (8): for x in range(start, end): print chr(x), if x >= 128: break print "\n" start = end + 1 end = start + 16
EENielsen/school-python
ascii-tabel.py
Python
mit
222
'use strict'; /** * Module dependencies. */ var CP_cache = require('../lib/CP_cache'); var CP_get = require('../lib/CP_get.min'); var CP_regexp = require('../lib/CP_regexp'); /** * Configuration dependencies. */ var config = require('../config/production/config'); var modules = require('../config/production/modules'); /** * Node dependencies. */ var md5 = require('md5'); var express = require('express'); var router = express.Router(); /** * RSS. */ router.get('/?', function(req, res, next) { var url = config.protocol + config.domain + req.originalUrl; var urlHash = md5(url.toLowerCase()); getRender(function (err, render) { renderData(err, render); }); /** * Get render. * * @param {Callback} callback */ function getRender(callback) { return (config.cache.time) ? getCache( function (err, render) { return (err) ? callback(err) : callback(null, render) }) : getSphinx( function (err, render) { return (err) ? callback(err) : callback(null, render) }); } /** * Get cache. * * @param {Callback} callback */ function getCache(callback) { CP_cache.get(urlHash, function (err, render) { if (err) return callback(err); return (render) ? callback(null, render) : getSphinx( function (err, render) { return (err) ? callback(err) : callback(null, render) }); }); } /** * Get sphinx. * * @param {Callback} callback */ function getSphinx(callback) { if (!modules.rss.status) { return callback('RSS is disabled!'); } var render = {}; render.config = config; render.movies = []; var collection = (req.query.collection) ? CP_regexp.str(req.query.collection) : ''; var tag = (req.query.tag) ? {"content_tags": CP_regexp.str(req.query.tag)} : ''; var ids = (req.query.ids) ? req.query.ids : ''; if (modules.content.status && collection) { CP_get.contents( {"content_url": collection}, function (err, contents) { if (err) { return callback(err); } if (contents && contents.length && contents[0].movies) { var query_id = []; contents[0].movies.forEach(function (item, i, arr) { query_id.push(item + '^' + (parseInt(arr.length) - parseInt(i))) }); var query = {"query_id": query_id.join('|')}; CP_get.movies( query, contents[0].movies.length, '', 1, function (err, movies) { if (err) { return callback(err); } render.movies = sortingIds(query_id, movies); callback(null, render); }); } else { return callback('Collection is empty!'); } }); } else if (config.index.ids.keys && ids) { var items = (((ids.replace(/[0-9,\s]/g, '')) ? config.index.ids.keys : ids.replace(/[^0-9,]/g, '')) .split(',')) .map(function (key) {return parseInt(key.trim());}); if (items && items.length) { var query_id = []; items.forEach(function (item, i, arr) { query_id.push(item + '^' + (arr.length - i)) }); var query = {"query_id": query_id.join('|')}; CP_get.movies( query, items.length, '', 1, function (err, movies) { if (err) { return callback(err); } render.movies = sortingIds(query_id, movies); callback(null, render); }); } else { return callback('No data!'); } } else if (modules.content.status && tag) { var options = {}; options.protocol = config.protocol; options.domain = config.domain; options.content_image = config.default.image; CP_get.contents( tag, 100, 1, true, options, function (err, contents) { if (err) return callback(err); if (contents && contents.length) { render.movies = contents; callback(null, render); } else { return callback('Tag does not exist!'); } }); } else { CP_get.publishIds(true, function (err, ids) { if (err) { return callback(err); } else if (!ids) { return callback('Publication is over!'); } render.movies = ids.movies; callback(null, render); }); } } /** * Render data. * * @param {Object} err * @param {Object} render */ function renderData(err, render) { if (err) { console.log('[routes/rss.js] Error:', url, err); return next({ "status": 404, "message": err }); } if (typeof render === 'object') { res.header('Content-Type', 'application/xml'); res.render('desktop/rss', render, function(err, html) { if (err) console.log('[renderData] Render Error:', err); res.send(html); if (config.cache.time && html) { CP_cache.set( urlHash, html, config.cache.time, function (err) { if (err) { if ((err+'').indexOf('1048576') + 1) { console.log('[routes/rss.js:renderData] Cache Length Error'); } else { console.log('[routes/rss.js:renderData] Cache Set Error:', err); } } } ); } }); } else { res.send(render); } } }); /** * Sort films are turned by id list. * * @param {Object} ids * @param {Object} movies * @return {Array} */ function sortingIds(ids, movies) { console.log(ids, movies); var result = []; for (var id = 0; id < ids.length; id++) { for (var i = 0; i < movies.length; i++) { if (parseInt(movies[i].kp_id) === parseInt(('' + ids[id]).trim())) { result.push(movies[i]); } } } console.log(result); return result; } module.exports = router;
CinemaPress/CinemaPress-ACMS
routes/rss.js
JavaScript
mit
8,046
({ "clearFilterDialogTitle": "Εκκαθάριση φίλτρου", "filterDefDialogTitle": "Φίλτρο", "ruleTitleTemplate": "Κανόνας ${0}", "conditionEqual": "ίσο", "conditionNotEqual": "όχι ίσο", "conditionLess": "είναι μικρότερο από", "conditionLessEqual": "μικρότερο ή ίσο", "conditionLarger": "είναι μεγαλύτερο από", "conditionLargerEqual": "μεγαλύτερο ή ίσο", "conditionContains": "περιέχει", "conditionIs": "είναι", "conditionStartsWith": "αρχίζει από", "conditionEndWith": "τελειώνει σε", "conditionNotContain": "δεν περιέχει", "conditionIsNot": "δεν είναι", "conditionNotStartWith": "δεν αρχίζει από", "conditionNotEndWith": "δεν τελειώνει σε", "conditionBefore": "πριν", "conditionAfter": "μετά", "conditionRange": "εύρος", "conditionIsEmpty": "είναι κενό", "all": "όλα", "any": "οποιοδήποτε", "relationAll": "όλοι οι κανόνες", "waiRelAll": "Αντιστοιχία με όλους τους παρακάτω κανόνες:", "relationAny": "οποιοσδήποτε κανόνας", "waiRelAny": "Αντιστοιχία με οποιονδήποτε από τους παρακάτω κανόνες:", "relationMsgFront": "Αντιστοιχία", "relationMsgTail": "", "and": "και", "or": "ή", "addRuleButton": "Προσθήκη κανόνα", "waiAddRuleButton": "Προσθήκη νέου κανόνα", "removeRuleButton": "Αφαίρεση κανόνα", "waiRemoveRuleButtonTemplate": "Αφαίρεση κανόνα ${0}", "cancelButton": "Ακύρωση", "waiCancelButton": "Ακύρωση αυτού του πλαισίου διαλόγου", "clearButton": "Εκκαθάριση", "waiClearButton": "Εκκαθάριση του φίλτρου", "filterButton": "Φίλτρο", "waiFilterButton": "Υποβολή του φίλτρου", "columnSelectLabel": "Στήλη", "waiColumnSelectTemplate": "Στήλη για τον κανόνα ${0}", "conditionSelectLabel": "Συνθήκη", "waiConditionSelectTemplate": "Συνθήκη για τον κανόνα ${0}", "valueBoxLabel": "Τιμή", "waiValueBoxTemplate": "Καταχωρήστε τιμή φίλτρου για τον κανόνα ${0}", "rangeTo": "έως", "rangeTemplate": "από ${0} έως ${1}", "statusTipHeaderColumn": "Στήλη", "statusTipHeaderCondition": "Κανόνες", "statusTipTitle": "Γραμμή φίλτρου", "statusTipMsg": "Πατήστε στη γραμμή φίλτρου για φιλτράρισμα με βάση τις τιμές στο ${0}.", "anycolumn": "οποιαδήποτε στήλη", "statusTipTitleNoFilter": "Γραμμή φίλτρου", "statusTipTitleHasFilter": "Φίλτρο", "statusTipRelPre": "Αντιστοιχία", "statusTipRelPost": "κανόνες.", "defaultItemsName": "στοιχεία", "filterBarMsgHasFilterTemplate": "Εμφανίζονται ${0} από ${1} ${2}.", "filterBarMsgNoFilterTemplate": "Δεν έχει εφαρμοστεί φίλτρο", "filterBarDefButton": "Ορισμός φίλτρου", "waiFilterBarDefButton": "Φιλτράρισμα του πίνακα", "a11yFilterBarDefButton": "Φιλτράρισμα...", "filterBarClearButton": "Εκκαθάριση φίλτρου", "waiFilterBarClearButton": "Εκκαθάριση του φίλτρου", "closeFilterBarBtn": "Κλείσιμο γραμμής φίλτρου", "clearFilterMsg": "Με την επιλογή αυτή θα αφαιρεθεί το φίλτρο και θα εμφανιστούν όλες οι διαθέσιμες εγγραφές.", "anyColumnOption": "Οποιαδήποτε στήλη", "trueLabel": "Αληθές", "falseLabel": "Ψευδές" })
henry-gobiernoabierto/geomoose
htdocs/libs/dojo/dojox/grid/enhanced/nls/el/Filter.js
JavaScript
mit
3,906
module Affiliator VERSION = "0.2.1" end
andrewls/affiliator
lib/affiliator/version.rb
Ruby
mit
42
#include "portremapsettingswidget.h" #include "controls/midichannelcombodelegate.h" #include "controls/midicontrollercombodelegate.h" #include "ui_portremapsettingswidget.h" #include <QLabel> PortRemapSettingsWidget::PortRemapSettingsWidget(PortDirection direction, QWidget *parent) : QWidget(parent), ui(new Ui::PortRemapSettingsWidget), portRemapDirection(direction) { ui->setupUi(this); MidiControllerComboDelegate *comboDelegate = new MidiControllerComboDelegate(); MidiChannelComboDelegate *midiChannelDelegate = new MidiChannelComboDelegate(); ui->m_pTblMidiControllerRemap->setItemDelegateForColumn(0, comboDelegate); ui->m_pTblMidiControllerRemap->setItemDelegateForColumn(1, comboDelegate); ui->m_pTblMidiControllerRemap->horizontalHeader()->setSectionResizeMode( QHeaderView::ResizeToContents); ui->m_pTblMidiControllerRemap->verticalHeader()->setSectionResizeMode( QHeaderView::ResizeToContents); ui->m_pTblMidiChannelMessageRemap->setItemDelegateForRow( 6, midiChannelDelegate); ui->m_pTblMidiChannelMessageRemap->horizontalHeader()->setSectionResizeMode( QHeaderView::ResizeToContents); ui->m_pTblMidiChannelMessageRemap->verticalHeader()->setSectionResizeMode( QHeaderView::ResizeToContents); createConnections(); } PortRemapSettingsWidget::~PortRemapSettingsWidget() { ui->m_pTblMidiControllerRemap->model()->deleteLater(); ui->m_pTblMidiChannelMessageRemap->model()->deleteLater(); delete ui; } void PortRemapSettingsWidget::setMidiControllerRemap( MIDIControllerRemap **midiControllerRemap) { MidiControllerRemapTM *midiControllerRemapTM = new MidiControllerRemapTM(midiControllerRemap); ui->m_pTblMidiControllerRemap->setModel(midiControllerRemapTM); int numberOfMidiContollers = static_cast<int>(sizeof(*midiControllerRemap)); for (int i = 0; i < numberOfMidiContollers; i++) { QModelIndex modelIndex = ui->m_pTblMidiControllerRemap->model()->index(i, 0, QModelIndex()); ui->m_pTblMidiControllerRemap->openPersistentEditor(modelIndex); modelIndex = ui->m_pTblMidiControllerRemap->model()->index(i, 1, QModelIndex()); ui->m_pTblMidiControllerRemap->openPersistentEditor(modelIndex); } connect(midiControllerRemapTM, &MidiControllerRemapTM::modelDataChanged, this, [=]() { emit remapDataChanged(portRemapDirection); }); } void PortRemapSettingsWidget::setMidiChannelMessagesRemap( MIDIChannelMessagesRemap **midiChannelMessagesRemap) { MidiChannelMessagesRemapTM *midiChannelMessagesRemapTM = new MidiChannelMessagesRemapTM(midiChannelMessagesRemap); ui->m_pTblMidiChannelMessageRemap->setModel(midiChannelMessagesRemapTM); for (int i = 0; i < midiChannelMessagesRemapTM->columnCount( midiChannelMessagesRemapTM->index(0, 0)); i++) { int rows = midiChannelMessagesRemapTM->rowCount( midiChannelMessagesRemapTM->index(0, 0)); QModelIndex modelIndex = midiChannelMessagesRemapTM->index(rows - 1, i); ui->m_pTblMidiChannelMessageRemap->openPersistentEditor(modelIndex); } connect(midiChannelMessagesRemapTM, &MidiChannelMessagesRemapTM::modelDataChanged, this, [=]() { emit remapDataChanged(portRemapDirection); }); } MIDIPortRemap *PortRemapSettingsWidget::getMidiPortRemap() { MIDIPortRemap *Remap = new MIDIPortRemap(); return Remap; } QTableWidgetItem *PortRemapSettingsWidget::getCheckStateItem(bool checked) { QTableWidgetItem *item = new QTableWidgetItem(); item->setCheckState(checked ? Qt::Checked : Qt::Unchecked); return item; } void PortRemapSettingsWidget::createConnections() {} /* ************************ * MidiControllerRemapTM * **************************/ MidiControllerRemapTM::MidiControllerRemapTM( MIDIControllerRemap **midiControllerRemap) { this->m_ppMidiControllerRemap = midiControllerRemap; } int MidiControllerRemapTM::rowCount(const QModelIndex &parent __attribute__((unused))) const { return sizeof(m_ppMidiControllerRemap); } int MidiControllerRemapTM::columnCount(const QModelIndex &) const { return MIDI_CHANNELS + 3; } QVariant MidiControllerRemapTM::data(const QModelIndex &index, int role) const { int row = index.row(); MIDIControllerRemap *midiControllerRemap = m_ppMidiControllerRemap[row]; switch (role) { case Qt::DisplayRole: if (index.column() == 0) { return midiControllerRemap->midiContollerSourceNumber; } else if (index.column() == 1) { return midiControllerRemap->midiContollerDestinationNumber; } break; case Qt::CheckStateRole: if (index.column() == 2) { for (int channel = 0; channel < MIDI_CHANNELS; channel++) { if (!midiControllerRemap->channel[channel]) return Qt::Unchecked; } return Qt::Checked; } if (index.column() > 2) return midiControllerRemap->channel[index.column() - 3] ? Qt::Checked : Qt::Unchecked; break; } return QVariant(); } QVariant MidiControllerRemapTM::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { switch (section) { case 0: return QString(tr("MIDI-Controller Source")); case 1: return QString(tr("MIDI-Controller Destination")); case 2: return QString(tr("all")); default: return QString::number(section - 2); } } if (role == Qt::DisplayRole && orientation == Qt::Vertical) { return QString::number(section + 1); } return QVariant(); } bool MidiControllerRemapTM::setData(const QModelIndex &index, const QVariant &value, int role) { MIDIControllerRemap *midiControllerRemap = m_ppMidiControllerRemap[index.row()]; if (role == Qt::EditRole) { if (!hasIndex(index.row(), index.column())) return false; if (index.column() == 0) { midiControllerRemap->midiContollerSourceNumber = value.toUInt(); emit modelDataChanged(); return true; } if (index.column() == 1) { midiControllerRemap->midiContollerDestinationNumber = value.toUInt(); emit modelDataChanged(); return true; } } if (role == Qt::CheckStateRole) { if (index.column() == 2) { for (int column = 0; column < MIDI_CHANNELS; column++) { midiControllerRemap->channel[column] = value.toBool(); } emit dataChanged(createIndex(index.row(), 3), createIndex(index.row(), MIDI_CHANNELS + 2)); emit modelDataChanged(); } else if (index.column() > 2) { midiControllerRemap->channel[index.column() - 3] = value.toBool(); emit dataChanged(createIndex(index.row(), 2), createIndex(index.row(), 2)); emit modelDataChanged(); } return true; } return false; } Qt::ItemFlags MidiControllerRemapTM::flags(const QModelIndex &index) const { if (index.column() > 0) return Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; return Qt::ItemIsEditable | QAbstractTableModel::flags(index); } /* ***************************** * MidiChannelMessagesRemapTM * *******************************/ MidiChannelMessagesRemapTM::MidiChannelMessagesRemapTM( MIDIChannelMessagesRemap **midiChannelMessagesRemap) { this->m_ppMidiChannelMessagesRemap = midiChannelMessagesRemap; } MidiChannelMessagesRemapTM::~MidiChannelMessagesRemapTM() { deleteLater(); } int MidiChannelMessagesRemapTM::rowCount(const QModelIndex &) const { return 7; } int MidiChannelMessagesRemapTM::columnCount(const QModelIndex &) const { return MIDI_CHANNELS; } QVariant MidiChannelMessagesRemapTM::data(const QModelIndex &index, int role) const { MIDIChannelMessagesRemap *midiChannelMessagesRemap = this->m_ppMidiChannelMessagesRemap[index.column()]; switch (role) { case Qt::CheckStateRole: switch (index.row()) { case 0: return boolToCheckState( midiChannelMessagesRemap->remapMidiPitchBendEvents); case 1: return boolToCheckState( midiChannelMessagesRemap->remapMidiChannelPressureEvents); case 2: return boolToCheckState( midiChannelMessagesRemap->remapMidiProgrammChangeEvents); case 3: return boolToCheckState( midiChannelMessagesRemap->remapMidiControlChangeEvents); case 4: return boolToCheckState( midiChannelMessagesRemap->remapMidiPolyKeyPressureEvents); case 5: return boolToCheckState( midiChannelMessagesRemap->remapMidiNoteOnOffEvents); default: return QVariant(); } case Qt::DisplayRole: switch (index.row()) { case 6: return QVariant(midiChannelMessagesRemap->remapChannel); } } return QVariant(); } QVariant MidiChannelMessagesRemapTM::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Vertical) { switch (section) { case 0: return QString(tr("Pitch Bend")); case 1: return QString(tr("Mono Key Pressure")); case 2: return QString(tr("Program Change")); case 3: return QString(tr("Control Change")); case 4: return QString(tr("Poly Key Pressure")); case 5: return QString(tr("Note On / Note Off")); case 6: return QString(tr("Map to Channel")); default: return QVariant(); } } if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { return QString::number(section + 1); } return QVariant(); } bool MidiChannelMessagesRemapTM::setData(const QModelIndex &index, const QVariant &value, int role) { MIDIChannelMessagesRemap *midiChannelMessagesRemap = this->m_ppMidiChannelMessagesRemap[index.column()]; switch (role) { case Qt::CheckStateRole: switch (index.row()) { case 0: midiChannelMessagesRemap->remapMidiPitchBendEvents = value.toBool(); break; case 1: midiChannelMessagesRemap->remapMidiChannelPressureEvents = value.toBool(); break; case 2: midiChannelMessagesRemap->remapMidiProgrammChangeEvents = value.toBool(); break; case 3: midiChannelMessagesRemap->remapMidiControlChangeEvents = value.toBool(); break; case 4: midiChannelMessagesRemap->remapMidiPolyKeyPressureEvents = value.toBool(); break; case 5: midiChannelMessagesRemap->remapMidiNoteOnOffEvents = value.toBool(); break; } emit modelDataChanged(); return true; case Qt::EditRole: switch (index.row()) { case 6: midiChannelMessagesRemap->remapChannel = static_cast<unsigned int>(value.toInt()); break; } emit modelDataChanged(); return true; } return false; } Qt::ItemFlags MidiChannelMessagesRemapTM::flags(const QModelIndex &index) const { if (index.row() < 6) return Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; return Qt::ItemIsEditable | QAbstractTableModel::flags(index); } Qt::CheckState MidiChannelMessagesRemapTM::boolToCheckState(bool value) const { if (value) return Qt::Checked; else return Qt::Unchecked; }
dehnhardt/mioconfig
src/widgets/portremapsettingswidget.cpp
C++
mit
10,679
import * as path from 'path'; import * as assert from 'assert'; import * as ttm from 'vsts-task-lib/mock-test'; import tl = require('vsts-task-lib'); import * as shared from './TestShared'; describe('Kubernetes Suite', function() { this.timeout(30000); before((done) => { process.env[shared.TestEnvVars.operatingSystem] = tl.osType().match(/^Win/) ? shared.OperatingSystems.Windows : shared.OperatingSystems.Other; done(); }); beforeEach(() => { process.env[shared.isKubectlPresentOnMachine] = "true"; delete process.env[shared.TestEnvVars.command]; delete process.env[shared.TestEnvVars.containerType]; delete process.env[shared.TestEnvVars.versionOrLocation]; delete process.env[shared.TestEnvVars.specifyLocation]; delete process.env[shared.TestEnvVars.versionSpec]; delete process.env[shared.TestEnvVars.checkLatest]; delete process.env[shared.TestEnvVars.namespace]; delete process.env[shared.TestEnvVars.arguments]; delete process.env[shared.TestEnvVars.useConfigurationFile]; delete process.env[shared.TestEnvVars.secretType]; delete process.env[shared.TestEnvVars.secretArguments]; delete process.env[shared.TestEnvVars.secretName]; delete process.env[shared.TestEnvVars.forceUpdate]; delete process.env[shared.TestEnvVars.configMapName]; delete process.env[shared.TestEnvVars.forceUpdateConfigMap]; delete process.env[shared.TestEnvVars.configMapArguments]; delete process.env[shared.TestEnvVars.outputFormat]; delete process.env[shared.TestEnvVars.kubectlOutput]; }); after(function () { }); it('Run successfully when the user provides a specific location for kubectl', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.versionOrLocation] = "location"; process.env[shared.TestEnvVars.specifyLocation] = shared.formatPath("newUserDir/kubectl.exe"); process.env[shared.isKubectlPresentOnMachine] = "false"; tr.run(); assert(tr.succeeded, 'task should have succeeded'); assert(tr.invokedToolCount == 1, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.stdout.indexOf(`Set kubectlPath to ${shared.formatPath("newUserDir/kubectl.exe")} and added permissions`) != -1, "Kubectl path should be set to the correct location"); assert(tr.stdout.indexOf(`[command]${shared.formatPath("newUserDir/kubectl.exe")} --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); it('Run successfully when the user provides the version for kubectl with checkLatest as false and version that dosent have a v prefix', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.versionOrLocation] = "version"; process.env[shared.TestEnvVars.versionSpec] = "1.7.0"; process.env[shared.isKubectlPresentOnMachine] = "false"; tr.run(); assert(tr.invokedToolCount == 1, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`Got kubectl version v1.7.0`) != -1, "Got the specific version of kubectl"); assert(tr.stdout.indexOf(`Downloaded kubectl version v1.7.0`) != -1, "Downloaded correct version of kubectl"); assert(tr.stdout.indexOf(`[command]${shared.formatPath("newUserDir/kubectl.exe")} --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); it('Run successfully when the user provides the version for kubectl with checkLatest as true', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.versionOrLocation] = "version"; process.env[shared.TestEnvVars.versionSpec] = "1.5.0"; process.env[shared.TestEnvVars.checkLatest] = "true"; process.env[shared.isKubectlPresentOnMachine] = "false"; tr.run(); assert(tr.invokedToolCount == 1, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`Get stable kubectl version`) != -1, "Stable version of kubectl is downloaded"); assert(tr.stdout.indexOf(`Got kubectl version v1.6.6`) != -1, "Got the latest version of kubectl"); assert(tr.stdout.indexOf(`Downloaded kubectl version v1.6.6`) != -1, "Downloaded correct version of kubectl"); assert(tr.stdout.indexOf(`[command]${shared.formatPath("newUserDir/kubectl.exe")} --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); it('Run successfully when the user provides the version 1.7 for kubectl with checkLatest as false', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.versionOrLocation] = "version"; process.env[shared.TestEnvVars.versionSpec] = "1.7"; process.env[shared.isKubectlPresentOnMachine] = "false"; tr.run(); assert(tr.invokedToolCount == 1, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`Get stable kubectl version`) != -1, "Stable version of kubectl is downloaded"); assert(tr.stdout.indexOf(`Got kubectl version v1.6.6`) != -1, "Got the latest version of kubectl"); assert(tr.stdout.indexOf(`Downloaded kubectl version v1.6.6`) != -1, "Downloaded correct version of kubectl"); assert(tr.stdout.indexOf(`[command]${shared.formatPath("newUserDir/kubectl.exe")} --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); it('Run fails when the user provides a wrong location for kubectl', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.versionOrLocation] = "location"; process.env[shared.TestEnvVars.specifyLocation] = shared.formatPath("wrongDir/kubectl.exe"); process.env[shared.isKubectlPresentOnMachine] = "false"; tr.run(); assert(tr.failed, 'task should have failed'); assert(tr.invokedToolCount == 0, 'should have invoked tool 0 times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length > 0 || tr.errorIssues.length, 'should have written to stderr'); assert(tr.stdout.indexOf(`Not found ${shared.formatPath("wrongDir/kubectl.exe")}`) != -1, "kubectl get should not run"); console.log(tr.stderr); done(); }); it('Runs successfully for kubectl apply using configuration file', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.apply; process.env[shared.TestEnvVars.useConfigurationFile] = "true"; tr.run(); assert(tr.invokedToolCount == 1, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} apply -f ${shared.formatPath("dir/deployment.yaml")}`) != -1, "kubectl apply should run"); console.log(tr.stderr); done(); }); it('Runs successfully for kubectl expose with configuration file and arguments', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.expose; process.env[shared.TestEnvVars.useConfigurationFile] = "true"; process.env[shared.TestEnvVars.arguments] = "--port=80 --target-port=8000"; tr.run(); assert(tr.invokedToolCount == 1, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} expose -f ${shared.formatPath("dir/deployment.yaml")} --port=80 --target-port=8000`) != -1, "kubectl expose should run"); console.log(tr.stderr); done(); }); it('Runs successfully for kubectl get', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; tr.run(); assert(tr.invokedToolCount == 1, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); it('Runs successfully for kubectl get in a particular namespace', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.namespace] = "kube-system"; tr.run(); assert(tr.invokedToolCount == 1, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get -n kube-system pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); it('Runs successfully for kubectl docker-registry secrets using Container Registry with forceUpdate', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.containerType] = shared.ContainerTypes.ContainerRegistry; process.env[shared.TestEnvVars.secretName] = "my-secret"; tr.run(); assert(tr.invokedToolCount == 2, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`DeleteSecret my-secret`) != -1, "kubectl delete should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create secret docker-registry my-secret --docker-server=https://index.docker.io/v1/ --docker-username=test --docker-password=regpassword --docker-email=test@microsoft.com`) != -1, "kubectl create should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); it('Runs successfully for kubectl docker-registry secrets using Container Registry without forceUpdate', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.containerType] = shared.ContainerTypes.ContainerRegistry; process.env[shared.TestEnvVars.secretName] = "my-secret"; process.env[shared.TestEnvVars.forceUpdate] = "false"; tr.run(); assert(tr.invokedToolCount == 2, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`DeleteSecret my-secret`) == -1, "kubectl delete should not run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create secret docker-registry my-secret --docker-server=https://index.docker.io/v1/ --docker-username=test --docker-password=regpassword --docker-email=test@microsoft.com`) != -1, "kubectl create should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); it('Runs successfully for kubectl docker-registry secrets using AzureContainerRegistry Registry with forceUpdate', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.containerType] = shared.ContainerTypes.AzureContainerRegistry; process.env[shared.TestEnvVars.secretName] = "my-secret"; tr.run(); assert(tr.invokedToolCount == 2, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`DeleteSecret my-secret`) != -1, "kubectl delete should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create secret docker-registry my-secret --docker-server=ajgtestacr1.azurecr.io --docker-username=spId --docker-password=spKey --docker-email=ServicePrincipal@AzureRM`) != -1, "kubectl create should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); it('Runs successfully for kubectl docker-registry secrets using AzureContainerRegistry without forceUpdate', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.containerType] = shared.ContainerTypes.AzureContainerRegistry; process.env[shared.TestEnvVars.secretName] = "my-secret"; process.env[shared.TestEnvVars.forceUpdate] = "false"; tr.run(); assert(tr.invokedToolCount == 2, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`DeleteSecret my-secret`) == -1, "kubectl delete should not run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create secret docker-registry my-secret --docker-server=ajgtestacr1.azurecr.io --docker-username=spId --docker-password=spKey --docker-email=ServicePrincipal@AzureRM`) != -1, "kubectl create should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); it('Runs successfully for kubectl generic secrets with forceUpdate', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.secretType] = "generic"; process.env[shared.TestEnvVars.secretArguments] = "--from-literal=key1=value1 --from-literal=key2=value2"; process.env[shared.TestEnvVars.secretName] = "my-secret"; tr.run(); assert(tr.invokedToolCount == 2, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`DeleteSecret my-secret`) != -1, "kubectl delete should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create secret generic my-secret --from-literal=key1=value1 --from-literal=key2=value2`) != -1, "kubectl create should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); it('Runs successfully for kubectl generic secrets without forceUpdate', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.secretType] = "generic"; process.env[shared.TestEnvVars.secretArguments] = "--from-literal=key1=value1 --from-literal=key2=value2"; process.env[shared.TestEnvVars.secretName] = "my-secret"; process.env[shared.TestEnvVars.forceUpdate] = "false"; tr.run(); assert(tr.invokedToolCount == 2, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`DeleteSecret my-secret`) == -1, "kubectl delete should not run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create secret generic my-secret --from-literal=key1=value1 --from-literal=key2=value2`) != -1, "kubectl create should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); /* it('Runs successfully for kubectl create configMap from file or directory with forceUpdate', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.configMapName] = "myConfigMap"; process.env[shared.TestEnvVars.useConfigMapFile] = "true"; process.env[shared.TestEnvVars.forceUpdateConfigMap] = "true"; tr.run(); assert(tr.invokedToolCount == 2, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`GetConfigMap myConfigMap`) == -1, "kubectl get should not run"); assert(tr.stdout.indexOf(`DeleteConfigMap myConfigMap`) != -1, "kubectl delete should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create configmap myConfigMap --from-file=${shared.formatPath("configMapDir/configMap.properties")}`) != -1, "kubectl create should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); it('Runs successfully for kubectl create configMap from file or directory without forceUpdate', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.configMapName] = "myConfigMap"; process.env[shared.TestEnvVars.useConfigMapFile] = "true"; tr.run(); assert(tr.invokedToolCount == 2, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`GetConfigMap myConfigMap`) != -1, "kubectl get should run"); assert(tr.stdout.indexOf(`DeleteConfigMap myConfigMap`) == -1, "kubectl delete should not run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create configmap myConfigMap --from-file=${shared.formatPath("configMapDir/configMap.properties")}`) != -1, "kubectl create should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); */ it('Runs successfully for kubectl create configMap using literal values with forceUpdate', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.configMapName] = "myConfigMap"; process.env[shared.TestEnvVars.configMapArguments] = "--from-literal=key1=value1 --from-literal=key2=value2"; process.env[shared.TestEnvVars.forceUpdateConfigMap] = "true"; tr.run(); assert(tr.invokedToolCount == 2, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`GetConfigMap myConfigMap`) == -1, "kubectl get should not run"); assert(tr.stdout.indexOf(`DeleteConfigMap myConfigMap`) != -1, "kubectl delete should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create configmap myConfigMap --from-literal=key1=value1 --from-literal=key2=value2`) != -1, "kubectl create should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); it('Runs successfully for kubectl kubectl create configMap using literal values without forceUpdate', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.configMapName] = "myConfigMap"; process.env[shared.TestEnvVars.configMapArguments] = "--from-literal=key1=value1 --from-literal=key2=value2"; tr.run(); assert(tr.invokedToolCount == 2, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`GetConfigMap myConfigMap`) != -1, "kubectl get should run"); assert(tr.stdout.indexOf(`DeleteConfigMap myConfigMap`) == -1, "kubectl delete should not run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create configmap myConfigMap --from-literal=key1=value1 --from-literal=key2=value2`) != -1, "kubectl create should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); it('Runs successfully for kubectl get and print the output in a particular format', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "secrets my-secret"; process.env[shared.TestEnvVars.outputFormat] = 'yaml'; process.env[shared.TestEnvVars.kubectlOutput] = "secretsOutputVariable"; tr.run(); assert(tr.invokedToolCount == 1, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get secrets my-secret -o yaml`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); it('Runs successfully for checking whether secrets, configmaps and kubectl commands are run in a consecutive manner', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.secretType] = "generic"; process.env[shared.TestEnvVars.secretArguments] = "--from-literal=key1=value1 --from-literal=key2=value2"; process.env[shared.TestEnvVars.secretName] = "my-secret"; process.env[shared.TestEnvVars.configMapName] = "myConfigMap"; process.env[shared.TestEnvVars.configMapArguments] = "--from-literal=key1=value1 --from-literal=key2=value2"; process.env[shared.TestEnvVars.forceUpdateConfigMap] = "true"; tr.run(); assert(tr.invokedToolCount == 3, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`DeleteSecret my-secret`) != -1, "kubectl delete should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create secret generic my-secret --from-literal=key1=value1 --from-literal=key2=value2`) != -1, "kubectl create should run"); assert(tr.stdout.indexOf(`DeleteConfigMap myConfigMap`) != -1, "kubectl delete should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create configmap myConfigMap --from-literal=key1=value1 --from-literal=key2=value2`) != -1, "kubectl create should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create secret generic my-secret --from-literal=key1=value1 --from-literal=key2=value2`) < tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create configmap myConfigMap --from-literal=key1=value1 --from-literal=key2=value2`), "kubectl create secrets should run before create configMap"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create configmap myConfigMap --from-literal=key1=value1 --from-literal=key2=value2`) < tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`), "kubectl create configMap should run before get"); console.log(tr.stderr); done(); }); it('Runs fails if create config command fails even if create secret is successful', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.secretType] = "generic"; process.env[shared.TestEnvVars.secretArguments] = "--from-literal=key1=value1 --from-literal=key2=value2"; process.env[shared.TestEnvVars.secretName] = "my-secret"; process.env[shared.TestEnvVars.configMapName] = "someConfigMap"; process.env[shared.TestEnvVars.configMapArguments] = "--from-literal=key1=value1 --from-literal=key2=value2"; tr.run(); assert(tr.invokedToolCount == 2, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.failed, 'task should have failed'); assert(tr.stdout.indexOf(`GetConfigMap someConfigMap`) != -1, "kubectl get should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create secret generic my-secret --from-literal=key1=value1 --from-literal=key2=value2`) != -1, "kubectl create should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create configmap someConfigMap --from-literal=key1=value1 --from-literal=key2=value2`) != -1, "kubectl create should run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) == -1, "kubectl get should not run"); console.log(tr.stderr); done(); }); it('Runs successfully when forceUpdateConfigMap is false and configMap exists', (done:MochaDone) => { let tp = path.join(__dirname, 'TestSetup.js'); let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp); process.env[shared.TestEnvVars.command] = shared.Commands.get; process.env[shared.TestEnvVars.arguments] = "pods"; process.env[shared.TestEnvVars.configMapName] = "existingConfigMap"; process.env[shared.TestEnvVars.configMapArguments] = "--from-literal=key1=value1 --from-literal=key2=value2"; tr.run(); assert(tr.invokedToolCount == 1, 'should have invoked tool one times. actual: ' + tr.invokedToolCount); assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdout.indexOf(`GetConfigMap existingConfigMap`) != -1, "kubectl get should run"); assert(tr.stdout.indexOf(`DeleteConfigMap existingConfigMap`) == -1, "kubectl delete should not run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} create configmap existingConfigMap --from-literal=key1=value1 --from-literal=key2=value2`) == -1, "kubectl create should not run"); assert(tr.stdout.indexOf(`[command]kubectl --kubeconfig ${shared.formatPath("newUserDir/config")} get pods`) != -1, "kubectl get should run"); console.log(tr.stderr); done(); }); });
aldoms/vsts-tasks
Tasks/Kubernetes/Tests/L0.ts
TypeScript
mit
34,309
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = true # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # SMTP Server setting (For devise) config.action_mailer.default_url_options = { host: ENV['RAILS_SMTP_HOST'] } config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: ENV['RAILS_SMTP_ADDRESS'], port: 465, authetication: :login, user_name: ENV['RAILS_SMTP_USER'], domain: ENV['RAILS_SMTP_DOMAIN'], password: ENV['RAILS_SMTP_PASSWORD'], ssl: true, tls: true, enable_starttls_auto: true, } end
azusanakano/rails-devise-ja
config/environments/development.rb
Ruby
mit
2,070
(function() { 'use strict'; angular .module('ngRouteApp') .controller('AboutController', AboutController); /** @ngInject */ function AboutController() { } })();
Toilal/showcase-ng-routers
ng-route-app/src/app/about/about.controller.js
JavaScript
mit
182
<?php namespace Cradle\Sql; use StdClass; use PHPUnit_Framework_TestCase; use Cradle\Resolver\ResolverHandler; use Cradle\Profiler\InspectorHandler; /** * Generated by PHPUnit_SkeletonGenerator on 2016-07-27 at 02:11:02. */ class Cradle_Sql_AbstractSql_Test extends PHPUnit_Framework_TestCase { /** * @var AbstractSql */ protected $object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $this->object = new AbstractSqlStub; } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. */ protected function tearDown() { } /** * @covers Cradle\Sql\AbstractSql::bind */ public function testBind() { $this->assertEquals(':bind0bind', $this->object->bind('foobar')); $this->assertEquals('(:bind1bind,:bind2bind)', $this->object->bind(array('foo','bar'))); $this->assertEquals(1, $this->object->bind(1)); } /** * @covers Cradle\Sql\AbstractSql::collection */ public function testCollection() { $collection = $this->object->collection(); $this->assertInstanceOf('Cradle\Sql\Collection', $collection); } /** * @covers Cradle\Sql\AbstractSql::deleteRows */ public function testDeleteRows() { $instance = $this->object->deleteRows('foobar', 'foo=bar'); $this->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $instance); $instance = $this->object->deleteRows('foobar', array('foo=%s', 'bar')); $this->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $instance); $instance = $this->object->deleteRows('foobar', array(array('foo=%s', 'bar'))); $this->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $instance); } /** * @covers Cradle\Sql\AbstractSql::getBinds */ public function testGetBinds() { $this->assertEquals(':bind0bind', $this->object->bind('foo')); $this->assertEquals(':bind1bind', $this->object->bind('bar')); $binds = $this->object->getBinds(); $this->assertEquals('foo', $binds[':bind0bind']); $this->assertEquals('bar', $binds[':bind1bind']); } /** * @covers Cradle\Sql\AbstractSql::getConnection */ public function testGetConnection() { $actual = $this->object->getConnection(); $this->assertEquals('foobar', $actual); } /** * @covers Cradle\Sql\AbstractSql::getDeleteQuery */ public function testGetDeleteQuery() { $actual = $this->object->getDeleteQuery('foobar'); $this->assertInstanceOf('Cradle\Sql\QueryDelete', $actual); } /** * @covers Cradle\Sql\AbstractSql::getInsertQuery */ public function testGetInsertQuery() { $actual = $this->object->getInsertQuery('foobar'); $this->assertInstanceOf('Cradle\Sql\QueryInsert', $actual); } /** * @covers Cradle\Sql\AbstractSql::getLastInsertedId */ public function testGetLastInsertedId() { $actual = $this->object->getLastInsertedId(); $this->assertEquals(123, $actual); } /** * @covers Cradle\Sql\AbstractSql::getModel */ public function testGetModel() { $model = $this->object->getModel('foobar', 'foo_id', 3); $this->assertInstanceOf('Cradle\Sql\Model', $model); } /** * @covers Cradle\Sql\AbstractSql::getRow */ public function testGetRow() { $actual = $this->object->getRow('foobar', 'foo_id', 3); $this->assertEquals('SELECT * FROM foobar WHERE foo_id = 3 LIMIT 0,1;', $actual['query']); } /** * @covers Cradle\Sql\AbstractSql::getSelectQuery */ public function testGetSelectQuery() { $actual = $this->object->getSelectQuery('foobar'); $this->assertInstanceOf('Cradle\Sql\QuerySelect', $actual); } /** * @covers Cradle\Sql\AbstractSql::getUpdateQuery */ public function testGetUpdateQuery() { $actual = $this->object->getUpdateQuery('foobar'); $this->assertInstanceOf('Cradle\Sql\QueryUpdate', $actual); } /** * @covers Cradle\Sql\AbstractSql::insertRow */ public function testInsertRow() { $instance = $this->object->insertRow('foobar', array( 'foo' => 'bar', 'bar' => null )); $this->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $instance); } /** * @covers Cradle\Sql\AbstractSql::insertRows */ public function testInsertRows() { $instance = $this->object->insertRows('foobar', array( array( 'foo' => 'bar', 'bar' => 'foo' ), array( 'foo' => 'bar', 'bar' => 'foo' ) )); $this->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $instance); } /** * @covers Cradle\Sql\AbstractSql::model */ public function testModel() { $collection = $this->object->model(); $this->assertInstanceOf('Cradle\Sql\Model', $collection); } /** * @covers Cradle\Sql\AbstractSql::query */ public function testQuery() { $actual = $this->object->query('foobar', array('foo', 'bar')); $this->assertEquals('foobar', $actual[0]['query']); } /** * @covers Cradle\Sql\AbstractSql::search */ public function testSearch() { $collection = $this->object->search('foobar'); $this->assertInstanceOf('Cradle\Sql\Search', $collection); } /** * @covers Cradle\Sql\AbstractSql::setBinds */ public function testSetBinds() { $instance = $this->object->setBinds(array( 'foo' => 'bar', 'bar' => 'foo' )); $this->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $instance); } /** * @covers Cradle\Sql\AbstractSql::setRow */ public function testSetRow() { $instance = $this->object->setRow('foobar', 'foo_id', 3, array( 'foo' => 'bar', 'bar' => 'foo' )); $this->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $instance); } /** * @covers Cradle\Sql\AbstractSql::updateRows */ public function testUpdateRows() { $instance = $this->object->updateRows('foobar', array( 'foo' => 'bar', 'bar' => 'foo' ), 'foo=bar'); $this->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $instance); } /** * @covers Cradle\Sql\AbstractSql::i */ public function testI() { $instance1 = AbstractSqlStub::i(); $this->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $instance1); $instance2 = AbstractSqlStub::i(); $this->assertTrue($instance1 !== $instance2); } /** * @covers Cradle\Sql\AbstractSql::loop */ public function testLoop() { $self = $this; $this->object->loop(function($i) use ($self) { $self->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $this); if ($i == 2) { return false; } }); } /** * @covers Cradle\Sql\AbstractSql::when */ public function testWhen() { $self = $this; $test = 'Good'; $this->object->when(function() use ($self) { $self->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $this); return false; }, function() use ($self, &$test) { $self->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $this); $test = 'Bad'; }); } /** * @covers Cradle\Sql\AbstractSql::getInspectorHandler */ public function testGetInspectorHandler() { $instance = $this->object->getInspectorHandler(); $this->assertInstanceOf('Cradle\Profiler\InspectorHandler', $instance); } /** * @covers Cradle\Sql\AbstractSql::inspect */ public function testInspect() { ob_start(); $this->object->inspect('foobar'); $contents = ob_get_contents(); ob_end_clean(); $this->assertEquals( '<pre>INSPECTING Variable:</pre><pre>foobar</pre>', $contents ); } /** * @covers Cradle\Sql\AbstractSql::setInspectorHandler */ public function testSetInspectorHandler() { $instance = $this->object->setInspectorHandler(new InspectorHandler); $this->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $instance); } /** * @covers Cradle\Sql\AbstractSql::addLogger */ public function testAddLogger() { $instance = $this->object->addLogger(function() {}); $this->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $instance); } /** * @covers Cradle\Sql\AbstractSql::log */ public function testLog() { $trigger = new StdClass(); $trigger->success = null; $this->object->addLogger(function($trigger) { $trigger->success = true; }) ->log($trigger); $this->assertTrue($trigger->success); } /** * @covers Cradle\Sql\AbstractSql::loadState */ public function testLoadState() { $state1 = new AbstractSqlStub(); $state2 = new AbstractSqlStub(); $state1->saveState('state1'); $state2->saveState('state2'); $this->assertTrue($state2 === $state1->loadState('state2')); $this->assertTrue($state1 === $state2->loadState('state1')); } /** * @covers Cradle\Sql\AbstractSql::saveState */ public function testSaveState() { $state1 = new AbstractSqlStub(); $state2 = new AbstractSqlStub(); $state1->saveState('state1'); $state2->saveState('state2'); $this->assertTrue($state2 === $state1->loadState('state2')); $this->assertTrue($state1 === $state2->loadState('state1')); } /** * @covers Cradle\Sql\AbstractSql::__call * @todo Implement test__call(). */ public function test__call() { $actual = $this->object->addResolver(ResolverCallStub::class, function() {}); $this->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $actual); } /** * @covers Cradle\Sql\AbstractSql::__callResolver * @todo Implement test__callResolver(). */ public function test__callResolver() { $actual = $this->object->addResolver(ResolverCallStub::class, function() {}); $this->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $actual); } /** * @covers Cradle\Sql\AbstractSql::addResolver */ public function testAddResolver() { $actual = $this->object->addResolver(ResolverCallStub::class, function() {}); $this->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $actual); } /** * @covers Cradle\Sql\AbstractSql::getResolverHandler */ public function testGetResolverHandler() { $actual = $this->object->getResolverHandler(); $this->assertInstanceOf('Cradle\Resolver\ResolverHandler', $actual); } /** * @covers Cradle\Sql\AbstractSql::resolve */ public function testResolve() { $actual = $this->object->addResolver( ResolverCallStub::class, function() { return new ResolverAddStub(); } ) ->resolve(ResolverCallStub::class) ->foo('bar'); $this->assertEquals('barfoo', $actual); } /** * @covers Cradle\Sql\AbstractSql::resolveShared */ public function testResolveShared() { $actual = $this ->object ->resolveShared(ResolverSharedStub::class) ->reset() ->foo('bar'); $this->assertEquals('barfoo', $actual); $actual = $this ->object ->resolveShared(ResolverSharedStub::class) ->foo('bar'); $this->assertEquals('barbar', $actual); } /** * @covers Cradle\Sql\AbstractSql::resolveStatic */ public function testResolveStatic() { $actual = $this ->object ->resolveStatic( ResolverStaticStub::class, 'foo', 'bar' ); $this->assertEquals('barfoo', $actual); } /** * @covers Cradle\Sql\AbstractSql::setResolverHandler */ public function testSetResolverHandler() { $actual = $this->object->setResolverHandler(new ResolverHandler); $this->assertInstanceOf('Cradle\Sql\AbstractSqlStub', $actual); } } if(!class_exists('Cradle\Sql\AbstractSqlStub')) { class AbstractSqlStub extends AbstractSql implements SqlInterface { public function connect($options = []) { $this->connection = 'foobar'; return $this; } public function getLastInsertedId($column = null) { return 123; } public function query($query, array $binds = [], $fetch = null) { return array(array( 'total' => 123, 'query' => (string) $query, 'binds' => $binds )); } public function getColumns() { return array( array( 'Field' => 'foobar_id', 'Type' => 'int', 'Key' => 'PRI', 'Default' => null, 'Null' => 1 ), array( 'Field' => 'foobar_title', 'Type' => 'vachar', 'Key' => null, 'Default' => null, 'Null' => 1 ), array( 'Field' => 'foobar_date', 'Type' => 'datetime', 'Key' => null, 'Default' => null, 'Null' => 1 ) ); } } } if(!class_exists('Cradle\Sql\ResolverCallStub')) { class ResolverCallStub { public function foo($string) { return $string . 'foo'; } } } if(!class_exists('Cradle\Sql\ResolverAddStub')) { class ResolverAddStub { public function foo($string) { return $string . 'foo'; } } } if(!class_exists('Cradle\Sql\ResolverSharedStub')) { class ResolverSharedStub { public $name = 'foo'; public function foo($string) { $name = $this->name; $this->name = $string; return $string . $name; } public function reset() { $this->name = 'foo'; return $this; } } } if(!class_exists('Cradle\Sql\ResolverStaticStub')) { class ResolverStaticStub { public static function foo($string) { return $string . 'foo'; } } }
CradlePHP/packages
test/Sql/AbstractSql.php
PHP
mit
15,278
/* * The MIT License (MIT) * * Copyright (c) 2013 Milad Naseri. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mmnaseri.dragonfly.metadata; /** * @author Milad Naseri (mmnaseri@programmer.net) * @since 1.0 (14/8/21 AD, 15:04) */ public interface PagingMetadata { /** * @return the number of items in each page */ int getPageSize(); /** * @return the page number to display, starting from 1 and onwards */ int getPageNumber(); }
agileapes/dragonfly
dragonfly-core/src/main/java/com/mmnaseri/dragonfly/metadata/PagingMetadata.java
Java
mit
1,516
<?php /** * This file is part of the contentful/contentful-management package. * * @copyright 2015-2022 Contentful GmbH * @license MIT */ declare(strict_types=1); namespace Contentful\Management\Resource; use Contentful\Core\Api\Link; use Contentful\Core\Resource\SystemPropertiesInterface; use Contentful\Management\Client; use function GuzzleHttp\json_encode as guzzle_json_encode; /** * BaseResource class. */ abstract class BaseResource implements ResourceInterface { /** * @var SystemPropertiesInterface */ protected $sys; /** * @var Client|null */ protected $client; /** * {@inheritdoc} */ public function getId(): string { return $this->getSystemProperties()->getId(); } /** * {@inheritdoc} */ public function getType(): string { return $this->getSystemProperties()->getType(); } /** * {@inheritdoc} */ public function asLink(): Link { return new Link($this->getId(), $this->getType()); } /** * {@inheritdoc} */ public function asRequestBody() { $body = $this->jsonSerialize(); unset($body['sys']); return guzzle_json_encode((object) $body, \JSON_UNESCAPED_UNICODE); } /** * Sets the current Client object instance. * This is done automatically when performing API calls, * so it shouldn't be used manually. * * @return static */ public function setClient(Client $client) { $this->client = $client; return $this; } }
contentful/contentful-management.php
src/Resource/BaseResource.php
PHP
mit
1,597
# A simple DOC file parser based on pyole import os import struct import logging import datetime from pyole import * class FIBBase(OLEBase): wIdent = 0 nFib = 0 unused = 0 lid = 0 pnNext = 0 Flags1 = 0 fDot = 0 fGlsy = 0 fComplex = 0 fHasPic = 0 cQuickSaves = 0 fEncrypted = 0 fWhichTblStm = 0 fReadOnlyRecommended = 0 fWriteReservation = 0 fExtChar = 0 fLoadOverride = 0 fFarEast = 0 fObfuscated = 0 nFibBack = 0 lKey = 0 envr = 0 Flag2 = 0 fMac = 0 fEmptySpecial = 0 fLoadOverridePage = 0 reserved1 = 0 reserved2 = 0 fSpare0 = 0 reserved3 = 0 reserved4 = 0 reserved5 = 0 reserved6 = 0 def __init__(self, data): self.wIdent = 0 self.nFib = 0 self.unused = 0 self.pnNext = 0 self.Flags1 = 0 self.fDot = 0 self.fGlsy = 0 self.fComplex = 0 self.fHasPic = 0 self.cQuickSaves = 0 self.fEncrypted = 0 self.fWhichTblStm = 0 self.fReadOnlyRecommended = 0 self.fWriteReservation = 0 self.fExtChar = 0 self.fLoadOverride = 0 self.fFarEast = 0 self.fObfuscated = 0 self.nFibBack = 0 self.lKey = 0 self.envr = 0 self.Flag2 = 0 self.fMac = 0 self.fEmptySpecial = 0 self.fLoadOverridePage = 0 self.reserved1 = 0 self.reserved2 = 0 self.fSpare0 = 0 self.reserved3 = 0 self.reserved4 = 0 self.reserved5 = 0 self.reserved6 = 0 self.wIdent = struct.unpack('<H', data[0x00:0x02])[0] self.ole_logger.debug('DOC.FIB.FIBBase.wIdent: ' + str(hex(self.wIdent))) if self.wIdent != 0xA5EC: self._raise_exception('DOC.FIB.FIBBase.wIdent has an abnormal value.') self.nFib = struct.unpack('<H', data[0x02:0x04])[0] self.ole_logger.debug('DOC.FIB.FIBBase.nFib: ' + str(hex(self.nFib))) if self.nFib != 0x00C1: self._raise_exception('DOC.FIB.FIBBase.nFib has an abnormal value.') self.unused = struct.unpack('<H', data[0x04:0x06])[0] self.ole_logger.debug('DOC.FIB.FIBBase.unused: ' + str(hex(self.unused))) #if self.unused != 0: # self.ole_logger.warning('DOC.FIB.FIBBase.unused is not zero.') self.lid = struct.unpack('<H', data[0x06:0x08])[0] self.ole_logger.debug('DOC.FIB.FIBBase.lid: ' + str(hex(self.lid))) self.pnNext = struct.unpack('<H', data[0x08:0x0A])[0] self.ole_logger.debug('DOC.FIB.FIBBase.pnNext: ' + str(hex(self.pnNext))) if self.pnNext != 0: self.ole_logger.warning('DOC.FIB.FIBBase.pnNext is not zero.') self.Flags1 = struct.unpack('<H', data[0x0A:0x0C])[0] self.fDot = self.Flags1 & 0x0001 self.ole_logger.debug('DOC.FIB.FIBBase.fDot: ' + str(self.fDot)) self.fGlsy = (self.Flags1 & 0x0002) >> 1 self.ole_logger.debug('DOC.FIB.FIBBase.fGlsy: ' + str(self.fGlsy)) self.fComplex = (self.Flags1 & 0x0004) >> 2 self.ole_logger.debug('DOC.FIB.FIBBase.fComplex: ' + str(self.fComplex)) self.fHasPic = (self.Flags1 & 0x0008) >> 3 self.ole_logger.debug('DOC.FIB.FIBBase.fHasPic: ' + str(self.fHasPic)) self.cQuickSaves = (self.Flags1 & 0x00F0) >> 4 self.ole_logger.debug('DOC.FIB.FIBBase.cQuickSaves: ' + str(self.cQuickSaves)) self.fEncrypted = (self.Flags1 & 0x0100) >> 8 self.ole_logger.debug('DOC.FIB.FIBBase.fEncrypted: ' + str(self.fEncrypted)) if self.fEncrypted == 1: self.ole_logger.warning('File is encrypted.') self.fWhichTblStm = (self.Flags1 & 0x0200) >> 9 self.ole_logger.debug('DOC.FIB.FIBBase.fWhichTblStm: ' + str(self.fWhichTblStm)) self.fReadOnlyRecommended = (self.Flags1 & 0x0400) >> 10 self.ole_logger.debug('DOC.FIB.FIBBase.fReadOnlyRecommended: ' + str(self.fReadOnlyRecommended)) self.fWriteReservation = (self.Flags1 & 0x0800) >> 11 self.ole_logger.debug('DOC.FIB.FIBBase.fWriteReservation: ' + str(self.fWriteReservation)) self.fExtChar = (self.Flags1 & 0x1000) >> 12 self.ole_logger.debug('DOC.FIB.FIBBase.fExtChar: ' + str(self.fExtChar)) if (self.Flags1 & 0x1000) >> 12 != 1: self._raise_exception('DOC.FIB.FIBBase.fExtChar has an abnormal value.') self.fLoadOverride = (self.Flags1 & 0x2000) >> 13 self.ole_logger.debug('DOC.FIB.FIBBase.fLoadOverride: ' + str(self.fLoadOverride)) self.fFarEast = (self.Flags1 & 0x4000) >> 14 self.ole_logger.debug('DOC.FIB.FIBBase.fFarEast: ' + str(self.fFarEast)) if self.fFarEast == 1: self.ole_logger.warning('The installation language of the application that created the document was an East Asian language.') self.fObfuscated = (self.Flags1 & 0x8000) >> 15 self.ole_logger.debug('DOC.FIB.FIBBase.fObfuscated: ' + str(self.fObfuscated)) if self.fObfuscated == 1: if self.fEncrypted == 1: self.ole_logger.warning('File is obfuscated by using XOR obfuscation.') self.nFibBack = struct.unpack('<H', data[0x0C:0x0E])[0] self.ole_logger.debug('DOC.FIB.FIBBase.nFibBack: ' + str(hex(self.nFibBack))) if self.nFibBack != 0x00BF and self.nFibBack != 0x00C1: self._raise_exception('DOC.FIB.FIBBase.nFibBack has an abnormal value.') self.lKey = struct.unpack('<I', data[0x0E:0x12])[0] self.ole_logger.debug('DOC.FIB.FIBBase.lKey: ' + str(hex(self.lKey))) if self.fEncrypted == 1: if self.fObfuscated == 1: self.ole_logger.info('The XOR obfuscation key is: ' + str(hex(self.lKey))) else: if self.lKey != 0: self._raise_exception('DOC.FIB.FIBBase.lKey has an abnormal value.') self.envr = ord(data[0x12]) self.ole_logger.debug('DOC.FIB.FIBBase.envr: ' + str(hex(self.envr))) if self.envr != 0: self._raise_exception('DOC.FIB.FIBBase.envr has an abnormal value.') self.Flag2 = ord(data[0x13]) self.fMac = self.Flag2 & 0x01 self.ole_logger.debug('DOC.FIB.FIBBase.fMac: ' + str(hex(self.fMac))) if self.fMac != 0: self._raise_exception('DOC.FIB.FIBBase.fMac has an abnormal value.') self.fEmptySpecial = (self.Flag2 & 0x02) >> 1 self.ole_logger.debug('DOC.FIB.FIBBase.fEmptySpecial: ' + str(hex(self.fEmptySpecial))) if self.fEmptySpecial != 0: self.ole_logger.warning('DOC.FIB.FIBBase.fEmptySpecial is not zero.') self.fLoadOverridePage = (self.Flag2 & 0x04) >> 2 self.ole_logger.debug('DOC.FIB.FIBBase.fLoadOverridePage: ' + str(hex(self.fLoadOverridePage))) self.reserved1 = (self.Flag2 & 0x08) >> 3 self.ole_logger.debug('DOC.FIB.FIBBase.reserved1: ' + str(hex(self.reserved1))) self.reserved2 = (self.Flag2 & 0x10) >> 4 self.ole_logger.debug('DOC.FIB.FIBBase.reserved2: ' + str(hex(self.reserved2))) self.fSpare0 = (self.Flag2 & 0xE0) >> 5 self.ole_logger.debug('DOC.FIB.FIBBase.fSpare0: ' + str(hex(self.fSpare0))) self.reserved3 = struct.unpack('<H', data[0x14:0x16])[0] self.ole_logger.debug('DOC.FIB.FIBBase.reserved3: ' + str(hex(self.reserved3))) self.reserved4 = struct.unpack('<H', data[0x16:0x18])[0] self.ole_logger.debug('DOC.FIB.FIBBase.reserved4: ' + str(hex(self.reserved4))) self.reserved5 = struct.unpack('<I', data[0x18:0x1C])[0] self.ole_logger.debug('DOC.FIB.FIBBase.reserved5: ' + str(hex(self.reserved5))) self.reserved6 = struct.unpack('<I', data[0x1C:0x20])[0] self.ole_logger.debug('DOC.FIB.FIBBase.reserved6: ' + str(hex(self.reserved6))) class FibRgFcLcb(OLEBase): fcSttbfAssoc = 0 lcbSttbfAssoc = 0 fcSttbfRMark = 0 lcbSttbfRMark = 0 fcSttbSavedBy = 0 lcbSttbSavedBy = 0 dwLowDateTime = 0 dwHighDateTime = 0 def __init__(self, data): self.fcSttbfAssoc = 0 self.lcbSttbfAssoc = 0 self.fcSttbfRMark = 0 self.lcbSttbfRMark = 0 self.fcSttbSavedBy = 0 self.lcbSttbSavedBy = 0 self.dwLowDateTime = 0 self.dwHighDateTime = 0 self.fcSttbfAssoc = struct.unpack('<I', data[0x100:0x104])[0] self.ole_logger.debug('DOC.FIB.FibRgFcLcb.fcSttbfAssoc: ' + str(hex(self.fcSttbfAssoc))) self.lcbSttbfAssoc = struct.unpack('<I', data[0x104:0x108])[0] self.ole_logger.debug('DOC.FIB.FibRgFcLcb.lcbSttbfAssoc: ' + str(hex(self.lcbSttbfAssoc))) self.fcSttbfRMark = struct.unpack('<I', data[0x198:0x19C])[0] self.ole_logger.debug('DOC.FIB.FibRgFcLcb.fcSttbfRMark: ' + str(hex(self.fcSttbfRMark))) self.lcbSttbfRMark = struct.unpack('<I', data[0x19C:0x1A0])[0] self.ole_logger.debug('DOC.FIB.FibRgFcLcb.lcbSttbfRMark: ' + str(hex(self.lcbSttbfRMark))) self.fcSttbSavedBy = struct.unpack('<I', data[0x238:0x23C])[0] self.ole_logger.debug('DOC.FIB.FibRgFcLcb.fcSttbSavedBy: ' + str(hex(self.fcSttbSavedBy))) self.lcbSttbSavedBy = struct.unpack('<I', data[0x23C:0x240])[0] self.ole_logger.debug('DOC.FIB.FibRgFcLcb.lcbSttbSavedBy: ' + str(hex(self.lcbSttbSavedBy))) self.dwLowDateTime = struct.unpack('<I', data[0x2B8:0x2BC])[0] self.ole_logger.debug('DOC.FIB.FibRgFcLcb.dwLowDateTime: ' + str(hex(self.dwLowDateTime))) self.dwHighDateTime = struct.unpack('<I', data[0x2BC:0x2C0])[0] self.ole_logger.debug('DOC.FIB.FibRgFcLcb.dwHighDateTime: ' + str(hex(self.dwHighDateTime))) class FIB(OLEBase): FIBBase = None csw = 0 fibRgW = '' cslw = 0 fibRgLw = '' cbRgFcLcb = 0 fibRgFcLcbBlob = '' cswNew = 0 def __init__(self, data): self.FIBBase = None self.csw = 0 self.fibRgW = '' self.cslw = 0 self.fibRgLw = '' self.cbRgFcLcb = 0 self.fibRgFcLcbBlob = '' self.cswNew = 0 self.ole_logger.debug('######## FIB ########') self.FIBBase = FIBBase(data[0:0x20]) self.csw = struct.unpack('<H', data[0x20:0x22])[0] self.ole_logger.debug('DOC.FIB.csw: ' + str(hex(self.csw))) if self.csw != 0x000E: self._raise_exception('DOC.FIB.csw has an abnormal value.') self.fibRgW = data[0x22:0x3E] self.cslw = struct.unpack('<H', data[0x3E:0x40])[0] self.ole_logger.debug('DOC.FIB.cslw: ' + str(hex(self.cslw))) if self.cslw != 0x0016: self._raise_exception('DOC.FIB.cslw has an abnormal value.') self.fibRgLw = data[0x40:0x98] self.cbRgFcLcb = struct.unpack('<H', data[0x98:0x9A])[0] self.ole_logger.debug('DOC.FIB.cbRgFcLcb: ' + str(hex(self.cbRgFcLcb))) ''' if self.FIBBase.nFib == 0x00C1 and self.cbRgFcLcb != 0x005D: self._raise_exception('DOC.FIB.cbRgFcLcb has an abnormal value.') if self.FIBBase.nFib == 0x00D9 and self.cbRgFcLcb != 0x006C: self._raise_exception('DOC.FIB.cbRgFcLcb has an abnormal value.') if self.FIBBase.nFib == 0x0101 and self.cbRgFcLcb != 0x0088: self._raise_exception('DOC.FIB.cbRgFcLcb has an abnormal value.') if self.FIBBase.nFib == 0x010C and self.cbRgFcLcb != 0x00A4: self._raise_exception('DOC.FIB.cbRgFcLcb has an abnormal value.') if self.FIBBase.nFib == 0x0112 and self.cbRgFcLcb != 0x00B7: self._raise_exception('DOC.FIB.cbRgFcLcb has an abnormal value.') ''' self.fibRgFcLcbBlob = FibRgFcLcb(data[0x9A:0x9A+self.cbRgFcLcb*8]) self.cswNew = struct.unpack('<H', data[0x9A+self.cbRgFcLcb*8:0x9A+self.cbRgFcLcb*8+0x02])[0] self.ole_logger.debug('DOC.FIB.cswNew: ' + str(hex(self.cswNew))) class DOCFile(OLEBase): OLE = None FIB = None SummaryInfo = None DocumentSummaryInfo = None def __init__(self, filename): self.OLE = None self.FIB = None self.SummaryInfo = None self.DocumentSummaryInfo = None if os.path.isfile(filename) == False: self._raise_exception('Invalid file: ' + filename) self.OLE = OLEFile(filename) self.ole_logger.debug('***** Parse Word Document *****') self.FIB = FIB(self.OLE.find_object_by_name('WordDocument')) def show_rmark_authors(self): if self.FIB.fibRgFcLcbBlob.fcSttbfRMark != 0: table_stream = '' if self.FIB.FIBBase.fWhichTblStm == 1: table_stream = self.OLE.find_object_by_name('1Table') elif self.FIB.FIBBase.fWhichTblStm == 1: table_stream = self.OLE.find_object_by_name('0Table') else: print 'DOC.FIB.FIBBase.fWhichTblStm has an abnormal value.' return if len(table_stream) > 0: #print table_stream offset = self.FIB.fibRgFcLcbBlob.fcSttbfRMark length = self.FIB.fibRgFcLcbBlob.lcbSttbfRMark SttbfRMark = table_stream[offset:offset+length] fExtend = struct.unpack('<H', SttbfRMark[0x00:0x02])[0] if fExtend != 0xFFFF: print 'fExtend has an abnormal value.' return cbExtra = struct.unpack('<H', SttbfRMark[0x04:0x06])[0] if cbExtra != 0: print 'cbExtra has an abnormal value.' return cData = struct.unpack('<H', SttbfRMark[0x02:0x04])[0] offset = 0 for i in range(0, cData): cchData = struct.unpack('<H', SttbfRMark[0x06+offset:0x08+offset])[0] Data = SttbfRMark[0x06+offset+0x02:0x08+offset+cchData*2] print Data.decode('utf-16') offset = offset + 0x02 + cchData*2 else: print 'Failed to read the Table Stream.' else: print 'No revision marks or comments author information.' if __name__ == '__main__': init_logging(True) try: docfile = DOCFile('oletest.doc') docfile.show_rmark_authors() except Exception as e: print e
z3r0zh0u/pyole
pydoc.py
Python
mit
14,460
"use strict"; var $ = require("jquery"); var _ = require("underscore"); /** * Adds relative attribute functions: minimum, maximum, equals. * * @param c The comparator function * @param a The attribute name * @param e1 The first element (the element to act upon) * @param s The selector to evaluate as an element to compare to */ function apply(c, a, e1, s) { var e2 = _.first($(s)); if (!e2) return; if (c(parseInt(e1.css(a)), parseInt(e2.css(a)))) { e1.css(a, e2.css(a)); } } var Relative = _.reduce({ "minimum": function(a, b) { return a < b; }, "maximum": function(a, b) { return a > b; }, "equals": function(a, b) { return a == b; } }, function(h, fn, a) { return h[a] = _.partial(apply, fn); }, {}); // alias equals Relative.equal = Relative.equals; console.log("Loaded Relative module"); module.exports = Relative;
sjohnr/behaviors.js
src/main/js/lib/Relative.js
JavaScript
mit
852
<?php namespace EntityManager50f974421cab3_546a8d27f194334ee012bfe64f629947b07e4919\__CG__\Doctrine\ORM; /** * CG library enhanced proxy class. * * This code was generated automatically by the CG library, manual changes to it * will be lost upon next generation. */ class EntityManager extends \Doctrine\ORM\EntityManager { private $delegate; private $container; /** * Executes a function in a transaction. * * The function gets passed this EntityManager instance as an (optional) parameter. * * {@link flush} is invoked prior to transaction commit. * * If an exception occurs during execution of the function or flushing or transaction commit, * the transaction is rolled back, the EntityManager closed and the exception re-thrown. * * @param callable $func The function to execute transactionally. * @return mixed Returns the non-empty value returned from the closure or true instead */ public function transactional($func) { return $this->delegate->transactional($func); } /** * Performs a rollback on the underlying database connection. */ public function rollback() { return $this->delegate->rollback(); } /** * Removes an entity instance. * * A removed entity will be removed from the database at or before transaction commit * or as a result of the flush operation. * * @param object $entity The entity instance to remove. */ public function remove($entity) { return $this->delegate->remove($entity); } /** * Refreshes the persistent state of an entity from the database, * overriding any local changes that have not yet been persisted. * * @param object $entity The entity to refresh. */ public function refresh($entity) { return $this->delegate->refresh($entity); } /** * Tells the EntityManager to make an instance managed and persistent. * * The entity will be entered into the database at or before transaction * commit or as a result of the flush operation. * * NOTE: The persist operation always considers entities that are not yet known to * this EntityManager as NEW. Do not pass detached entities to the persist operation. * * @param object $object The instance to make managed and persistent. */ public function persist($entity) { return $this->delegate->persist($entity); } /** * Create a new instance for the given hydration mode. * * @param int $hydrationMode * @return \Doctrine\ORM\Internal\Hydration\AbstractHydrator */ public function newHydrator($hydrationMode) { return $this->delegate->newHydrator($hydrationMode); } /** * Merges the state of a detached entity into the persistence context * of this EntityManager and returns the managed copy of the entity. * The entity passed to merge will not become associated/managed with this EntityManager. * * @param object $entity The detached entity to merge into the persistence context. * @return object The managed copy of the entity. */ public function merge($entity) { return $this->delegate->merge($entity); } /** * Acquire a lock on the given entity. * * @param object $entity * @param int $lockMode * @param int $lockVersion * @throws OptimisticLockException * @throws PessimisticLockException */ public function lock($entity, $lockMode, $lockVersion = NULL) { return $this->delegate->lock($entity, $lockMode, $lockVersion); } /** * Check if the Entity manager is open or closed. * * @return bool */ public function isOpen() { return $this->delegate->isOpen(); } /** * Checks whether the state of the filter collection is clean. * * @return boolean True, if the filter collection is clean. */ public function isFiltersStateClean() { return $this->delegate->isFiltersStateClean(); } /** * Helper method to initialize a lazy loading proxy or persistent collection. * * This method is a no-op for other objects * * @param object $obj */ public function initializeObject($obj) { return $this->delegate->initializeObject($obj); } /** * Checks whether the Entity Manager has filters. * * @return True, if the EM has a filter collection. */ public function hasFilters() { return $this->delegate->hasFilters(); } /** * Gets the UnitOfWork used by the EntityManager to coordinate operations. * * @return \Doctrine\ORM\UnitOfWork */ public function getUnitOfWork() { return $this->delegate->getUnitOfWork(); } /** * Gets the repository for an entity class. * * @param string $entityName The name of the entity. * @return EntityRepository The repository class. */ public function getRepository($className) { $repository = $this->delegate->getRepository($className); if ($repository instanceof \Symfony\Component\DependencyInjection\ContainerAwareInterface) { $repository->setContainer($this->container); return $repository; } if (null !== $metadata = $this->container->get("jms_di_extra.metadata.metadata_factory")->getMetadataForClass(get_class($repository))) { foreach ($metadata->classMetadata as $classMetadata) { foreach ($classMetadata->methodCalls as $call) { list($method, $arguments) = $call; call_user_func_array(array($repository, $method), $this->prepareArguments($arguments)); } } } return $repository; } /** * Gets a reference to the entity identified by the given type and identifier * without actually loading it, if the entity is not yet loaded. * * @param string $entityName The name of the entity type. * @param mixed $id The entity identifier. * @return object The entity reference. */ public function getReference($entityName, $id) { return $this->delegate->getReference($entityName, $id); } /** * Gets the proxy factory used by the EntityManager to create entity proxies. * * @return ProxyFactory */ public function getProxyFactory() { return $this->delegate->getProxyFactory(); } /** * Gets a partial reference to the entity identified by the given type and identifier * without actually loading it, if the entity is not yet loaded. * * The returned reference may be a partial object if the entity is not yet loaded/managed. * If it is a partial object it will not initialize the rest of the entity state on access. * Thus you can only ever safely access the identifier of an entity obtained through * this method. * * The use-cases for partial references involve maintaining bidirectional associations * without loading one side of the association or to update an entity without loading it. * Note, however, that in the latter case the original (persistent) entity data will * never be visible to the application (especially not event listeners) as it will * never be loaded in the first place. * * @param string $entityName The name of the entity type. * @param mixed $identifier The entity identifier. * @return object The (partial) entity reference. */ public function getPartialReference($entityName, $identifier) { return $this->delegate->getPartialReference($entityName, $identifier); } /** * Gets the metadata factory used to gather the metadata of classes. * * @return \Doctrine\ORM\Mapping\ClassMetadataFactory */ public function getMetadataFactory() { return $this->delegate->getMetadataFactory(); } /** * Gets a hydrator for the given hydration mode. * * This method caches the hydrator instances which is used for all queries that don't * selectively iterate over the result. * * @param int $hydrationMode * @return \Doctrine\ORM\Internal\Hydration\AbstractHydrator */ public function getHydrator($hydrationMode) { return $this->delegate->getHydrator($hydrationMode); } /** * Gets the enabled filters. * * @return FilterCollection The active filter collection. */ public function getFilters() { return $this->delegate->getFilters(); } /** * Gets an ExpressionBuilder used for object-oriented construction of query expressions. * * Example: * * <code> * $qb = $em->createQueryBuilder(); * $expr = $em->getExpressionBuilder(); * $qb->select('u')->from('User', 'u') * ->where($expr->orX($expr->eq('u.id', 1), $expr->eq('u.id', 2))); * </code> * * @return \Doctrine\ORM\Query\Expr */ public function getExpressionBuilder() { return $this->delegate->getExpressionBuilder(); } /** * Gets the EventManager used by the EntityManager. * * @return \Doctrine\Common\EventManager */ public function getEventManager() { return $this->delegate->getEventManager(); } /** * Gets the database connection object used by the EntityManager. * * @return \Doctrine\DBAL\Connection */ public function getConnection() { return $this->delegate->getConnection(); } /** * Gets the Configuration used by the EntityManager. * * @return \Doctrine\ORM\Configuration */ public function getConfiguration() { return $this->delegate->getConfiguration(); } /** * Returns the ORM metadata descriptor for a class. * * The class name must be the fully-qualified class name without a leading backslash * (as it is returned by get_class($obj)) or an aliased class name. * * Examples: * MyProject\Domain\User * sales:PriceRequest * * @return \Doctrine\ORM\Mapping\ClassMetadata * @internal Performance-sensitive method. */ public function getClassMetadata($className) { return $this->delegate->getClassMetadata($className); } /** * Flushes all changes to objects that have been queued up to now to the database. * This effectively synchronizes the in-memory state of managed objects with the * database. * * If an entity is explicitly passed to this method only this entity and * the cascade-persist semantics + scheduled inserts/removals are synchronized. * * @param object $entity * @throws \Doctrine\ORM\OptimisticLockException If a version check on an entity that * makes use of optimistic locking fails. */ public function flush($entity = NULL) { return $this->delegate->flush($entity); } /** * Finds an Entity by its identifier. * * @param string $entityName * @param mixed $id * @param integer $lockMode * @param integer $lockVersion * * @return object */ public function find($entityName, $id, $lockMode = 0, $lockVersion = NULL) { return $this->delegate->find($entityName, $id, $lockMode, $lockVersion); } /** * Detaches an entity from the EntityManager, causing a managed entity to * become detached. Unflushed changes made to the entity if any * (including removal of the entity), will not be synchronized to the database. * Entities which previously referenced the detached entity will continue to * reference it. * * @param object $entity The entity to detach. */ public function detach($entity) { return $this->delegate->detach($entity); } /** * Create a QueryBuilder instance * * @return QueryBuilder $qb */ public function createQueryBuilder() { return $this->delegate->createQueryBuilder(); } /** * Creates a new Query object. * * @param string $dql The DQL string. * @return \Doctrine\ORM\Query */ public function createQuery($dql = '') { return $this->delegate->createQuery($dql); } /** * Creates a native SQL query. * * @param string $sql * @param ResultSetMapping $rsm The ResultSetMapping to use. * @return NativeQuery */ public function createNativeQuery($sql, \Doctrine\ORM\Query\ResultSetMapping $rsm) { return $this->delegate->createNativeQuery($sql, $rsm); } /** * Creates a Query from a named query. * * @param string $name * @return \Doctrine\ORM\Query */ public function createNamedQuery($name) { return $this->delegate->createNamedQuery($name); } /** * Creates a NativeQuery from a named native query. * * @param string $name * @return \Doctrine\ORM\NativeQuery */ public function createNamedNativeQuery($name) { return $this->delegate->createNamedNativeQuery($name); } /** * Creates a copy of the given entity. Can create a shallow or a deep copy. * * @param object $entity The entity to copy. * @return object The new entity. * @todo Implementation need. This is necessary since $e2 = clone $e1; throws an E_FATAL when access anything on $e: * Fatal error: Maximum function nesting level of '100' reached, aborting! */ public function copy($entity, $deep = false) { return $this->delegate->copy($entity, $deep); } /** * Determines whether an entity instance is managed in this EntityManager. * * @param object $entity * @return boolean TRUE if this EntityManager currently manages the given entity, FALSE otherwise. */ public function contains($entity) { return $this->delegate->contains($entity); } /** * Commits a transaction on the underlying database connection. */ public function commit() { return $this->delegate->commit(); } /** * Closes the EntityManager. All entities that are currently managed * by this EntityManager become detached. The EntityManager may no longer * be used after it is closed. */ public function close() { return $this->delegate->close(); } /** * Clears the EntityManager. All entities that are currently managed * by this EntityManager become detached. * * @param string $entityName if given, only entities of this type will get detached */ public function clear($entityName = NULL) { return $this->delegate->clear($entityName); } /** * Starts a transaction on the underlying database connection. */ public function beginTransaction() { return $this->delegate->beginTransaction(); } public function __construct($objectManager, \Symfony\Component\DependencyInjection\ContainerInterface $container) { $this->delegate = $objectManager; $this->container = $container; } private function prepareArguments(array $arguments) { $processed = array(); foreach ($arguments as $arg) { if ($arg instanceof \Symfony\Component\DependencyInjection\Reference) { $processed[] = $this->container->get((string) $arg, $arg->getInvalidBehavior()); } else if ($arg instanceof \Symfony\Component\DependencyInjection\Parameter) { $processed[] = $this->container->getParameter((string) $arg); } else { $processed[] = $arg; } } return $processed; } }
ultimo/tr
app/cache/dev/jms_diextra/doctrine/EntityManager_50f974421cab3.php
PHP
mit
16,022
module.exports = function(grunt) { "use strict"; require("matchdep").filterDev("grunt-*").forEach(grunt.loadNpmTasks); grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), bannercss: "/*! =============================================================\n" + " * Maricopa Association of Governments\n" + " * CSS files for MAG Development Review Map Viewer\n" + " * @concat.min.css | @version | <%= pkg.version %>\n" + " * Production | <%= pkg.date %>\n" + " * http://ims.azmag.gov/\n" + " * MAG Development Review Viewer\n" + " * ===============================================================\n" + " * @Copyright <%= pkg.copyright %> MAG\n" + " * @License MIT\n" + " * ===============================================================\n" + " */\n", bannerjs: '/*!\n' + '*@main.min.js\n' + '*@JavaScript document for Development Review Map Viewer @ MAG\n' + '*@For Production\n' + '*@<%= pkg.name %> - v<%= pkg.version %> | <%= grunt.template.today("mm-dd-yyyy") %>\n' + '*@author <%= pkg.author %>\n' + '*/\n', htmlhint: { build: { options: { "tag-pair": true, // Force tags to have a closing pair "tagname-lowercase": true, // Force tags to be lowercase "attr-lowercase": true, // Force attribute names to be lowercase e.g. <div id="header"> is invalid "attr-value-double-quotes": true, // Force attributes to have double quotes rather than single "doctype-first": true, // Force the DOCTYPE declaration to come first in the document "spec-char-escape": true, // Force special characters to be escaped "id-unique": true, // Prevent using the same ID multiple times in a document // "head-script-disabled": false, // Prevent script tags being loaded in the head for performance reasons "style-disabled": true // Prevent style tags. CSS should be loaded through }, src: ["src/index.html", "src/view/*.html"] } }, // CSSLint. Tests CSS code quality // https://github.com/gruntjs/grunt-contrib-csslint csslint: { // define the files to lint files: ["src/css/main.css"], strict: { options: { "import": 0, "empty-rules": 0, "display-property-grouping": 0, "shorthand": 0, "font-sizes": 0, "zero-units": 0, "important": 0, "duplicate-properties": 0, } } }, jshint: { files: ["src/js/main.js", "src/js/config.js", "src/js/plugins.js"], options: { // strict: true, sub: true, quotmark: "double", trailing: true, curly: true, eqeqeq: true, unused: true, scripturl: true, // This option defines globals exposed by the Dojo Toolkit. dojo: true, // This option defines globals exposed by the jQuery JavaScript library. jquery: true, // Set force to true to report JSHint errors but not fail the task. force: true, reporter: require("jshint-stylish-ex") } }, uglify: { options: { // add banner to top of output file banner: '<%= bannerjs %>\n' }, build: { files: { "dist/js/main.min.js": ["src/js/main.js"], "dist/js/vendor/bootstrapmap.min.js": ["src/js/vendor/bootstrapmap.js"] } } }, cssmin: { add_banner: { options: { // add banner to top of output file banner: '/* <%= pkg.name %> - v<%= pkg.version %> | <%= grunt.template.today("mm-dd-yyyy") %> */' }, files: { "dist/css/main.min.css": ["src/css/main.css"], "dist/css/normalize.min.css": ["src/css/normalize.css"], "dist/css/bootstrapmap.min.css": ["src/css/bootstrapmap.css"] } } }, concat: { options: { stripBanners: true, banner: '<%= bannercss %>\n' }, dist: { src: ["dist/css/normalize.min.css", "dist/css/bootstrapmap.min.css", "dist/css/main.min.css"], dest: 'dist/css/concat.min.css' } }, clean: { build: { src: ["dist/"] } }, copy: { build: { cwd: "src/", src: ["**"], dest: "dist/", expand: true } }, watch: { html: { files: ["index.html"], tasks: ["htmlhint"] }, css: { files: ["css/main.css"], tasks: ["csslint"] }, js: { files: ["js/mainmap.js", "Gruntfile.js", "js/config.js"], tasks: ["jshint"] } }, versioncheck: { options: { skip: ["semver", "npm", "lodash"], hideUpToDate: false } }, replace: { update_Meta: { src: ["src/index.html", "src/js/config.js", "src/humans.txt", "README.md"], // source files array // src: ["README.md"], // source files array overwrite: true, // overwrite matched source files replacements: [{ // html pages from: /(<meta name="revision-date" content=")[0-9]{2}\/[0-9]{2}\/[0-9]{4}(">)/g, to: '<meta name="revision-date" content="' + '<%= pkg.date %>' + '">', }, { // html pages from: /(<meta name="version" content=")([0-9]+)(?:\.([0-9]+))(?:\.([0-9]+))(">)/g, to: '<meta name="version" content="' + '<%= pkg.version %>' + '">', }, { // config.js from: /(v)([0-9]+)(?:\.([0-9]+))(?:\.([0-9]+))( \| )[0-9]{2}\/[0-9]{2}\/[0-9]{4}/g, to: 'v' + '<%= pkg.version %>' + ' | ' + '<%= pkg.date %>', }, { // humans.txt from: /(Version\: v)([0-9]+)(?:\.([0-9]+))(?:\.([0-9]+))/g, to: "Version: v" + '<%= pkg.version %>', }, { // humans.txt from: /(Last updated\: )[0-9]{2}\/[0-9]{2}\/[0-9]{4}/g, to: "Last updated: " + '<%= pkg.date %>', }, { // README.md from: /(#### version )([0-9]+)(?:\.([0-9]+))(?:\.([0-9]+))/g, to: "#### version " + '<%= pkg.version %>', }, { // README.md from: /(`Updated: )[0-9]{2}\/[0-9]{2}\/[0-9]{4}/g, to: "`Updated: " + '<%= pkg.date %>', }] } } }); // this would be run by typing "grunt test" on the command line grunt.registerTask("work", ["jshint"]); grunt.registerTask("workHTML", ["htmlhint"]); grunt.registerTask("buildcss", ["cssmin", "concat"]); grunt.registerTask("buildjs", ["uglify"]); grunt.registerTask("build-test", ["clean", "copy"]); grunt.registerTask("build", ["clean", "replace", "copy", "uglify", "cssmin", "concat"]); // the default task can be run just by typing "grunt" on the command line grunt.registerTask("default", []); }; // ref // http://coding.smashingmagazine.com/2013/10/29/get-up-running-grunt/ // http://csslint.net/about.html // http://www.jshint.com/docs/options/ // test test test test test test test
AZMAG/map-Developments
Gruntfile.js
JavaScript
mit
8,849
import {Reducer} from "redux"; import {ActionType, getType} from "typesafe-actions"; import * as Actions from './actions'; import ld_filter from 'lodash/filter'; import ld_find from 'lodash/find'; import {PanelPermission, RoleClearance} from "./types"; export interface PermissionReducerState { panelPermissions: PanelPermission[] roleClearances: RoleClearance[] } const defaultState: PermissionReducerState = { panelPermissions: [], roleClearances: [] }; type PermissionAction = ActionType<typeof Actions> const reducer: Reducer<PermissionReducerState, PermissionAction> = (state = defaultState, action) => { switch (action.type) { case getType(Actions.getPanelPermissionsOk): return { ...state, panelPermissions: action.payload }; case getType(Actions.createPanelPermissionOk): return { ...state, panelPermissions: [...state.panelPermissions, action.payload] }; case getType(Actions.deletePanelPermission): return { ...state, panelPermissions: ld_filter(state.panelPermissions, perm => perm.id != action.payload) }; case getType(Actions.modifyPanelPermission): let permissions = [...state.panelPermissions]; let target = ld_find(permissions, {id: action.payload.id}); if (target) { target.permission = action.payload.permission } return { ...state, panelPermissions: permissions }; case getType(Actions.getRoleClearanceOk): return { ...state, roleClearances: action.payload }; case getType(Actions.deleteRoleClearance): return { ...state, roleClearances: ld_filter(state.roleClearances, clearance => clearance.id != action.payload) }; case getType(Actions.modifyRoleClearance): let clearances = [...state.roleClearances]; let targetRole = ld_find(clearances, {id: action.payload.id}); if (targetRole) { targetRole.permission_level = action.payload.clearance; } return { ...state, roleClearances: clearances }; case getType(Actions.createRoleClearanceOk): return { ...state, roleClearances: [...state.roleClearances, action.payload] }; default: return state } }; export default reducer
mrkirby153/KirBotPanel
resources/assets/js/components/dashboard/permissions/reducer.ts
TypeScript
mit
2,674
/** * Created by ndyumin on 29.05.2015. * @exports UIModule */ define(function(require) { require('./styles/field.less'); var Wreqr = require('backbone.wreqr'); var globalBus = Wreqr.radio.channel('global'); var UIController = require('./UIController'); return function(app) { var controller = new UIController(app); globalBus.vent.on('newgame', controller.init, controller); } });
nikitadyumin/tetris
src/app/game_ui/UIModule.js
JavaScript
mit
427
<?php /** * @package framework * @subpackage control */ class RequestProcessor { private $filters = array(); public function __construct($filters = array()) { $this->filters = $filters; } public function setFilters($filters) { $this->filters = $filters; } public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model) { foreach ($this->filters as $filter) { $res = $filter->preRequest($request, $session, $model); if ($res === false) { return false; } } } /** * Filter executed AFTER a request */ public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model) { foreach ($this->filters as $filter) { $res = $filter->postRequest($request, $response, $model); if ($res === false) { return false; } } } }
harrymule/nairobi-webportal
framework/control/RequestProcessor.php
PHP
mit
823
package com.witchworks.common.brew; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import javax.annotation.Nullable; /** * This class was created by Arekkuusu on 11/06/2017. * It's distributed as part of Witchworks under * the MIT license. */ public class GrassGrowBrew extends BlockHitBrew { @Override public int getColor() { return 0x4CBB17; } @Override public String getName() { return "growth"; } @Override public void safeImpact(BlockPos pos, @Nullable EnumFacing side, World world, int amplifier) { int box = 1 + (int) ((float) amplifier / 2F); BlockPos posI = pos.add(box, box, box); BlockPos posF = pos.add(-box, -box, -box); Iterable<BlockPos> spots = BlockPos.getAllInBox(posI, posF); for (BlockPos spot : spots) { IBlockState state = world.getBlockState(spot); boolean place = amplifier > 2 || world.rand.nextBoolean(); if (place && state.getBlock() == Blocks.MYCELIUM && world.isAirBlock(spot.up())) { world.setBlockState(spot, Blocks.GRASS.getDefaultState(), 3); } else if (state.getBlock() == Blocks.DIRT) { world.setBlockState(spot, Blocks.GRASS.getDefaultState(), 3); } } } }
backuporg/Witchworks
src/main/java/com/witchworks/common/brew/GrassGrowBrew.java
Java
mit
1,298
from setuptools import setup from os.path import join as join_path from os import walk def files_in(package, directory): paths = [] for root, dirs, files in walk(join_path(package, directory)): for file in files: paths.append(join_path(root, file)[(len(package) + 1):]) return paths additional_files = [] additional_files.extend(files_in('datdash', 'skeleton')) additional_files.extend(files_in('datdash', 'javascript')) setup( name='DatDash', version='0.1alpha', packages=['datdash'], package_data={'datdash': additional_files}, license='MIT', long_description=open('README.md').read(), scripts=['bin/datdash'], install_requires=[ 'Flask', 'CoffeeScript', 'requests', 'pyScss', 'docopt', 'pyScss', ] )
LuRsT/datdash
setup.py
Python
mit
825
module MickTagger class FileStore attr_reader :content def initialize(content) @content = content end def files_for(tag) @content.select {|file, tags| tags.include?(tag) }.keys end def add_tag_to(file, tag) @content[file] ||= [] @content[file] << tag @content[file].uniq! end def remove_tag_from(file, tag) @content[file].delete(tag) @content.delete(file) if @content[file].empty? end def remove_deleted_files! @content.keys.inject([]) do |deleted_files, file| unless File.exists?(file) @content.delete(file) deleted_files << file end deleted_files end end end end
mrnugget/micktagger
lib/micktagger/file_store.rb
Ruby
mit
716
import json import os from collections import OrderedDict from difflib import unified_diff import pytest from dash.development._py_components_generation import generate_class from dash.development.component_generator import reserved_words from . import _dir, expected_table_component_doc @pytest.fixture def component_class(load_test_metadata_json): return generate_class( typename="Table", props=load_test_metadata_json["props"], description=load_test_metadata_json["description"], namespace="TableComponents", ) @pytest.fixture def component_written_class(): path = os.path.join(_dir, "metadata_required_test.json") with open(path) as data_file: json_string = data_file.read() required_data = json.JSONDecoder(object_pairs_hook=OrderedDict).decode( json_string ) return generate_class( typename="TableRequired", props=required_data["props"], description=required_data["description"], namespace="TableComponents", ) def test_to_plotly_json(component_class): c = component_class() assert c.to_plotly_json() == { "namespace": "TableComponents", "type": "Table", "props": {"children": None}, } c = component_class(id="my-id") assert c.to_plotly_json() == { "namespace": "TableComponents", "type": "Table", "props": {"children": None, "id": "my-id"}, } c = component_class(id="my-id", optionalArray=None) assert c.to_plotly_json() == { "namespace": "TableComponents", "type": "Table", "props": {"children": None, "id": "my-id", "optionalArray": None}, } def test_arguments_become_attributes(component_class): kwargs = {"id": "my-id", "children": "text children", "optionalArray": [[1, 2, 3]]} component_instance = component_class(**kwargs) for k, v in list(kwargs.items()): assert getattr(component_instance, k) == v def test_repr_single_default_argument(component_class): c1 = component_class("text children") c2 = component_class(children="text children") assert repr(c1) == "Table('text children')" assert repr(c2) == "Table('text children')" def test_repr_single_non_default_argument(component_class): c = component_class(id="my-id") assert repr(c) == "Table(id='my-id')" def test_repr_multiple_arguments(component_class): # Note how the order in which keyword arguments are supplied is # not always equal to the order in the repr of the component c = component_class(id="my id", optionalArray=[1, 2, 3]) assert repr(c) == "Table(id='my id', optionalArray=[1, 2, 3])" def test_repr_nested_arguments(component_class): c1 = component_class(id="1") c2 = component_class(id="2", children=c1) c3 = component_class(children=c2) assert repr(c3) == "Table(Table(children=Table(id='1'), id='2'))" def test_repr_with_wildcards(component_class): c = component_class(id="1", **{"data-one": "one", "aria-two": "two"}) data_first = "Table(id='1', data-one='one', aria-two='two')" aria_first = "Table(id='1', aria-two='two', data-one='one')" repr_string = repr(c) assert repr_string == data_first or repr_string == aria_first def test_docstring(component_class): assert not list( unified_diff(expected_table_component_doc, component_class.__doc__.splitlines()) ) def test_no_events(component_class): assert not hasattr(component_class, "available_events") def test_required_props(component_written_class): with pytest.raises(Exception): component_written_class() component_written_class(id="test") with pytest.raises(Exception): component_written_class(id="test", lahlah="test") with pytest.raises(Exception): component_written_class(children="test") def test_attrs_match_forbidden_props(component_class): assert "_.*" in reserved_words, "props cannot have leading underscores" # props are not added as attrs unless explicitly provided # except for children, which is always set if it's a prop at all. expected_attrs = set(reserved_words + ["children"]) - {"_.*"} c = component_class() base_attrs = set(dir(c)) extra_attrs = set(a for a in base_attrs if a[0] != "_") assert ( extra_attrs == expected_attrs ), "component has only underscored and reserved word attrs" # setting props causes them to show up as attrs c2 = component_class("children", id="c2", optionalArray=[1]) prop_attrs = set(dir(c2)) assert base_attrs - prop_attrs == set([]), "no attrs were removed" assert prop_attrs - base_attrs == { "id", "optionalArray", }, "explicit props were added as attrs"
plotly/dash
tests/unit/development/test_generate_class.py
Python
mit
4,761
require('../../stylus/components/_dialogs.styl') // Mixins import Dependent from '../../mixins/dependent' import Detachable from '../../mixins/detachable' import Overlayable from '../../mixins/overlayable' import Stackable from '../../mixins/stackable' import Toggleable from '../../mixins/toggleable' // Directives import ClickOutside from '../../directives/click-outside' // Helpers import { getZIndex } from '../../util/helpers' export default { name: 'v-dialog', mixins: [Dependent, Detachable, Overlayable, Stackable, Toggleable], directives: { ClickOutside }, data () { return { isDependent: false, stackClass: 'dialog__content__active', stackMinZIndex: 200 } }, props: { disabled: Boolean, persistent: Boolean, fullscreen: Boolean, fullWidth: Boolean, maxWidth: { type: [String, Number], default: 'none' }, origin: { type: String, default: 'center center' }, width: { type: [String, Number], default: 'auto' }, scrollable: Boolean, transition: { type: [String, Boolean], default: 'dialog-transition' } }, computed: { classes () { return { [(`dialog ${this.contentClass}`).trim()]: true, 'dialog--active': this.isActive, 'dialog--persistent': this.persistent, 'dialog--fullscreen': this.fullscreen, 'dialog--stacked-actions': this.stackedActions && !this.fullscreen, 'dialog--scrollable': this.scrollable } }, contentClasses () { return { 'dialog__content': true, 'dialog__content__active': this.isActive } } }, watch: { isActive (val) { if (val) { this.show() } else { this.removeOverlay() this.unbind() } } }, mounted () { this.isBooted = this.isActive this.isActive && this.show() }, beforeDestroy () { if (typeof window !== 'undefined') this.unbind() }, methods: { closeConditional (e) { // close dialog if !persistent, clicked outside and we're the topmost dialog. // Since this should only be called in a capture event (bottom up), we shouldn't need to stop propagation return !this.persistent && getZIndex(this.$refs.content) >= this.getMaxZIndex() && !this.$refs.content.contains(e.target) }, show () { !this.fullscreen && !this.hideOverlay && this.genOverlay() this.fullscreen && this.hideScroll() this.$refs.content.focus() this.$listeners.keydown && this.bind() }, bind () { window.addEventListener('keydown', this.onKeydown) }, unbind () { window.removeEventListener('keydown', this.onKeydown) }, onKeydown (e) { this.$emit('keydown', e) } }, render (h) { const children = [] const data = { 'class': this.classes, ref: 'dialog', directives: [ { name: 'click-outside', value: { callback: this.closeConditional, include: this.getOpenDependentElements } }, { name: 'show', value: this.isActive } ], on: { click: e => e.stopPropagation() } } if (!this.fullscreen) { data.style = { maxWidth: this.maxWidth === 'none' ? undefined : (isNaN(this.maxWidth) ? this.maxWidth : `${this.maxWidth}px`), width: this.width === 'auto' ? undefined : (isNaN(this.width) ? this.width : `${this.width}px`) } } if (this.$slots.activator) { children.push(h('div', { 'class': 'dialog__activator', on: { click: e => { if (!this.disabled) this.isActive = !this.isActive } } }, [this.$slots.activator])) } const dialog = h('transition', { props: { name: this.transition || '', // If false, show nothing origin: this.origin } }, [h('div', data, this.showLazyContent(this.$slots.default) )]) children.push(h('div', { 'class': this.contentClasses, domProps: { tabIndex: -1 }, style: { zIndex: this.activeZIndex }, ref: 'content' }, [dialog])) return h('div', { 'class': 'dialog__container', style: { display: !this.$slots.activator && 'none' || this.fullWidth ? 'block' : 'inline-block' } }, children) } }
azaars/vuetify
src/components/VDialog/VDialog.js
JavaScript
mit
4,409
package service import ( "net/http" "github.com/codegangsta/negroni" "github.com/gorilla/mux" "github.com/unrolled/render" ) func NewServer() *negroni.Negroni { formatter := render.New(render.Options{ IndentJSON:true, }) n := negroni.Classic() mx := mux.NewRouter() initRoutes(mx, formatter) n.UseHandler(mx) return n } func initRoutes(mx *mux.Router, formatter *render.Render) { mx.HandleFunc("/test", testHandler(formatter)).Methods("GET") } func testHandler(formatter *render.Render) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { formatter.JSON(w, http.StatusOK, struct{Test string}{"This is a test"}) } }
mmsikora/gogo-service
service/service.go
GO
mit
691
using UnityEngine; using System.Collections; using System; using Epm3d; /// <summary> /// Manages a single PO. Calls GameManager to update PO approval status, waits for response. /// Listens to highlight events, does other highlight stuff like PO display (via script PoGui), halting /// movement, everything not related to the highlight visual change on the object (which is done by /// Highlight_IsHighlightable). /// </summary> [RequireComponent (typeof (PoGui))] public class PoManager : MonoBehaviour { public GameObject PoToDisplayWhenDead; public GameObject RocketAttachedWhenApproved; /// <summary> /// PO with Items business data. /// </summary> public EpmPoDataWithItems PoBusinessDataWithItems; /// <summary> /// PO gameplay behaviour data (eg movement type) /// NB This is assigned values in code, not from inspector, it is left in inspector to help debugging /// </summary> public EpmPoBehaviour PoBehaviour; /// <summary> /// Occurs when on this PO approved, when we've heard genuine positive response from gamemanager. /// </summary> public event EventHandler<EventArgs> OnThisPOApproved = delegate {}; /// <summary> /// Occurs when on this PO rejected, when we've heard genuine positive response from gamemanager. /// </summary> public event EventHandler<EventArgs> OnThisPORejected = delegate {}; // refs to others components and scripts on the same game object private Highlight_IsHighlightable _scriptIsHighlightable; private PoMover _poMover; /// <summary> /// The _po GUI, set to active when PO highlighted /// </summary> private PoGui _poGui; private GameGui _gameGui; private enum PoManagerState { Normal, BusyRequestingApproved, BusyChangingStateApproved, BusyRequestingRejected, BusyChangingStateRejected } /// <summary> /// State machine for this PO manager /// Used eg to ensure PO cannot be fiddled with whilst it is being approved or rejected (ie whilst effects are happening) /// </summary> private PoManagerState _poManagerState; private float _shakingTimeLeft; void Start() { _poManagerState = PoManagerState.Normal; _shakingTimeLeft = PoBehaviour.PreRocketWarmUpTime; // Listen to global approve reject events, which we'll filter to make sure it's only the // one that applies to this PO GameManager.Instance.OnSinglePOApproved += OnSinglePOApproved; GameManager.Instance.OnSinglePORejected += OnSinglePORejected; // Highlighting - start stop movement when highlighted _scriptIsHighlightable = GetComponent<Highlight_IsHighlightable>(); if (_scriptIsHighlightable != null) { _scriptIsHighlightable.OnHighlighted += OnHighlighted; _scriptIsHighlightable.OnUnhighlighted += OnUnhighlighted; } // Po GUI to display PO details _poGui = GetComponent<PoGui>(); _poGui.enabled = false; // always start switched off // Game Gui, to tell it when we approve/reject GameObject go = GameObject.Find("GameGui"); if (go != null) { _gameGui = go.GetComponent<GameGui>(); } // Movement - get reference _poMover = GetComponent<PoMover>(); // Delete mover for static POs if (_poMover != null && PoBehaviour.movementType == EpmPoMovementType.Static) { Component.Destroy(_poMover); } } private void OnSinglePOApproved(object sender, PoApprovedEventArgs e) { if (e.PurchaseOrderId == this.PoBusinessDataWithItems.PurchaseOrderId) { // It's us! Changing this state triggers the shaking effect, which itself is applied in FixedUpdate() _poManagerState = PoManagerState.BusyChangingStateApproved; // Visuals and audio for the immediate act of approval are done in PoSfx, which listens to this event OnThisPOApproved(null, null); // Stop any other movement if (_poMover != null) { Component.Destroy(_poMover); } // Set rocket attachment Invoke("AttachRocket", PoBehaviour.PreRocketWarmUpTime); Invoke("UpdateApprovedPoScore", 4); // Self destruct // TODO add a destructor if object outside game world box Destroy(this.gameObject, 10f); } } private void AttachRocket() { // allow po to rocket through any obstacles GetComponent<Collider>().enabled = false; // Attach rocket gameobject to this game object // Visuals and audio of the rocket are done in this new gameobject RocketAttachedWhenApproved GameObject gParent = this.gameObject; Vector3 spawnPosition = this.transform.position; Quaternion spawnRotation = this.transform.rotation; GameObject g = (GameObject)Instantiate(RocketAttachedWhenApproved, spawnPosition, spawnRotation); g.transform.parent = gParent.transform; } private void OnSinglePORejected(object sender, PoApprovedEventArgs e) { if (e.PurchaseOrderId == this.PoBusinessDataWithItems.PurchaseOrderId) { // It's us! _poManagerState = PoManagerState.BusyChangingStateRejected; // Visuals and audio are done in PoSfx, which listens to this event OnThisPORejected(null, null); // Hide self GetComponent<Renderer>().enabled = false; GetComponent<Collider>().enabled = false; // Self destruct Destroy(this.gameObject, 5f); // delay needed to allow audio and explosion particles to finish // Create smoke gameobject as separate gameobject in the PO bucket folder // This gameobject PoToDisplayWhenDead prefab could have some models too GameObject gParent = GameObject.FindWithTag("PoBucket"); Vector3 spawnPosition = this.transform.position; Quaternion spawnRotation = this.transform.rotation; GameObject g = (GameObject)Instantiate(PoToDisplayWhenDead, spawnPosition, spawnRotation); g.transform.parent = gParent.transform; // Tell Gui if (_gameGui != null) { _gameGui.PoRejected(); } } } private void UpdateApprovedPoScore() { // Tell Gui if (_gameGui != null) { _gameGui.PoApproved(); } } private void OnHighlighted(object sender, EventArgs e) { if (_poMover != null) { _poMover.enabled = false; } // po gui script is a required cpt, dont need to check existence _poGui.enabled = true; } private void OnUnhighlighted(object sender, EventArgs e) { if (_poMover != null) { _poMover.enabled = true; } // po gui script is a required cpt, dont need to check existence _poGui.enabled = false; } // Update is called once per frame void Update() { switch (_poManagerState) { case PoManagerState.Normal: if (_poGui.enabled) { if (Input.GetButtonUp("Approve")) { GameManager.Instance.GetEpmData_ApprovePO(PoBusinessDataWithItems.PurchaseOrderId); _poManagerState = PoManagerState.BusyRequestingApproved; } if (Input.GetButtonUp("Reject")) { GameManager.Instance.GetEpmData_RejectPO(PoBusinessDataWithItems.PurchaseOrderId); _poManagerState = PoManagerState.BusyRequestingRejected; } } break; default: break; } } void FixedUpdate() { switch (_poManagerState) { case PoManagerState.BusyChangingStateApproved: _shakingTimeLeft -= Time.deltaTime; if(_shakingTimeLeft > 0f) { // shaking effect float mag = UnityEngine.Random.Range(10f, 15f); //Vector3 dir = UnityEngine.Random.onUnitSphere; Vector2 circ = UnityEngine.Random.insideUnitCircle; Vector3 diralt = new Vector3(circ.x, 0.05f, circ.y); //rigidbody.AddForce(dir * mag); //rigidbody.AddRelativeTorque(diralt * mag); GetComponent<Rigidbody>().AddTorque(diralt * mag); } break; default: break; } } }
KevinSmall/HanaShine3d
Epm3d/Assets/_Scripts/Po/PoManager.cs
C#
mit
8,495
# ============================================================================== # Copyright 2019 - Philip Paquette # # NOTICE: Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # ============================================================================== """ Policy model (Order Based) - Contains the parent policy model, to evaluate the best actions given a state """ from collections import OrderedDict import logging import math from diplomacy_research.models.policy.base_policy_model import GREEDY_DECODER, TRAINING_DECODER, StatsKey, \ OrderProbTokenLogProbs, BasePolicyModel, load_args as load_parent_args from diplomacy_research.models.state_space import ix_to_order, get_order_tokens, EOS_ID, EOS_TOKEN, PAD_TOKEN, \ POWER_VOCABULARY_IX_TO_KEY, POWER_VOCABULARY_LIST, NB_SUPPLY_CENTERS, STANDARD_TOPO_LOCS, TOKENS_PER_ORDER # Constants LOGGER = logging.getLogger(__name__) def load_args(): """ Load possible arguments :return: A list of tuple (arg_type, arg_name, arg_value, arg_desc) """ return load_parent_args() class OrderBasedPolicyModel(BasePolicyModel): """ Policy Model """ def __init__(self, dataset, hparams): """ Initialization :param dataset: The dataset that is used to iterate over the data. :param hparams: A dictionary of hyper parameters with their values :type dataset: diplomacy_research.models.datasets.supervised_dataset.SupervisedDataset :type dataset: diplomacy_research.models.datasets.queue_dataset.QueueDataset """ from diplomacy_research.utils.tensorflow import tf hps = lambda hparam_name: self.hparams[hparam_name] BasePolicyModel.__init__(self, dataset, hparams) # Learning rate if not hasattr(self, 'learning_rate') or self.learning_rate is None: with tf.device(self.cluster_config.worker_device if self.cluster_config else None): self.learning_rate = tf.Variable(float(hps('learning_rate')), trainable=False, dtype=tf.float32) # Optimizer if not hasattr(self, 'optimizer') or self.optimizer is None: self.optimizer = self.make_optimizer(self.learning_rate) # Build ops self.build_policy() # Decay ops if not hasattr(self, 'decay_learning_rate') or self.decay_learning_rate is None: self.decay_learning_rate = self.learning_rate.assign(self.placeholders['learning_rate']) @property def _nb_evaluation_loops(self): """ Contains the number of different evaluation tags we want to compute This also represent the number of loops we should do over the validation set Some model wants to calculate different statistics and require multiple pass to do that A value of 1 indicates to only run in the main validation loop A value > 1 indicates to run additional loops only for this model. """ return 2 @property def _evaluation_tags(self): """ List of evaluation tags (1 list of evaluation tag for each evaluation loop) e.g. [['Acc_1', 'Acc_5', 'Acc_Tokens'], ['Gr_1', 'Gr_5', 'Gr_Tokens']] """ return [['[TF]X-Ent', '[TF]Perplexity', '[TF]Acc_1', '[TF]Acc_1_NoHold', '[TF]Acc_Tokens', '[TF]Acc_Player'], ['[Gr]Acc_1', '[Gr]Acc_1_NoHold', '[Gr]Acc_Tokens', '[Gr]Acc_Player']] @property def _early_stopping_tags(self): """ List of tags to use to detect early stopping The tags are a tuple of 1) 'min' or 'max' and 2) the tag's name e.g. [('max', '[Gr]Acc_1'), ('min', '[TF]Perplexity')] """ return [('min', '[TF]Perplexity'), ('max', '[Gr]Acc_1')] @property def _placeholders(self): """ Return a dictionary of all placeholders needed by the model """ from diplomacy_research.utils.tensorflow import tf, get_placeholder, get_placeholder_with_default # Note: 'decoder_type' needs to have a batch_dim to be compatible with TF Serving # but will be reduced to a scalar with tf.reduce_max return { 'decoder_type': get_placeholder('decoder_type', shape=[None], dtype=tf.uint8), 'learning_rate': get_placeholder_with_default('learning_rate', 1e-4, shape=(), dtype=tf.float32), 'dropout_rate': get_placeholder_with_default('dropout_rate', 0., shape=(), dtype=tf.float32), 'is_training': get_placeholder_with_default('is_training', False, shape=(), dtype=tf.bool), 'stop_gradient_all': get_placeholder_with_default('stop_gradient_all', False, shape=(), dtype=tf.bool) } def _build_policy_initial(self): """ Builds the policy model (initial step) """ raise NotImplementedError() @staticmethod def _get_optimizer(learning_rate): """ Returns the optimizer to use for this model """ from diplomacy_research.utils.tensorflow import tf LOGGER.info('Using tf.contrib.opt.LazyAdamOptimizer as the optimizer.') return tf.contrib.opt.LazyAdamOptimizer(learning_rate=learning_rate) def _get_session_args(self, decode=False, eval_loop_ix=None): """ Returns a dict of kwargs to feed to session.run Expected format: {fetches, feed_dict=None} """ hps = lambda hparam_name: self.hparams[hparam_name] # Detecting if we are doing validation in_validation, our_validation = False, False if eval_loop_ix is not None: in_validation = True our_validation = eval_loop_ix in self.my_eval_loop_ixs # --------- Fetches --------------- train_fetches = {'optimizer_op': self.outputs['optimizer_op'], 'policy_loss': self.outputs['policy_loss']} eval_fetches = {'policy_loss': self.outputs['policy_loss'], 'argmax_tokens': self.outputs['argmax_tokens'], 'log_probs': self.outputs['log_probs'], 'targets': self.outputs['targets'], 'current_power': self.features['current_power'], 'current_season': self.features['current_season'], 'in_retreat_phase': self.outputs['in_retreat_phase'], 'request_id': self.features['request_id']} # --------- Feed dict -------------- # Building feed dict feed_dict = {self.placeholders['decoder_type']: [TRAINING_DECODER], # Batch size of 1 self.placeholders['is_training']: True, self.placeholders['stop_gradient_all']: False} # Dropout disabled during debug (batch), validation, or decoding (stats) if self.hparams['debug_batch'] or in_validation or decode: feed_dict.update({self.placeholders['dropout_rate']: 0.}) else: feed_dict.update({self.placeholders['dropout_rate']: hps('dropout_rate')}) # --------- Validation Loop -------------- # Validation Loop - Running one of our validation loops if our_validation: decoder_type = {0: TRAINING_DECODER, 1: GREEDY_DECODER}[self.my_eval_loop_ixs.index(eval_loop_ix)] feed_dict[self.placeholders['decoder_type']] = [decoder_type] # Batch size of 1 feed_dict[self.placeholders['is_training']] = False return {'fetches': eval_fetches, 'feed_dict': feed_dict} # Validation Loop - Running someone else validation loop if in_validation: return {'feed_dict': feed_dict} # --------- Training Loop -------------- # Training Loop - We want to decode the specific batch to display stats if decode: decoder_type = TRAINING_DECODER feed_dict[self.placeholders['decoder_type']] = [decoder_type] # Batch size of 1 feed_dict[self.placeholders['is_training']] = False return {'fetches': eval_fetches, 'feed_dict': feed_dict} # Training Loop - Training the model return {'fetches': train_fetches, 'feed_dict': feed_dict} @staticmethod def _decode(**fetches): """ Performs decoding on the output (order_based model) :param fetches: A dictionary of fetches from the model. Keys can include: - selected_tokens / argmax_tokens: [Required] The tokens from the model (Tensor [batch, decoder_length]) - log_probs: [Required] The log probs from the model (Tensor [batch, decoder_length]) - policy_loss: The policy loss for the batch. - targets: The targets from the model (Tensor [batch, length]). Required for evaluation. - current_power: The current_power from the model (Tensor [batch,]). Required for evaluation. - current_season: The current_season from the model (Tensor [batch,]). Required for evaluation. - in_retreat_phase: Boolean that indicates dislodged units are on the map. ([b,]). Required for evaluation. - request_id: The unique request id for each item in the batch. :return: A dictionary of decoded results, including - 1) decoded_orders: A list of dictionary (one per batch) where each dict has location as key and a OrderProbTokenLogProbs tuple as value (i.e. an order, its prob, and the token log probs) e.g. [{'PAR': (order, prob, log_probs),'MAR': (order, prob, log_probs)}, {'PAR': (order, prob, log_probs),'MAR': (order, prob, log_probs)}] - 2) various other keys for evaluation """ # Missing the required fetches, returning an empty decoded results if ('selected_tokens' not in fetches and 'argmax_tokens' not in fetches) or 'log_probs' not in fetches: return {} # tokens: [batch, dec_len] # log_probs: [batch, dec_len] # policy_loss: () # targets: [batch, dec_len] # current_power: [batch] # current_season: [batch] # in_retreat_phase: [batch] # request_ids: [batch] tokens = fetches.get('selected_tokens', fetches.get('argmax_tokens')) log_probs = fetches['log_probs'] policy_loss = fetches.get('policy_loss', None) targets = fetches.get('targets', None) current_power = fetches.get('current_power', None) current_season = fetches.get('current_season', None) in_retreat_phase = fetches.get('in_retreat_phase', None) request_ids = fetches.get('request_id', None) # Decoding orders results = [] result_tokens = [] nb_batches = tokens.shape[0] for batch_ix in range(nb_batches): batch_results = OrderedDict() batch_results_tokens = OrderedDict() batch_tokens = tokens[batch_ix] batch_log_probs = log_probs[batch_ix] nb_waive = 0 # We didn't try to predict orders - Skipping if not len(batch_tokens) or batch_tokens[0] == [0]: # pylint: disable=len-as-condition results += [batch_results] result_tokens += [batch_results_tokens] continue for token_ix, token in enumerate(batch_tokens): if token <= EOS_ID: continue order = ix_to_order(token) # WAIVE orders if order == 'WAIVE': loc = 'WAIVE_{}'.format(nb_waive) nb_waive += 1 # Use normal location and skip if already stored else: loc = order.split()[1] if loc in batch_results: continue loc = loc[:3] # Storing order batch_results[loc] = OrderProbTokenLogProbs(order=order, probability=1., log_probs=[batch_log_probs[token_ix]]) batch_results_tokens[loc] = [token] # Done with batch results += [batch_results] result_tokens += [batch_results_tokens] # Returning return {'decoded_orders': results, 'policy_loss': policy_loss, 'targets': targets, 'tokens': result_tokens, 'current_power': current_power, 'current_season': current_season, 'in_retreat_phase': in_retreat_phase, 'request_id': request_ids, 'log_probs': log_probs} def _evaluate(self, decoded_results, feed_dict, eval_loop_ix, incl_detailed): """ Calculates the accuracy of the model :param decoded_results: The decoded results (output of _decode() function) :param feed_dict: The feed dictionary that was given to session.run() :param eval_loop_ix: The current evaluation loop index (-1 for training) :param incl_detailed: is true if training is over, more statistics can be computed :return: A tuple consisting of: 1) An ordered dictionary with result_name as key and (weight, value) as value (Regular results) 2) An ordered dictionary with result_name as key and a list of result values (Detailed results) """ # Detecting if it's our evaluation or not if eval_loop_ix == -1: eval_loop_ix = 0 else: our_validation = eval_loop_ix in self.my_eval_loop_ixs if not our_validation: return OrderedDict(), OrderedDict() eval_loop_ix = self.my_eval_loop_ixs.index(eval_loop_ix) # Evaluating policy_loss = decoded_results['policy_loss'] # Avg X-Ent per unit-order perplexity = math.exp(policy_loss) if policy_loss <= 100 else float('inf') targets = decoded_results['targets'] batch_size = targets.shape[0] nb_locs_per_target = targets.shape[1] decoded_orders = decoded_results['decoded_orders'] # Logging an error if perplexity is inf if perplexity == float('inf'): for request_id, log_probs in zip(decoded_results['request_id'], decoded_results['log_probs']): if sum(log_probs) <= -100: LOGGER.error('Request %s has log probs that causes a -inf perplexity.', request_id) # Accuracy acc_1_num, denom = 0., 0. acc_1_no_hold_num, denom_no_hold = 0., 0. nb_tokens_match, nb_tokens_total = 0., 0. acc_player_num, denom_player = 0., 0. # Decoding batch by batch, loc by loc for batch_ix in range(batch_size): player_order_mismatch = False nb_waive = 0 # We didn't learn a policy - Skipping if not len(targets[batch_ix]) or targets[batch_ix][0] == 0: # pylint: disable=len-as-condition continue for loc_ix in range(nb_locs_per_target): decoded_target = targets[batch_ix][loc_ix] decoded_target_order = ix_to_order(decoded_target) if decoded_target > EOS_ID else '' if not decoded_target_order: break nb_tokens_total += TOKENS_PER_ORDER if decoded_target_order == 'WAIVE': loc = 'WAIVE_{}'.format(nb_waive) is_hold_order = False nb_waive += 1 else: loc = decoded_target_order.split()[1][:3] is_hold_order = len(decoded_target_order.split()) <= 2 or decoded_target_order.split()[2] == 'H' # Computing Acc 1 denom += 1. if not is_hold_order: denom_no_hold += 1. # Checking if the target is in the decoded results if loc in decoded_orders[batch_ix] and decoded_orders[batch_ix][loc].order == decoded_target_order: acc_1_num += 1. if not is_hold_order: acc_1_no_hold_num += 1. else: player_order_mismatch = True # Computing Acc Tokens tokenized_targets = get_order_tokens(decoded_target_order) + [EOS_TOKEN] tokenized_targets += [PAD_TOKEN] * (TOKENS_PER_ORDER - len(tokenized_targets)) tokenized_results = [-1] * TOKENS_PER_ORDER if loc in decoded_orders[batch_ix]: tokenized_results = get_order_tokens(decoded_orders[batch_ix][loc].order) + [EOS_TOKEN] tokenized_results += [PAD_TOKEN] * (TOKENS_PER_ORDER - len(tokenized_results)) nb_tokens_match += sum([1. for i in range(TOKENS_PER_ORDER) if tokenized_targets[i] == tokenized_results[i]]) # Compute accuracy for this phase if not player_order_mismatch: acc_player_num += 1 denom_player += 1 # No orders at all if not denom: acc_1 = 1. acc_1_no_hold = 1. acc_tokens = 1. acc_player = 1. else: acc_1 = acc_1_num / (denom + 1e-12) acc_1_no_hold = acc_1_no_hold_num / (denom_no_hold + 1e-12) acc_tokens = nb_tokens_match / (nb_tokens_total + 1e-12) acc_player = acc_player_num / (denom_player + 1e-12) # Computing detailed statistics detailed_results = OrderedDict() if incl_detailed: detailed_results = self._get_detailed_results(decoded_results, feed_dict, eval_loop_ix) # Validating decoder type decoder_type = [value for tensor, value in feed_dict.items() if 'decoder_type' in tensor.name] decoder_type = '' if not decoder_type else decoder_type[0][0] # 0 - Teacher Forcing results if eval_loop_ix == 0: assert decoder_type == TRAINING_DECODER return OrderedDict({'[TF]X-Ent': (denom, policy_loss), '[TF]Perplexity': (denom, perplexity), '[TF]Acc_1': (denom, 100. * acc_1), '[TF]Acc_1_NoHold': (denom_no_hold, 100. * acc_1_no_hold), '[TF]Acc_Tokens': (nb_tokens_total, 100. * acc_tokens), '[TF]Acc_Player': (denom_player, 100. * acc_player)}), detailed_results # 1 - Greedy Results if eval_loop_ix == 1: assert decoder_type == GREEDY_DECODER return OrderedDict({'[Gr]Acc_1': (denom, 100. * acc_1), '[Gr]Acc_1_NoHold': (denom_no_hold, 100. * acc_1_no_hold), '[Gr]Acc_Tokens': (nb_tokens_total, 100. * acc_tokens), '[Gr]Acc_Player': (denom_player, 100. * acc_player)}), detailed_results # Otherwise, invalid evaluation_loop_ix raise RuntimeError('Invalid evaluation_loop_ix - Got "%s"' % eval_loop_ix) @staticmethod def _get_detailed_results(decoded_results, feed_dict, evaluation_loop_ix): """ Computes detailed accuracy statistics for the batch :param decoded_results: The decoded results (output of _decode() function) :param feed_dict: The feed dictionary that was given to session.run() :param eval_loop_ix: The current evaluation loop index :return: An ordered dictionary with result_name as key and a list of result values (Detailed results) """ del feed_dict # Unused args targets = decoded_results['targets'] log_probs = decoded_results['log_probs'] request_ids = decoded_results['request_id'] batch_size = targets.shape[0] nb_locs_per_target = targets.shape[1] decoded_orders = decoded_results['decoded_orders'] # Extracting from additional info for field_name in ['current_power', 'current_season', 'in_retreat_phase']: if field_name not in decoded_results: LOGGER.warning('The field "%s" is missing. Cannot compute stats', field_name) return OrderedDict() current_power_name = [POWER_VOCABULARY_IX_TO_KEY[current_power] for current_power in decoded_results['current_power']] current_season_name = ['SFW'[current_season] for current_season in decoded_results['current_season']] in_retreat_phase = decoded_results['in_retreat_phase'] # Prefix prefix = '[TF]' if evaluation_loop_ix == 0 else '[Gr]' # Building results dict results = OrderedDict() results[prefix + 'Accuracy'] = [] results[prefix + 'LogProbsDetails'] = [{}] # {request_id: (log_probs, mismatch)} for power_name in POWER_VOCABULARY_LIST: results[prefix + power_name] = [] for order_type in ['H', '-', '- VIA', 'S', 'C', 'R', 'B', 'D', 'WAIVE']: results[prefix + 'Order %s' % order_type] = [] for season in 'SFW': # Spring, Fall, Winter results[prefix + 'Season %s' % season] = [] for phase in 'MRA': # Movement, Retreats, Adjustments results[prefix + 'Phase %s' % phase] = [] for position in range(-1, NB_SUPPLY_CENTERS): # Position -1 is used for Adjustment phases results[prefix + 'Position %d' % position] = [] for order_loc in sorted(STANDARD_TOPO_LOCS): # Order location results[prefix + 'Loc %s' % order_loc] = [] # Computing accuracy for batch_ix in range(batch_size): request_id = request_ids[batch_ix] player_orders_mismatch = False nb_waive = 0 # We didn't learn a policy - Skipping if not len(targets[batch_ix]) or targets[batch_ix][0] == 0: # pylint: disable=len-as-condition continue for loc_ix in range(nb_locs_per_target): decoded_target = targets[batch_ix][loc_ix] decoded_target_order = ix_to_order(decoded_target) if decoded_target > EOS_ID else '' if not decoded_target_order: break if decoded_target_order == 'WAIVE': loc = 'WAIVE_{}'.format(nb_waive) order_type = 'WAIVE' nb_waive += 1 else: loc = decoded_target_order.split()[1][:3] order_type = decoded_target_order.split()[2] if len(decoded_target_order.split()) > 2 else 'H' if order_type == '-' and decoded_target_order.split()[-1] == 'VIA': order_type = '- VIA' # Determining categories power_name = current_power_name[batch_ix] season = current_season_name[batch_ix] if in_retreat_phase[batch_ix]: phase = 'R' order_type = 'R' if order_type in ['-', '- VIA'] else order_type else: phase = {'H': 'M', '-': 'M', '- VIA': 'M', 'S': 'M', 'C': 'M', 'R': 'R', 'D': 'A', 'B': 'A', 'WAIVE': 'A'}[order_type] # Use -1 as position for A phase position = -1 if phase == 'A' else loc_ix stats_key = StatsKey(prefix, power_name, order_type, season, phase, position) # Computing accuracies success = int(loc in decoded_orders[batch_ix] and decoded_orders[batch_ix][loc].order == decoded_target_order) if not success: player_orders_mismatch = True results[prefix + 'Accuracy'] += [success] results[prefix + power_name] += [success] results[prefix + 'Order %s' % order_type] += [success] results[prefix + 'Season %s' % season] += [success] results[prefix + 'Phase %s' % phase] += [success] results[prefix + 'Position %d' % position] += [success] if order_type != 'WAIVE': results[prefix + 'Loc %s' % loc] += [success] results[stats_key] = results.get(stats_key, []) + [success] # Storing (log_probs, mismatch) results[prefix + 'LogProbsDetails'][0][request_id] = (log_probs[batch_ix].sum(), int(player_orders_mismatch)) # Returning results return results @staticmethod def _post_process_results(detailed_results): """ Perform post-processing on the detailed results :param detailed_results: An dictionary which contains detailed evaluation statistics :return: A dictionary with the post-processed statistics. """ # Adding [Gr]SearchFailure (== 1. iff. logprob(label) > logprob(greedy) and greedy != label) # Adding [TF]Acc_Player and [Gr]Acc_Player # Removing LogProbsDetails # Make sure the detailed results have the correct key (i.e. they have not yet been post-processed) for prefix in ['[TF]', '[Gr]']: assert prefix + 'LogProbsDetails' in detailed_results # Building a dictionary {request_id: (log_probs, mismatch)} tf_items, gr_items = {}, {} for tf_item in detailed_results['[TF]LogProbsDetails']: tf_items.update(tf_item) for gr_item in detailed_results['[Gr]LogProbsDetails']: gr_items.update(gr_item) # Making sure we have processed the same number of TF items and Gr items tf_nb_items = len(tf_items) gr_nb_items = len(gr_items) if tf_nb_items != gr_nb_items: LOGGER.warning('Got a different number of items between [TF] (%d items) and [Gr] (%d items)', tf_nb_items, gr_nb_items) # Computing search failure and mismatch search_failure, gr_acc_player, tf_acc_player = [], [], [] for request_id in tf_items: if request_id not in gr_items: LOGGER.warning('Item %s was computed using [TF], but is missing for [Gr]. Skipping.', request_id) continue tf_logprobs, tf_mismatch = tf_items[request_id] gr_logprobs, gr_mismatch = gr_items[request_id] # Computing stats if gr_mismatch: search_failure += [int(tf_logprobs > gr_logprobs)] tf_acc_player += [int(not tf_mismatch)] gr_acc_player += [int(not gr_mismatch)] # Removing extra keys and adding new keys detailed_results['[Gr]SearchFailure'] = search_failure detailed_results['[TF]Acc_Player'] = tf_acc_player detailed_results['[Gr]Acc_Player'] = gr_acc_player del detailed_results['[TF]LogProbsDetails'] del detailed_results['[Gr]LogProbsDetails'] # Returning post-processed results return detailed_results
diplomacy/research
diplomacy_research/models/policy/order_based/model.py
Python
mit
28,290
package com.currencycloud.client.model; import com.currencycloud.client.Utils; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.annotation.JsonNaming; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; @Deprecated @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) @JsonInclude(JsonInclude.Include.NON_NULL) public class Iban implements Entity { private String id; private String ibanCode; private String accountId; private String currency; private String accountHolderName; private String bankInstitutionName; private String bankInstitutionAddress; private String bankInstitutionCountry; private String bicSwift; private Date createdAt; private Date updatedAt; private String scope; protected Iban() { } public static Iban create() { return new Iban(); } @Override public String getId() { return id; } public void setId(String id) { this.id = id; } public String getIbanCode() { return ibanCode; } public void setIbanCode(String ibanCode) { this.ibanCode = ibanCode; } public String getAccountId() { return accountId; } public void setAccountId (String accountId) { this.accountId = accountId; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public String getAccountHolderName() { return accountHolderName; } public void setAccountHolderName(String accountHolderName) { this.accountHolderName = accountHolderName; } public String getBankInstitutionName() { return bankInstitutionName; } public void setBankInstitutionName(String bankInstitutionName) { this.bankInstitutionName = bankInstitutionName; } public String getBankInstitutionAddress() { return bankInstitutionAddress; } public void setBankInstitutionAddress (String bankInstitutionAddress) { this.bankInstitutionAddress = bankInstitutionAddress; } public String getBankInstitutionCountry() { return bankInstitutionCountry; } public void setBankInstitutionCountry(String bankInstitutionCountry) { this.bankInstitutionCountry = bankInstitutionCountry; } public String getBicSwift() { return bicSwift; } public void setBicSwift(String bicSwift) { this.bicSwift = bicSwift; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } @Override public String toString() { final ObjectMapper objectMapper = new ObjectMapper() .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .setDateFormat(new SimpleDateFormat(Utils.dateFormat)); Map<String, Object> map = new HashMap<>(); map.put("id", id); map.put("ibanCode", ibanCode); map.put("accountId", accountId); map.put("currency", currency); map.put("accountHolderName", accountHolderName); map.put("bankInstitutionName", bankInstitutionName); map.put("bankInstitutionAddress", bankInstitutionAddress); map.put("bankInstitutionCountry", bankInstitutionCountry); map.put("bicSwift", bicSwift); map.put("createdAt", createdAt); map.put("updatedAt", updatedAt); try { return objectMapper.writeValueAsString(map); } catch (JsonProcessingException e) { return String.format("{\"error\": \"%s\"}", e.getMessage()); } } }
CurrencyCloud/currencycloud-java
src/main/java/com/currencycloud/client/model/Iban.java
Java
mit
4,309
module.exports = function() { let heroes = ["leto", "duncan", "goku", "batman", "asterix", "naruto", "totoro"]; for(let index = Math.max(0, heroes.length - 5), __ks_0 = Math.min(heroes.length, 3), hero; index < __ks_0; ++index) { hero = heroes[index]; console.log("The hero at index %d is %s", index, hero); } };
kaoscript/kaoscript
test/fixtures/compile/for/for.block.in.from.asc.wbn.wep.ns.js
JavaScript
mit
319
// Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). // For example: // Given binary tree {3,9,20,#,#,15,7}, // 3 // / \ // 9 20 // / \ // 15 7 // return its level order traversal as: // [ // [3], // [9,20], // [15,7] // ] /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ var levelOrder = function(root) { var lib = {}, result = []; function traverse(cNode, cDepth){ if(cNode === null){ return; } else { if(lib[cDepth] === undefined){ lib[cDepth] = [cNode.val]; } else { lib[cDepth].push(cNode.val); } traverse(cNode.left, cDepth+1); traverse(cNode.right, cDepth+1); } } traverse(root, 1); for(var i = 1; i <= Object.keys(lib).length; i++){ result.push(lib[i]); } return result; };
Vrturo/Algo-Gem
Algorithms/JS/trees/binaryLvlOrderTraverse.js
JavaScript
mit
1,066
""" Django settings for sippa project. Generated by 'django-admin startproject' using Django 1.10.2. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os import environ # three folder back (/a/b/c/ - 3 = /) root = environ.Path(__file__) - 3 # set default values and casting env = environ.Env(DEBUG=(bool, False),) # reading .env file environ.Env.read_env() # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env('DEBUG') ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core.apps.CoreConfig', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'sippa.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'sippa.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'pt-br' TIME_ZONE = 'America/Fortaleza' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY') AWS_AUTO_CREATE_BUCKET = True AWS_STORAGE_BUCKET_NAME = 'sippa_files' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_FILE_OVERWRITE = False AWS_QUERYSTRING_AUTH = False AWS_S3_SECURE_URLS = False BASE_AWS_URL = 'https://%s' % AWS_S3_CUSTOM_DOMAIN STATICFILES_LOCATION = 'static' STATIC_URL = '%s/%s/' % (BASE_AWS_URL, STATICFILES_LOCATION) MEDIAFILES_LOCATION = 'media' MEDIA_URL = '%s/%s/' % (BASE_AWS_URL, MEDIAFILES_LOCATION) # For custom admin ADMIN_SITE_HEADER = 'SIPPA' CORS_URLS_REGEX = r'^.*$' CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', )
luissiqueira/sippa-no-api
sippa/settings.py
Python
mit
4,223
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using ILCompiler.DependencyAnalysis; using ILCompiler.DependencyAnalysisFramework; using Internal.IL; using Internal.IL.Stubs; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Debug = System.Diagnostics.Debug; namespace ILCompiler { public abstract class Compilation : ICompilation { protected readonly DependencyAnalyzerBase<NodeFactory> _dependencyGraph; protected readonly NodeFactory _nodeFactory; protected readonly Logger _logger; public NameMangler NameMangler => _nodeFactory.NameMangler; public NodeFactory NodeFactory => _nodeFactory; public CompilerTypeSystemContext TypeSystemContext => NodeFactory.TypeSystemContext; public Logger Logger => _logger; internal PInvokeILProvider PInvokeILProvider { get; } protected abstract bool GenerateDebugInfo { get; } private readonly TypeGetTypeMethodThunkCache _typeGetTypeMethodThunks; private readonly AssemblyGetExecutingAssemblyMethodThunkCache _assemblyGetExecutingAssemblyMethodThunks; private readonly MethodBaseGetCurrentMethodThunkCache _methodBaseGetCurrentMethodThunks; protected Compilation( DependencyAnalyzerBase<NodeFactory> dependencyGraph, NodeFactory nodeFactory, IEnumerable<ICompilationRootProvider> compilationRoots, Logger logger) { _dependencyGraph = dependencyGraph; _nodeFactory = nodeFactory; _logger = logger; _dependencyGraph.ComputeDependencyRoutine += ComputeDependencyNodeDependencies; NodeFactory.AttachToDependencyGraph(_dependencyGraph); var rootingService = new RootingServiceProvider(dependencyGraph, nodeFactory); foreach (var rootProvider in compilationRoots) rootProvider.AddCompilationRoots(rootingService); MetadataType globalModuleGeneratedType = nodeFactory.CompilationModuleGroup.GeneratedAssembly.GetGlobalModuleType(); _typeGetTypeMethodThunks = new TypeGetTypeMethodThunkCache(globalModuleGeneratedType); _assemblyGetExecutingAssemblyMethodThunks = new AssemblyGetExecutingAssemblyMethodThunkCache(globalModuleGeneratedType); _methodBaseGetCurrentMethodThunks = new MethodBaseGetCurrentMethodThunkCache(); bool? forceLazyPInvokeResolution = null; // TODO: Workaround lazy PInvoke resolution not working with CppCodeGen yet // https://github.com/dotnet/corert/issues/2454 // https://github.com/dotnet/corert/issues/2149 if (nodeFactory.IsCppCodegenTemporaryWorkaround) forceLazyPInvokeResolution = false; PInvokeILProvider = new PInvokeILProvider(new PInvokeILEmitterConfiguration(forceLazyPInvokeResolution), nodeFactory.InteropStubManager.InteropStateManager); _methodILCache = new ILProvider(PInvokeILProvider); } private ILProvider _methodILCache; public MethodIL GetMethodIL(MethodDesc method) { // Flush the cache when it grows too big if (_methodILCache.Count > 1000) _methodILCache = new ILProvider(PInvokeILProvider); return _methodILCache.GetMethodIL(method); } protected abstract void ComputeDependencyNodeDependencies(List<DependencyNodeCore<NodeFactory>> obj); protected abstract void CompileInternal(string outputFile, ObjectDumper dumper); public DelegateCreationInfo GetDelegateCtor(TypeDesc delegateType, MethodDesc target, bool followVirtualDispatch) { return DelegateCreationInfo.Create(delegateType, target, NodeFactory, followVirtualDispatch); } /// <summary> /// Gets an object representing the static data for RVA mapped fields from the PE image. /// </summary> public ObjectNode GetFieldRvaData(FieldDesc field) { if (field.GetType() == typeof(PInvokeLazyFixupField)) { var pInvokeFixup = (PInvokeLazyFixupField)field; PInvokeMetadata metadata = pInvokeFixup.PInvokeMetadata; return NodeFactory.PInvokeMethodFixup(metadata.Module, metadata.Name); } else { // Use the typical field definition in case this is an instantiated generic type field = field.GetTypicalFieldDefinition(); return NodeFactory.ReadOnlyDataBlob(NameMangler.GetMangledFieldName(field), ((EcmaField)field).GetFieldRvaData(), NodeFactory.Target.PointerSize); } } public bool HasLazyStaticConstructor(TypeDesc type) { return TypeSystemContext.HasLazyStaticConstructor(type); } public MethodDebugInformation GetDebugInfo(MethodIL methodIL) { if (!GenerateDebugInfo) return MethodDebugInformation.None; // This method looks odd right now, but it's an extensibility point that lets us generate // fake debugging information for things that don't have physical symbols. return methodIL.GetDebugInfo(); } /// <summary> /// Resolves a reference to an intrinsic method to a new method that takes it's place in the compilation. /// This is used for intrinsics where the intrinsic expansion depends on the callsite. /// </summary> /// <param name="intrinsicMethod">The intrinsic method called.</param> /// <param name="callsiteMethod">The callsite that calls the intrinsic.</param> /// <returns>The intrinsic implementation to be called for this specific callsite.</returns> public MethodDesc ExpandIntrinsicForCallsite(MethodDesc intrinsicMethod, MethodDesc callsiteMethod) { Debug.Assert(intrinsicMethod.IsIntrinsic); var intrinsicOwningType = intrinsicMethod.OwningType as MetadataType; if (intrinsicOwningType == null) return intrinsicMethod; if (intrinsicOwningType.Module != TypeSystemContext.SystemModule) return intrinsicMethod; if (intrinsicOwningType.Name == "Type" && intrinsicOwningType.Namespace == "System") { if (intrinsicMethod.Signature.IsStatic && intrinsicMethod.Name == "GetType") { ModuleDesc callsiteModule = (callsiteMethod.OwningType as MetadataType)?.Module; if (callsiteModule != null) { Debug.Assert(callsiteModule is IAssemblyDesc, "Multi-module assemblies"); return _typeGetTypeMethodThunks.GetHelper(intrinsicMethod, ((IAssemblyDesc)callsiteModule).GetName().FullName); } } } else if (intrinsicOwningType.Name == "Assembly" && intrinsicOwningType.Namespace == "System.Reflection") { if (intrinsicMethod.Signature.IsStatic && intrinsicMethod.Name == "GetExecutingAssembly") { ModuleDesc callsiteModule = (callsiteMethod.OwningType as MetadataType)?.Module; if (callsiteModule != null) { Debug.Assert(callsiteModule is IAssemblyDesc, "Multi-module assemblies"); return _assemblyGetExecutingAssemblyMethodThunks.GetHelper((IAssemblyDesc)callsiteModule); } } } else if (intrinsicOwningType.Name == "MethodBase" && intrinsicOwningType.Namespace == "System.Reflection") { if (intrinsicMethod.Signature.IsStatic && intrinsicMethod.Name == "GetCurrentMethod") { return _methodBaseGetCurrentMethodThunks.GetHelper(callsiteMethod).InstantiateAsOpen(); } } return intrinsicMethod; } public bool HasFixedSlotVTable(TypeDesc type) { return NodeFactory.VTable(type).HasFixedSlots; } public bool NeedsRuntimeLookup(ReadyToRunHelperId lookupKind, object targetOfLookup) { switch (lookupKind) { case ReadyToRunHelperId.TypeHandle: case ReadyToRunHelperId.NecessaryTypeHandle: case ReadyToRunHelperId.DefaultConstructor: return ((TypeDesc)targetOfLookup).IsRuntimeDeterminedSubtype; case ReadyToRunHelperId.MethodDictionary: case ReadyToRunHelperId.MethodEntry: case ReadyToRunHelperId.VirtualDispatchCell: case ReadyToRunHelperId.MethodHandle: return ((MethodDesc)targetOfLookup).IsRuntimeDeterminedExactMethod; case ReadyToRunHelperId.FieldHandle: return ((FieldDesc)targetOfLookup).OwningType.IsRuntimeDeterminedSubtype; default: throw new NotImplementedException(); } } public ISymbolNode ComputeConstantLookup(ReadyToRunHelperId lookupKind, object targetOfLookup) { switch (lookupKind) { case ReadyToRunHelperId.TypeHandle: return NodeFactory.ConstructedTypeSymbol((TypeDesc)targetOfLookup); case ReadyToRunHelperId.NecessaryTypeHandle: return NodeFactory.NecessaryTypeSymbol((TypeDesc)targetOfLookup); case ReadyToRunHelperId.MethodDictionary: return NodeFactory.MethodGenericDictionary((MethodDesc)targetOfLookup); case ReadyToRunHelperId.MethodEntry: return NodeFactory.FatFunctionPointer((MethodDesc)targetOfLookup); case ReadyToRunHelperId.MethodHandle: return NodeFactory.RuntimeMethodHandle((MethodDesc)targetOfLookup); case ReadyToRunHelperId.FieldHandle: return NodeFactory.RuntimeFieldHandle((FieldDesc)targetOfLookup); case ReadyToRunHelperId.DefaultConstructor: { var type = (TypeDesc)targetOfLookup; MethodDesc ctor = type.GetDefaultConstructor(); if (ctor == null) { MetadataType activatorType = TypeSystemContext.SystemModule.GetKnownType("System", "Activator"); MetadataType classWithMissingCtor = activatorType.GetKnownNestedType("ClassWithMissingConstructor"); ctor = classWithMissingCtor.GetParameterlessConstructor(); } return NodeFactory.CanonicalEntrypoint(ctor); } default: throw new NotImplementedException(); } } public GenericDictionaryLookup ComputeGenericLookup(MethodDesc contextMethod, ReadyToRunHelperId lookupKind, object targetOfLookup) { GenericContextSource contextSource; if (contextMethod.RequiresInstMethodDescArg()) { contextSource = GenericContextSource.MethodParameter; } else if (contextMethod.RequiresInstMethodTableArg()) { contextSource = GenericContextSource.TypeParameter; } else { Debug.Assert(contextMethod.AcquiresInstMethodTableFromThis()); contextSource = GenericContextSource.ThisObject; } // Can we do a fixed lookup? Start by checking if we can get to the dictionary. // Context source having a vtable with fixed slots is a prerequisite. if (contextSource == GenericContextSource.MethodParameter || HasFixedSlotVTable(contextMethod.OwningType)) { DictionaryLayoutNode dictionaryLayout; if (contextSource == GenericContextSource.MethodParameter) dictionaryLayout = _nodeFactory.GenericDictionaryLayout(contextMethod); else dictionaryLayout = _nodeFactory.GenericDictionaryLayout(contextMethod.OwningType); // If the dictionary layout has fixed slots, we can compute the lookup now. Otherwise defer to helper. if (dictionaryLayout.HasFixedSlots) { int pointerSize = _nodeFactory.Target.PointerSize; GenericLookupResult lookup = ReadyToRunGenericHelperNode.GetLookupSignature(_nodeFactory, lookupKind, targetOfLookup); int dictionarySlot = dictionaryLayout.GetSlotForEntry(lookup); int dictionaryOffset = dictionarySlot * pointerSize; if (contextSource == GenericContextSource.MethodParameter) { return GenericDictionaryLookup.CreateFixedLookup(contextSource, dictionaryOffset); } else { int vtableSlot = VirtualMethodSlotHelper.GetGenericDictionarySlot(_nodeFactory, contextMethod.OwningType); int vtableOffset = EETypeNode.GetVTableOffset(pointerSize) + vtableSlot * pointerSize; return GenericDictionaryLookup.CreateFixedLookup(contextSource, vtableOffset, dictionaryOffset); } } } // Fixed lookup not possible - use helper. return GenericDictionaryLookup.CreateHelperLookup(contextSource); } CompilationResults ICompilation.Compile(string outputFile, ObjectDumper dumper) { if (dumper != null) { dumper.Begin(); } // In multi-module builds, set the compilation unit prefix to prevent ambiguous symbols in linked object files NameMangler.CompilationUnitPrefix = _nodeFactory.CompilationModuleGroup.IsSingleFileCompilation ? "" : Path.GetFileNameWithoutExtension(outputFile); CompileInternal(outputFile, dumper); if (dumper != null) { dumper.End(); } return new CompilationResults(_dependencyGraph, _nodeFactory); } private class RootingServiceProvider : IRootingServiceProvider { private DependencyAnalyzerBase<NodeFactory> _graph; private NodeFactory _factory; public RootingServiceProvider(DependencyAnalyzerBase<NodeFactory> graph, NodeFactory factory) { _graph = graph; _factory = factory; } public void AddCompilationRoot(MethodDesc method, string reason, string exportName = null) { IMethodNode methodEntryPoint = _factory.CanonicalEntrypoint(method); _graph.AddRoot(methodEntryPoint, reason); if (exportName != null) _factory.NodeAliases.Add(methodEntryPoint, exportName); } public void AddCompilationRoot(TypeDesc type, string reason) { if (!ConstructedEETypeNode.CreationAllowed(type)) { _graph.AddRoot(_factory.NecessaryTypeSymbol(type), reason); } else { _graph.AddRoot(_factory.ConstructedTypeSymbol(type), reason); } } public void RootThreadStaticBaseForType(TypeDesc type, string reason) { Debug.Assert(!type.IsGenericDefinition); MetadataType metadataType = type as MetadataType; if (metadataType != null && metadataType.ThreadStaticFieldSize.AsInt > 0) { _graph.AddRoot(_factory.TypeThreadStaticIndex(metadataType), reason); // Also explicitly root the non-gc base if we have a lazy cctor if(_factory.TypeSystemContext.HasLazyStaticConstructor(type)) _graph.AddRoot(_factory.TypeNonGCStaticsSymbol(metadataType), reason); } } public void RootGCStaticBaseForType(TypeDesc type, string reason) { Debug.Assert(!type.IsGenericDefinition); MetadataType metadataType = type as MetadataType; if (metadataType != null && metadataType.GCStaticFieldSize.AsInt > 0) { _graph.AddRoot(_factory.TypeGCStaticsSymbol(metadataType), reason); // Also explicitly root the non-gc base if we have a lazy cctor if (_factory.TypeSystemContext.HasLazyStaticConstructor(type)) _graph.AddRoot(_factory.TypeNonGCStaticsSymbol(metadataType), reason); } } public void RootNonGCStaticBaseForType(TypeDesc type, string reason) { Debug.Assert(!type.IsGenericDefinition); MetadataType metadataType = type as MetadataType; if (metadataType != null && (metadataType.NonGCStaticFieldSize.AsInt > 0 || _factory.TypeSystemContext.HasLazyStaticConstructor(type))) { _graph.AddRoot(_factory.TypeNonGCStaticsSymbol(metadataType), reason); } } public void RootVirtualMethodForReflection(MethodDesc method, string reason) { Debug.Assert(method.IsVirtual); if (!_factory.VTable(method.OwningType).HasFixedSlots) _graph.AddRoot(_factory.VirtualMethodUse(method), reason); if (method.IsAbstract) { _graph.AddRoot(_factory.ReflectableMethod(method), reason); } } } } // Interface under which Compilation is exposed externally. public interface ICompilation { CompilationResults Compile(string outputFileName, ObjectDumper dumper); } public class CompilationResults { private readonly DependencyAnalyzerBase<NodeFactory> _graph; private readonly NodeFactory _factory; protected ImmutableArray<DependencyNodeCore<NodeFactory>> MarkedNodes { get { return _graph.MarkedNodeList; } } internal CompilationResults(DependencyAnalyzerBase<NodeFactory> graph, NodeFactory factory) { _graph = graph; _factory = factory; } public void WriteDependencyLog(string fileName) { using (FileStream dgmlOutput = new FileStream(fileName, FileMode.Create)) { DgmlWriter.WriteDependencyGraphToStream(dgmlOutput, _graph, _factory); dgmlOutput.Flush(); } } public IEnumerable<MethodDesc> CompiledMethodBodies { get { foreach (var node in MarkedNodes) { if (node is IMethodBodyNode) yield return ((IMethodBodyNode)node).Method; } } } public IEnumerable<TypeDesc> ConstructedEETypes { get { foreach (var node in MarkedNodes) { if (node is ConstructedEETypeNode || node is CanonicalEETypeNode) { yield return ((IEETypeNode)node).Type; } } } } } }
yizhang82/corert
src/ILCompiler.Compiler/src/Compiler/Compilation.cs
C#
mit
20,193
using System.Text.RegularExpressions; using SharpRaven.Logging; namespace SentryWeb.Scrubbing { /// <summary> /// Silly example of replacing zero with hero when the divide by zero exception is thrown. /// </summary> public class DivisionByZeroFilter : IFilter { private static readonly Regex phoneRegex = new Regex("zero", RegexOptions.Compiled); public string Filter(string input) { return phoneRegex.Replace(input, "##-HERO-##"); } } }
olsh/serilog-sinks-sentry
demos/SentryWeb/Scrubbing/DivisionByZeroFilter.cs
C#
mit
519
require 'spec_helper' require 'lumberg/whm' CERT = File.read('./spec/sample_certs/main.crt') SELF_CERT = File.read('./spec/sample_certs/sample.crt') SELF_KEY = File.read('./spec/sample_certs/sample.key') module Lumberg describe Whm::Cert do before(:each) do @login = { host: @whm_host, hash: @whm_hash } @server = Whm::Server.new(@login.dup) @cert = Whm::Cert.new(server: @server.dup) end describe "#listcrts" do use_vcr_cassette "whm/cert/listcrts" it "lists installed certificates" do result = @cert.listcrts result[:success].should be_true result[:message].should be_true end end describe "#fetchsslinfo" do use_vcr_cassette "whm/cert/fetchsslinfo" it "displays the SSL certificate, private key, and CA bundle/intermediate certificate associated with a specified domain" do result = @cert.fetchsslinfo(domain: "myhost.com", crtdata: CERT) result[:success].should be_true result[:message].should match("ok") result[:params][:crt].should match(/.*BEGIN CERTIFICATE.*/) result[:params][:key].should match(/.*KEY.*/) end end describe "#generatessl" do use_vcr_cassette "whm/cert/generatessl" context "generating a new CSR" do subject do @cert.generatessl( city: "houston", host: "myhost.com", country: "US", state: "TX", company: "Company", company_division: "Dept", email: "test@myhost.com", pass: "abc123", xemail: "", noemail: 1 ) end its([:success]) { should be_true } its([:message]) { should == "Key, Certificate, and CSR generated OK" } its([:params]) { should have_key :csr } its([:params]) { should have_key :key } its([:params]) { should have_key :cert } end context "generating a new CSR with an ampersand in company name" do subject do @cert.generatessl( city: "houston", host: "myhost.com", country: "US", state: "TX", company: "Foo & Bar", company_division: "Dept", email: "test@myhost.com", pass: "abc123", xemail: "", noemail: 1 ) end its([:success]) { should be_true } its([:message]) { should == "Key, Certificate, and CSR generated OK" } its([:params]) { should have_key :csr } its([:params]) { should have_key :key } its([:params]) { should have_key :cert } end end describe "#installssl" do use_vcr_cassette "whm/cert/installssl" it "installs a certificate" do result = @cert.installssl(domain: 'check.com', user: "nobody", cert: SELF_CERT, key: SELF_KEY, ip: '192.1.2.3') result[:success].should be_true result[:message].should match(/Certificate successfully installed/) end end describe "#fetch_ssl_vhosts" do use_vcr_cassette "whm/cert/fetch_ssl_vhosts" it "returns SSL vhosts" do result = @cert.fetch_ssl_vhosts result[:params][:vhosts].first[:user].should eq "blah" result[:params][:vhosts].first[:domains].should include "example.com" end end end end
site5/lumberg
spec/whm/cert_spec.rb
Ruby
mit
3,549
// import { CallLogs } from '../index'; import expect from 'expect'; // import { shallow } from 'enzyme'; // import React from 'react'; describe('<CallLogs />', () => { it('Expect to have unit tests specified', () => { expect(true).toEqual(false); }); });
luis-teixeira/react-twilio-webphone
app/containers/CallLogs/tests/index.test.js
JavaScript
mit
266
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using BookClient.Enum; using BookClient.Interface; using BookClient.Models; using BookClient.ViewModels; namespace BookClient.Controllers { public class BookController : Controller { private readonly string _serviceUri; public BookController(IServiceFactory serviceFactory) { _serviceUri = serviceFactory.GetServiceUri(); } // GET: Book public ActionResult Index() { return View(); } public ActionResult Details(int id) { //TODO create a new view and show that return RedirectToAction("Index", "Book", id); } public ActionResult Edit(int id) { throw new NotImplementedException(); } public ActionResult Delete(int id) { throw new NotImplementedException(); } public ActionResult Create() { return View(new CreateBookViewModel()); } public async Task<ActionResult> SearchAsync(SearchBookViewModel searchBookViewModel) { HttpClient client = new HttpClient { BaseAddress = new Uri(_serviceUri) }; try { var bookViewModel = new SearchBookViewModel(); HttpResponseMessage response = await client.GetAsync("api/books/search/" + searchBookViewModel.SearchField + (string.IsNullOrEmpty(searchBookViewModel.Subject) ? null : "/" + searchBookViewModel.Subject)).ConfigureAwait(false); if (response.StatusCode == HttpStatusCode.OK) { bookViewModel.Books = await response.Content.ReadAsAsync<List<Book>>().ConfigureAwait(false); } else if (response.StatusCode == HttpStatusCode.NotFound) { ModelState.AddModelError("", "No books found."); return View("Index"); } return View("Index", bookViewModel); } catch (HttpRequestException e) { ModelState.AddModelError("Error", "Error: " + e.Message); return View("Index"); } } public async Task<ActionResult> ReserveAsync(string isbn) { HttpClient client = new HttpClient { BaseAddress = new Uri(_serviceUri) }; try { if (Session["UserId"] != null) { HttpResponseMessage normalMemberResponse = await client.GetAsync("api/NormalMembers/Search/" + (int)Session["UserId"]).ConfigureAwait(false); if (normalMemberResponse.StatusCode == HttpStatusCode.OK) { NormalMember member = await normalMemberResponse.Content.ReadAsAsync<NormalMember>().ConfigureAwait(false); HttpResponseMessage response = await client.PostAsJsonAsync("api/LibraryLoan", new LoanRequirement { Isbn = isbn, CopyNumber = 1, MemberId = member.Member_id }) .ConfigureAwait(false); if (response.StatusCode == HttpStatusCode.OK) { TempData["msg"] = "<script>alert('Reserve successfully');</script>"; return View("Index"); } else { ModelState.AddModelError("Error", await response.Content.ReadAsStringAsync().ConfigureAwait(false)); return View("Index"); } } else { ModelState.AddModelError("Error", "Error: user is not a library member, please contact the library."); return View("Index"); } } else { return RedirectToAction("Index", "Login"); } } catch (HttpRequestException e) { ModelState.AddModelError("Error", "Error: " + e.Message); return View("Index"); } } } }
Yaxuan/BookApp
BookClient/Controllers/BookController.cs
C#
mit
4,685
namespace Kanbang.Core.Events { using System; internal static class EventTypes { public static readonly EventType<Exception> ExceptionOccured = new EventType<Exception>(1000, "Exception occured"); } }
niaher/kanbang
Kanbang.Core/Events/EventTypes.cs
C#
mit
210
'use strict'; import axios from 'axios'; export default { search: (criteria) => { return axios.post('/gameSystemRankings/search', criteria) .then(function(response) { return response.data; }); }, createOrUpdate: (data) => { return axios.post('/gameSystemRankings', data) .then(function(response) { return response.data; }); }, remove: (id) => { return axios.delete('/gameSystemRankings/' + id) .then(function(response) { return response.data; }); } };
zdizzle6717/battle-comm
src/services/GameSystemRankingService.js
JavaScript
mit
496
namespace Light.Data { internal class LightStringMatchDataFieldInfo : LightDataFieldInfo, ISupportNotDefine, IDataFieldInfoConvert { private bool _isNot; private readonly bool _starts; private readonly bool _ends; private readonly object _left; private readonly object _right; public LightStringMatchDataFieldInfo (DataEntityMapping mapping, bool starts, bool ends, object left, object right) : base (mapping) { _starts = starts; _ends = ends; _left = left; _right = right; } public void SetNot () { _isNot = !_isNot; } internal override string CreateSqlString (CommandFactory factory, bool isFullName, CreateSqlState state) { var sql = state.GetDataSql (this, isFullName); if (sql != null) { return sql; } object left; object right; var leftInfo = _left as DataFieldInfo; var rightInfo = _right as DataFieldInfo; if (!Equals (leftInfo, null) && !Equals (rightInfo, null)) { left = leftInfo.CreateSqlString (factory, isFullName, state); right = rightInfo.CreateSqlString (factory, isFullName, state); } else if (!Equals (leftInfo, null)) { left = leftInfo.CreateSqlString (factory, isFullName, state); var rightObject = LambdaExpressionExtend.ConvertLambdaObject (_right); right = state.AddDataParameter (factory, rightObject); } else if (!Equals (rightInfo, null)) { right = rightInfo.CreateSqlString (factory, isFullName, state); var leftObject = LambdaExpressionExtend.ConvertLambdaObject (_left); left = state.AddDataParameter (factory, leftObject); } else { throw new LightDataException (SR.DataFieldContentError); } sql = factory.CreateLikeMatchQuerySql (left, right, _starts, _ends, _isNot); state.SetDataSql (this, isFullName, sql); return sql; } public QueryExpression ConvertToExpression () { return new LightMatchQueryExpression (this); } } }
aquilahkj/Light.Data2
src/Light.Data/DataField/LightStringMatchDataFieldInfo.cs
C#
mit
1,919
<?php header("Content-type:application/json; charset=utf-8"); require_once('db.php'); if($link){ @$newsId = $_POST['newsId']; mysqli_query($link,'SET NAMES utf8'); //防止中文变成问号或乱码 $sql = "DELETE FROM `news` WHERE `news`.`id` = {$newsId}"; mysqli_query($link,$sql); echo json_encode(array('删除状态'=>'成功')); } mysqli_close($link); //关闭数据库连接 ?>
pengxiaohua/baiduNews-by-PHP
server/delete.php
PHP
mit
450
# encoding: utf-8 from views import dogs, breeds, users urls = [ ('/dogs/', dogs.DogAPI.as_view('dog_api')), ('/user_dogs/', dogs.UserDogsAPI.as_view('user_dogs_api')), ('/breeds/', breeds.BreedAPI.as_view('breed_api')), ('/breed_dogs/', breeds.BreedDogsAPI.as_view('breed_dogs_api')), ('/users/', users.UserAPI.as_view('user_api')), ('/login/', users.LoginAPI.as_view('login_api')), ('/logout/', users.LogoutAPI.as_view('logout_api')) ]
gabrielecker/DogAdoption-Backend
project/urls.py
Python
mit
467
<?php /* * The MIT License (MIT) * * Copyright (c) 2014-2015 Spomky-Labs * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ namespace SpomkyLabs\IpFilterBundle\Model; use Symfony\Bridge\Doctrine\RegistryInterface; class IpManager implements IpManagerInterface { /** * @var \Doctrine\Common\Persistence\ObjectManager */ protected $entity_manager; /** * @var string */ protected $class; /** * @var \Doctrine\Common\Persistence\ObjectRepository */ protected $entity_repository; public function __construct(RegistryInterface $registry, $class) { $this->class = $class; $this->entity_manager = $registry->getManagerForClass($class); $this->entity_repository = $this->entity_manager->getRepository($class); } /** * @return \Doctrine\Common\Persistence\ObjectManager */ protected function getEntityManager() { return $this->entity_manager; } /** * {@inheritdoc} */ protected function getEntityRepository() { return $this->entity_repository; } /** * {@inheritdoc} */ public function findIpAddress($ip, $environment) { return $this->getEntityRepository()->createQueryBuilder('r') ->where('r.ip = :ip') ->andWhere("r.environment LIKE :environment OR r.environment='a:0:{}'") ->orderBy('r.authorized', 'DESC') ->setParameter('ip', $ip) ->setParameter('environment', "%$environment%") ->getQuery() ->execute(); } /** * {@inheritdoc} */ public function createIp() { $class = $this->class; return new $class(); } /** * {@inheritdoc} */ public function saveIp(IpInterface $ip) { $this->getEntityManager()->persist($ip); $this->getEntityManager()->flush(); return $this; } /** * {@inheritdoc} */ public function deleteIp(IpInterface $ip) { $this->getEntityManager()->remove($ip); $this->getEntityManager()->flush(); return $this; } }
Spomky-Labs/IpFilterBundle
Model/IpManager.php
PHP
mit
2,234
var StatusSelector = React.createClass({ handleChange: function(event) { this.props.updateStatusFilter(event.target.value) }, handleNodeGrep: function(event) { this.props.updateNodeFilter(event.target.value) }, handleKeyGrep: function(event) { this.props.updateKeyFilter(event.target.value) }, render: function() { return ( <div> <nav className="navbar navbar-default"> <div className="container"> <form className="form-inline"> <button type="button" value="" className="btn btn-default navbar-btn" onClick={this.handleChange}>Any</button> <button type="button" value="success" className="btn btn-default navbar-btn alert-success" onClick={this.handleChange}>Success</button> <button type="button" value="warning" className="btn btn-default navbar-btn alert-warning" onClick={this.handleChange}>Warning</button> <button type="button" value="danger" className="btn btn-default navbar-btn alert-danger" onClick={this.handleChange}>Danger</button> <button type="button" value="info" className="btn btn-default navbar-btn alert-info" onClick={this.handleChange}>Info</button> <input type="text" id="nodeFilter" className="form-control" placeholder="node | service" onKeyUp={this.handleNodeGrep}/> <input type="text" id="keyFilter" className="form-control" placeholder="key" onKeyUp={this.handleKeyGrep}/> </form> </div> </nav> </div> ); } }); var Title = React.createClass({ render: function() { return ( <span>: {this.props.category}</span> ); } }); var Category = React.createClass({ render: function() { var active = this.props.currentCategory == this.props.name ? "active" : ""; var href = "/" + this.props.name; return ( <li role="presentation" className={active}><a href={href}>{this.props.name}</a></li> ); } }); var Categories = React.createClass({ render: function() { var currentCategory = this.props.currentCategory var handleChange = this.handleChange var cats = this.props.data.map(function(cat, index) { return ( <Category key={index} name={cat} currentCategory={currentCategory}/> ); }); return ( <ul className="nav nav-tabs"> {cats} </ul> ); } }); var Item = React.createClass({ render: function() { var item = this.props.item; var icon = "glyphicon"; var status = item.status; if (item.status != "success" && item.status != "info") { icon += " glyphicon-alert"; status += " alert-" + item.status; } return ( <tbody> <tr className={status} title={status}> <td><span className={icon} /> {item.node}</td> <td>{item.address}</td> <td>{item.key}</td> <td>{item.timestamp}</td> </tr> <tr className={status}> <td colSpan={4}><ItemBody>{item.data}</ItemBody></td> </tr> </tbody> ); } }); var ItemBody = React.createClass({ handleClick: function() { if ( this.state.expanded && window.getSelection().toString() != "" ) { return; } this.setState({ expanded: !this.state.expanded }) }, getInitialState: function() { return { expanded: false }; }, render: function() { var classString = "item_body" if (this.state.expanded) { classString = "item_body_expanded" } return ( <pre className={classString} onClick={this.handleClick}>{this.props.children}</pre> ); } }); var Dashboard = React.createClass({ loadCategoriesFromServer: function() { $.ajax({ url: "/api/?keys", dataType: 'json', success: function(data, textStatus, request) { if (!this.state.currentCategory) { location.pathname = "/" + data[0] } else { this.setState({categories: data}) } }.bind(this), error: function(xhr, status, err) { console.error("/api/?keys", status, err.toString()); }.bind(this) }); }, loadDashboardFromServer: function() { if (!this.state.currentCategory) { setTimeout(this.loadDashboardFromServer, this.props.pollWait / 5); return; } var statusFilter = this.state.statusFilter; var ajax = $.ajax({ url: "/api/" + this.state.currentCategory + "?recurse&wait=55s&index=" + this.state.index || 0, dataType: 'json', success: function(data, textStatus, request) { var timer = setTimeout(this.loadDashboardFromServer, this.props.pollWait); var index = request.getResponseHeader('X-Consul-Index') this.setState({ items: data, index: index, timer: timer, }); }.bind(this), error: function(xhr, status, err) { console.log("ajax error:" + err) var wait = this.props.pollWait * 5 if (err == "abort") { wait = 0 } var timer = setTimeout(this.loadDashboardFromServer, wait); this.setState({ timer: timer }) }.bind(this) }); this.setState({ajax: ajax}) }, getInitialState: function() { var cat = location.pathname.replace(/^\//,"") if (cat == "") { cat = undefined } return { items: [], categories: [], index: 0, ajax: undefined, timer: undefined, statusFilter: "", nodeFilter: "", keyFilter: "", currentCategory: cat }; }, componentDidMount: function() { this.loadCategoriesFromServer(); this.loadDashboardFromServer(); }, updateStatusFilter: function(filter) { this.setState({ statusFilter: filter }); }, updateNodeFilter: function(filter) { this.setState({ nodeFilter: filter }); }, updateKeyFilter: function(filter) { this.setState({ keyFilter: filter }); }, render: function() { var statusFilter = this.state.statusFilter; var nodeFilter = this.state.nodeFilter; var keyFilter = this.state.keyFilter; var items = this.state.items.map(function(item, index) { if ((statusFilter == "" || item.status == statusFilter) && (nodeFilter == "" || item.node.indexOf(nodeFilter) != -1 ) && (keyFilter == "" || item.key.indexOf(keyFilter) != -1 )) { return ( <Item key={index} item={item} /> ); } else { return; } }); return ( <div> <h1>Dashboard <Title category={this.state.currentCategory} /></h1> <Categories data={this.state.categories} currentCategory={this.state.currentCategory} /> <StatusSelector status={this.state.statusFilter} updateStatusFilter={this.updateStatusFilter} updateNodeFilter={this.updateNodeFilter} updateKeyFilter={this.updateKeyFilter} /> <table className="table table-bordered"> <thead> <tr> <th>node | service</th> <th>address</th> <th>key</th> <th className="item_timestamp_col">timestamp</th> </tr> </thead> {items} </table> </div> ); } }); React.render( <Dashboard pollWait={1000} />, document.getElementById('content') );
fujiwara/consul-kv-dashboard
assets/scripts/dashboard.js
JavaScript
mit
7,248
module SimpleSalesforce module SalesforceObject # :nodoc: module CreatorsAndUpdaters def self.included(klass) klass.class_eval do extend ClassMethods include InstanceMethods end end module ClassMethods # Create a new SalesforceObject from a hash of attributes # e.g. SalesforceContact.create(:first_name => "Joe", :last_name => "Bloggs") def create(attributes) object = new(attributes) object.save object end end module InstanceMethods # Update an existing SalesforceObject with a hash of attributes, and save it def update_attributes(attributes) attributes.each do |att, value| send("#{att}=", value) end save end def new_record? salesforce_id.nil? end def save result = new_record? ? create : update end private def create attributes_for_create = build_salesforce_attributes # Response is of the format {:createResponse=>{:result=>{:success=>"true", :id=>"0038000000fgO5XAAU"}}} response = SimpleSalesforce::Binding.binding.create :sObject => attributes_for_create created_successfully = (response[:createResponse][:result][:success] == "true") rescue false if created_successfully @salesforce_id = response[:createResponse][:result][:id] rescue nil end created_successfully end def update attributes_for_update = build_salesforce_attributes response = SimpleSalesforce::Binding.binding.update :sObject => attributes_for_update updated_successfully = (response[:updateResponse][:result][:success] == "true") rescue false updated_successfully end def build_salesforce_attributes salesforce_attributes = {} self.class.local_fields.each do |local_field| salesforce_attributes[self.class.to_salesforce_field(local_field)] = send(:"#{local_field}") unless send(:"#{local_field}").nil? end salesforce_attributes[:type] = self.salesforce_object_type salesforce_attributes end end end end end
webcollective/simple_salesforce
lib/simple_salesforce/salesforce_object/creators_and_updaters.rb
Ruby
mit
2,391
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * 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@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_InfoCard * @subpackage Zend_InfoCard_Xml * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Interface.php 10020 2009-08-18 14:34:09Z j.fischer@metaways.de $ */ /** * The Interface required by any InfoCard Assertion Object implemented within the component * * @category Zend * @package Zend_InfoCard * @subpackage Zend_InfoCard_Xml * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ interface Zend_InfoCard_Xml_Assertion_Interface { /** * Get the Assertion ID of the assertion * * @return string The Assertion ID */ public function getAssertionID(); /** * Return an array of attributes (claims) contained within the assertion * * @return array An array of attributes / claims within the assertion */ public function getAttributes(); /** * Get the Assertion URI for this type of Assertion * * @return string the Assertion URI */ public function getAssertionURI(); /** * Return an array of conditions which the assertions are predicated on * * @return array an array of conditions */ public function getConditions(); /** * Validate the conditions array returned from the getConditions() call * * @param array $conditions An array of condtions for the assertion taken from getConditions() * @return mixed Boolean true on success, an array of condition, error message on failure */ public function validateConditions(Array $conditions); }
jodier/tmpdddf
web/private/tine20/library/Zend/InfoCard/Xml/Assertion/Interface.php
PHP
mit
2,251
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Comments extends MY_Shoptotalk { public $blockCommentsDelta = 0; public function __construct() { parent::__construct(); } public function index() { $post_id = $this->input->post('post_id'); $this->db->where("post_id", $post_id); $this->db->where("valid", 1); // When send new comment if($this->input->post('limit')){ $this->db->limit($this->input->post('limit')); $this->db->order_by("rdate", "desc"); } else { $this->db->order_by("rdate", "asc"); } $query = $this->db->get('comments'); foreach($query->result() AS $comment) { $comment->user_comment = $this->db->get_where('users', Array("_id" => $comment->user_id))->row(0); $comment->numOfCommentLoves = $this->count_comment_loves($comment->_id); $data['data'][] = $this->load->view('comment', $comment, TRUE); } $data['numOfComments'] = $this->count_comments($post_id); die(json_encode($data)); } public function add() { if($this->userCommentsBlock()) die('false'); $user_id = $this->userInfo->_id; $data['user_id'] = $user_id; $data['post_id'] = $this->input->post('post_id'); $data['text'] = $this->input->post('text'); $this->db->insert('comments',$data); $commentID = $this->db->insert_id(); $return['numOfcomments'] = $this->count_comments($data['post_id']); $return['commentID'] = $commentID; $post = $this->getPost($data['post_id']); $return['post_id'] = $post->_id; $return['alertUser'] = $this->getUser($post->user_id)->_id; $return['userMakeAction'] = $this->userInfo->fname. ' '.$this->userInfo->lname; $return['userMakeActionID'] = $this->userInfo->_id; $return['msg'] = 'newComment'; $return['type'] = 'posts'; $return['type'] = 'posts'; if($return['alertUser'] == $this->userInfo->_id) unset($return['alertUser']); die(json_encode($return)); } public function delete() { $id = $this->input->post('id'); $post_id = $this->input->post('post_id'); $data = Array('valid' => 0); $this->db->where("_id", $id); $this->db->where("user_id", $this->userInfo->_id); $this->db->update('comments', $data); if($this->db->affected_rows()){ $return['success'] = true; $return['post_id'] = $post_id; $return['numOfComments'] = $this->count_comments($post_id); } else { $return['success'] = false; } die(json_encode($return)); } private function userCommentsBlock() { $lastComment = $this->session->userdata('lastComment'); if( (time() - $lastComment) < $this->blockCommentsDelta) return true; $data['lastComment'] = time(); $this->session->set_userdata($data); return false; } }
Shoptotalk/SHOPTOTALK
application/controllers/Comments.php
PHP
mit
3,085
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using ChronicNetCore.Tags.Repeaters; using ChronicNetCore; namespace ChronicNetCore.Handlers { public class RmnSdSyHandler : IHandler { public Span Handle(IList<Token> tokens, Options options) { var month = (int)tokens[0].GetTag<RepeaterMonthName>().Value; var day = tokens[1].GetTag<ScalarDay>().Value; var year = tokens[2].GetTag<ScalarYear>().Value; Span span = null; try { var timeTokens = tokens.Skip(3).ToList(); var dayStart = Time.New(year, month, day); span = Utils.DayOrTime(dayStart, timeTokens, options); } catch (ArgumentException e) { span = null; } return span; } } }
messier51a/ChronicNetCore
src/ChronicNetCore/Handlers/RmnSdSyHandler.cs
C#
mit
911
module SS module TmpDirSupport def self.extended(obj) obj.before(:example) do obj.metadata[:tmpdir] = ::Dir.mktmpdir end obj.after(:example) do tmpdir = obj.metadata[:tmpdir] obj.metadata[:tmpdir] = nil ::FileUtils.rm_rf(tmpdir) if tmpdir end obj.class_eval do define_method(:tmpdir) do obj.metadata[:tmpdir] end def tmpfile(options = {}, &block) tmpfile = "#{tmpdir}/#{unique_id}" mode = options[:binary] ? "wb" : "w" mode = "#{mode}:#{options[:encoding]}" if options[:encoding] ::File.open(tmpfile, mode) { |file| yield file } tmpfile end def tmp_ss_file(options = {}) options = options.dup contents = options[:contents] if contents.respond_to?(:path) source_file = contents.path elsif contents.present? && (::File.exists?(contents) rescue false) source_file = contents else source_file = tmpfile(binary: options.delete(:binary)) { |file| file.write contents } end ss_file = SS::File.new(model: options.delete(:model) || "ss/temp_file") ss_file.site_id = options[:site].id if options[:site] ss_file.user_id = options[:user].id if options[:user] options.delete(:site) options.delete(:user) basename = options.delete(:basename) || "spec" content_type = options.delete(:content_type) || "application/octet-stream" Fs::UploadedFile.create_from_file(source_file, basename: basename, content_type: content_type) do |f| ss_file.in_file = f ss_file.save! ss_file.in_file = nil end ss_file.reload ss_file end end end end end RSpec.configuration.extend(SS::TmpDirSupport, tmpdir: true)
shirasagi/ss-handson
spec/support/ss/tmp_dir_support.rb
Ruby
mit
1,917
<?php /* Element Description: VC Image Box */ // Element Class class vc_facebook_button extends WPBakeryShortCode { // Element Init function __construct() { add_action( 'init', array( $this, 'vc_facebook_button_mapping' ) ); add_shortcode( 'vc_facebook_button', array( $this, 'vc_render_facebook_button' ) ); } // Element Mapping public function vc_facebook_button_mapping() { // Stop all if VC is not enabled if ( !defined( 'WPB_VC_VERSION' ) ) { return; } // Map the block with vc_map() vc_map( array( 'name' => __('WHOTHAT Facebook Button', 'facebook_button'), 'base' => 'vc_facebook_button', 'description' => __('Custom FACEBOOK button, that links to an account on the social media ', 'facebook_button'), 'category' => __('WHOTHAT elements', 'facebook_button'), 'icon' => get_template_directory_uri().'/assets/icons/ic_social_facebook.png', 'params' => array( array( 'type' => 'attach_image', 'holder' => 'img', 'heading' => __( 'Icon', 'image_box' ), 'param_name' => 'icon', 'admin_label' => false, 'weight' => 0, 'group' => 'General', ), array( 'type' => 'textfield', 'holder' => 'h4', 'heading' => __( 'Title', 'image_box' ), 'param_name' => 'title', 'value' => __( 'Input title', 'image_box' ), 'admin_label' => false, 'weight' => 1, 'group' => 'General', ), array( 'type' => 'textfield', 'holder' => 'h6', 'heading' => __( 'Subtitle', 'image_box' ), 'param_name' => 'subtitle', 'value' => __( 'Input title', 'image_box' ), 'admin_label' => false, 'weight' => 2, 'group' => 'General', ), array( 'type' => 'colorpicker', 'heading' => __( 'Hover color', 'image_box' ), 'param_name' => 'hover_color', 'value' => __( 'Hover color', 'image_box' ), 'admin_label' => false, 'weight' => 3, 'group' => 'General', ), array( 'type' => 'vc_link', 'heading' => __( 'Choose page', 'image_box' ), 'param_name' => 'target_link', 'admin_label' => false, 'weight' => 4, 'group' => 'General', ), array( 'type' => 'css_editor', 'heading' => __( 'Css', 'image_box' ), 'param_name' => 'css', 'group' => __( 'Design options', 'image_box' ), ), ), ) ); } // Element HTML public function vc_render_facebook_button ( $atts ) { // Params extraction extract( shortcode_atts( array( 'icon' => '', 'title' => '', 'subtitle' => '', 'hover_color' => '', 'target_link' => '', 'css' => '', ), $atts ) ); $href = vc_build_link( $target_link ); // Fill $html var with data $html = ' <div class="vc_imagebox_wrap ' . esc_attr( $css ) . '"> <a href="'.$href[url].'" class="imagebox_link" > <div class="vc_imagebox_image" > '.$iconlink.' </div> <div class="vc_imagebox_text"> </div> </a> </div> '; return $html; } } // End Element Class // Element Class Init new vc_facebook_button(); ?>
whothat-dk/Slagelse-Lift
wp-content/themes/whothat/composer/socialFacebook.php
PHP
mit
3,239
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CinemaWorld.Web")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CinemaWorld.Web")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2c1d0ee7-8e13-44da-8f8d-4661f9634618")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
izabelk/CinemaWorld
CinemaWorldProject/CinemaWorld.Web/Properties/AssemblyInfo.cs
C#
mit
1,361
/* TDD style with BDD statements */ import LoggerWithMetadata from './index'; import clogy from '../../lib/clogy.js'; // Passing arrow functions to Mocha is discouraged. Their lexical binding of the // this value makes them unable to access the Mocha context, and statements like // this.timeout(1000); will not work inside an arrow function. // https://mochajs.org/#arrow-functions describe('loggerWithMetadata', function() { let sandbox; beforeEach(function() { sandbox = sinon.sandbox.create(); }); afterEach(function() { sandbox.restore(); }); it('should call clogs info method with the given metadata', function() { sandbox.stub(clogy, 'info'); const loggerWithMetadata = LoggerWithMetadata({ file: 'somefile.js' }); loggerWithMetadata.info('Hello World', 'Everyone'); expect(clogy.info).to.have.been.calledWith('[INFO] [file:somefile.js]', 'Hello World', 'Everyone'); }); });
pgmanutd/clogy
extensions/logger-with-metadata/index.spec.js
JavaScript
mit
928
import json from unittest import TestCase from mock import Mock, patch, create_autospec class CommandTestCase(TestCase): """A TestCase for unit testing bot requests and responses. To use it: * provide your bot in *bot_class* (and optionally a config). * use self.send_message inside your test cases. It returns what your command returns. """ bot_class = None config = {} def setUp(self): self.bot = self.bot_class('slack_token', self.config.copy()) self.bot.name = str(self.bot_class) self.bot.my_mention = None # we'll just send test messages by name, not mention. # This patch is introspected to find command responses (and also prevents interaction with slack). self.bot._handle_command_response = create_autospec(self.bot._handle_command_response) self.ws = Mock() self.slack_patcher = patch.object(self.bot, 'slack', autospec=True) self.slack_mock = self.slack_patcher.start() def tearDown(self): self.slack_patcher.stop() def send_message(self, command, message_delimiter=':', **event): """Return the bot's response to a given command. :param command: the message to the bot. Do not include the bot's name, just the part after the colon. :param event: kwargs that will override the event sent to the bot. Useful when your bot expects message from a certain user or channel. """ _event = { 'type': 'message', 'text': "%s%s%s" % (self.bot.name, message_delimiter, command), 'channel': None, } self.assertTrue(_event['text'].startswith("%s%s" % (self.bot.name, message_delimiter))) _event.update(event) self.bot._on_message(self.ws, json.dumps(_event)) args, _ = self.bot._handle_command_response.call_args return args[0]
venmo/slouch
slouch/testing.py
Python
mit
1,912
'use strict'; const expect = require('chai').use(require('chai-string')).expect; const RSVP = require('rsvp'); const request = RSVP.denodeify(require('request')); const AddonTestApp = require('ember-cli-addon-tests').AddonTestApp; describe('FastBoot config', function () { this.timeout(400000); let app; before(function () { app = new AddonTestApp(); return app .create('fastboot-config', { skipNpm: true, emberVersion: 'latest', emberDataVersion: 'latest', }) .then(function () { app.editPackageJSON((pkg) => { delete pkg.devDependencies['ember-fetch']; delete pkg.devDependencies['ember-welcome-page']; }); return app.run('npm', 'install'); }) .then(function () { return app.startServer({ command: 'serve', }); }); }); after(function () { return app.stopServer(); }); it('provides sandbox globals', function () { return request({ url: 'http://localhost:49741/', headers: { Accept: 'text/html', }, }).then(function (response) { expect(response.statusCode).to.equal(200); expect(response.headers['content-type']).to.equalIgnoreCase( 'text/html; charset=utf-8' ); expect(response.body).to.contain('<h1>My Global</h1>'); }); }); });
ember-fastboot/ember-cli-fastboot
packages/ember-cli-fastboot/test/fastboot-config-test.js
JavaScript
mit
1,367
<?php include 'functions.php'; // laços (for,while,do..while,foreach) // for for ($i=0; $i < 10; $i++) { echo "ola for $i".linha(); } // while (testa sempre antes de entrar no bloco) $j = 11; while ($j <= 10) { echo "ola while $j".linha(); $j++; } // do..while (executa ao menos uma vez antes de testar) $k = 11; do { echo "ola do..while $k".linha(); $k++; } while ($k <= 10); // foreach $teste = array('id' => 123, 'nome' => 'fulano', 'email' => 'fulano@bla'); foreach ($teste as $key => $value) { echo "$key: $value".linha(); } ?>
mrecondo/linguagem_php
src/lacos.php
PHP
mit
586
@extends('pdf_layout') @section('style') <style> th{ padding: 5px; } .rotate { text-align: center; white-space: nowrap; vertical-align: middle; width: 1.5em; } .rotate div{ /* FF3.5+ */ -moz-transform: rotate(-90.0deg); /* Opera 10.5 */ -o-transform: rotate(-90.0deg); /* Saf3.1+, Chrome */ -webkit-transform: rotate(-90.0deg); /* IE6,IE7 */ filter: progid: DXImageTransform.Microsoft.BasicImage(rotation=0.083); /* IE8 */ -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)"; /* Standard */ transform: rotate(-90.0deg); } </style> @endsection @section('content') <section class="row bg-white"> <div class="col-12"> <table class="table-bordered" id="schedule"> <thead> <tr style="height:180px;"> <th width="15%">โครงการ</th> @php $emp_count = 0; @endphp @foreach($employee as $row) <th class="rotate"><div>{{$row->emp_fname}}</div></th> @php $emp_count++; @endphp @endforeach <th class="rotate" style="background-color:#de3465;"><div>แรงงาน</div></th> <th class="rotate" style="background-color:#de3465;"><div>4 ล้อ</div></th> <th class="rotate" style="background-color:#de3465;"><div>6 ล้อ</div></th> <th class="rotate" style="background-color:#de3465;"><div>10 ล้อ</div></th> </tr> </thead> <tbody> @php $a = 0; @endphp @foreach($ProjectSchedule as $row) <tr class="border"> <td> <h6>{{ $row->task_name }}</h6><br> <strong>{{ $row->project_name }}</strong><br> <strong>เริ่ม:</strong>{{ $row->start }}<br> <strong>จบ:</strong>{{ $row->finish }} </td> @php $ref_start = DateTime::createFromFormat('Y-m-d H:i:s',$row->start); $ref_end = DateTime::createFromFormat('Y-m-d H:i:s',$row->finish); @endphp @for($i=0;$i<$emp_count+4;$i++) <td style="width:30px;"></td> @endfor @php $a++; @endphp </tr> @endforeach </tbody> </table> </div> </section> <section class="row mt-4 mb-5"> <div class="col-12"> <table width="100%"> <tr> <td style="border: none">หมายเหตุ</td> <td width="95%" style="border-bottom: 1px solid black;"></td> </tr> <tr> <td height="32px" colspan="2" style="border-bottom: 1px solid black;"></td> </tr> <tr> <td height="32px" colspan="2" style="border-bottom: 1px solid black;"></td> </tr> </table> </div> </section> <section class="row"> <div class="col-12"> <table width="100%"> <tr> <td class="text-center">ลายเซ็นต์ _____________________</td> <td class="text-center">ลายเซ็นต์ _____________________</td> </tr> <tr> <td class="text-center">วันที่ _______/_______/________</td> <td class="text-center">วันที่ _______/_______/________</td> </tr> <tr> <td class="text-center">ลูกค้า</td> <td class="text-center">Project Manager</td> </tr> </table> </div> </section> @endsection
bhurivaj/erp
resources/views/Project/pdf/project_schedule.blade.php
PHP
mit
3,610