code stringlengths 4 1.01M |
|---|
namespace Ioke.Lang {
using Ioke.Lang.Util;
using System.Text;
public class Locals {
public static void Init(IokeObject obj) {
obj.Kind = "Locals";
obj.GetMimics().Clear();
obj.SetCell("=", obj.runtime.Base.Cells["="]);
var assgn = IokeObject.As(obj.runtime.DefaultBehavior.Cells["Assignment"], null).Cells;
obj.SetCell("++", assgn["++"]);
obj.SetCell("--", assgn["--"]);
obj.SetCell("+=", assgn["+="]);
obj.SetCell("-=", assgn["-="]);
obj.SetCell("/=", assgn["/="]);
obj.SetCell("*=", assgn["*="]);
obj.SetCell("%=", assgn["%="]);
obj.SetCell("**=", assgn["**="]);
obj.SetCell("&=", assgn["&="]);
obj.SetCell("|=", assgn["|="]);
obj.SetCell("^=", assgn["^="]);
obj.SetCell("<<=", assgn["<<="]);
obj.SetCell(">>=", assgn[">>="]);
obj.SetCell("&&=", assgn["&&="]);
obj.SetCell("||=", assgn["||="]);
obj.SetCell("cell", obj.runtime.Base.Cells["cell"]);
obj.SetCell("cell=", obj.runtime.Base.Cells["cell="]);
obj.SetCell("cells", obj.runtime.Base.Cells["cells"]);
obj.SetCell("cellNames", obj.runtime.Base.Cells["cellNames"]);
obj.SetCell("removeCell!", obj.runtime.Base.Cells["removeCell!"]);
obj.SetCell("undefineCell!", obj.runtime.Base.Cells["undefineCell!"]);
obj.SetCell("cellOwner?", obj.runtime.Base.Cells["cellOwner?"]);
obj.SetCell("cellOwner", obj.runtime.Base.Cells["cellOwner"]);
obj.SetCell("identity", obj.runtime.Base.Cells["identity"]);
obj.RegisterMethod(obj.runtime.NewNativeMethod("will pass along the call to the real self object of this context.",
new NativeMethod("pass", DefaultArgumentsDefinition.builder()
.WithRestUnevaluated("arguments")
.Arguments,
(method, context, message, on, outer) => {
object selfDelegate = IokeObject.As(on, context).Self;
if(selfDelegate != null && selfDelegate != on) {
return IokeObject.Perform(selfDelegate, context, message);
}
return context.runtime.nil;
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("will return a text representation of the current stack trace",
new NativeMethod.WithNoArguments("stackTraceAsText",
(method, context, m, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, m, on);
Runtime runtime = context.runtime;
StringBuilder sb = new StringBuilder();
IokeObject current = IokeObject.As(on, context);
while("Locals".Equals(current.GetKind(m, context))) {
IokeObject message = IokeObject.As(IokeObject.GetCell(current, m, context, "currentMessage"), context);
IokeObject start = message;
while(Message.GetPrev(start) != null && Message.GetPrev(start).Line == message.Line) {
start = Message.GetPrev(start);
}
string s1 = Message.Code(start);
int ix = s1.IndexOf("\n");
if(ix > -1) {
ix--;
}
sb.Append(string.Format(" {0,-48} {1}\n",
(ix == -1 ? s1 : s1.Substring(0,ix)),
"[" + message.File + ":" + message.Line + ":" + message.Position + GetContextMessageName(IokeObject.As(current.Cells["surroundingContext"], context)) + "]"));
current = IokeObject.As(IokeObject.FindCell(current, m, context, "surroundingContext"), context);
}
return runtime.NewText(sb.ToString());
})));
}
public static string GetContextMessageName(IokeObject ctx) {
if("Locals".Equals(ctx.GetKind())) {
return ":in `" + IokeObject.As(ctx.Cells["currentMessage"], ctx).Name + "'";
} else {
return "";
}
}
}
}
|
<div class="copy">
All Rights Reserved <span class='uc'>[uC]</span> 2017
</div> |
module.exports = require('./lib/Redback');
|
import {Component, ElementRef} from '@angular/core';
import { ProductionTileService } from '../../shared/services/productiontile.service';
import { Router } from '@angular/router';
import {Observable} from 'rxjs/Rx';
//import 'style-loader!./tiles.scss';
@Component({
selector: 'production-tiles',
styleUrls: ['./tiles.scss'],
templateUrl: './productiontiles.html'
})
export class ProductionTiles {
productions: Observable<Array<any>>
sub_prod: Observable<Array<any>>
summary:number=0;
constructor(private router: Router, protected service: ProductionTileService) {
}
ngOnInit() {
this.productions = this.service.getProductionTiles().map(response => response.json()["tiles"]);
this.sub_prod=this.productions;
}
button_details(id): void {
this.router.navigate(['pages/productiontiles/details', id]);
}
summary_details(id): void {
this.summary = 1;
document.getElementsByClassName('widgets')['0'].style.display = 'none';
document.getElementById("summary").style.display = 'block';
}
back_state():void{
this.summary = 0;
document.getElementsByClassName('widgets')['0'].style.display = 'block';
document.getElementById("summary").style.display = 'none';
}
} |
#[macro_use]
extern crate nom;
extern crate regex;
#[macro_use]
extern crate log;
#[macro_use]
mod internals;
pub mod types;
pub mod parser; |
<?php
return [
'@class' => 'Grav\\Common\\File\\CompiledYamlFile',
'filename' => 'C:/xampp/htdocs/castledevcms/user/plugins/admin/languages/ar.yaml',
'modified' => 1493044482,
'data' => [
'PLUGIN_ADMIN' => [
'ADMIN_BETA_MSG' => 'هذا إصدار بيتا! استخدم هذا في الإنتاج على مسؤوليتك الخاصة...',
'ADMIN_REPORT_ISSUE' => 'وجدت مشكلة؟ الرجاء الإبلاغ عن GitHub.',
'EMAIL_FOOTER' => '<a href="http://getgrav.org">Powered by Grav</a> - The Modern Flat File CMS',
'LOGIN_BTN' => 'تسجل الدخول',
'LOGIN_BTN_FORGOT' => 'نسيت',
'LOGIN_BTN_RESET' => 'إعادة تعيين كلمة المرور',
'LOGIN_BTN_SEND_INSTRUCTIONS' => 'إرسال إرشادات إعادة تعيين',
'LOGIN_BTN_CLEAR' => 'مسح النموذج',
'LOGIN_BTN_CREATE_USER' => 'أنشاء مستخدم جديد',
'LOGIN_LOGGED_IN' => 'لقد تم تسجيل بنجاح',
'LOGIN_FAILED' => 'فشل تسجيل الخول',
'LOGGED_OUT' => 'لقد قمت بتسجيل الخروج',
'RESET_NEW_PASSWORD' => 'إدخال كلمة سر جديدة رجاءً …',
'RESET_LINK_EXPIRED' => 'انتهت مدة صلاحية إعادة الارتباط، الرجاء المحاولة مرة أخرى',
'RESET_PASSWORD_RESET' => 'لقد تم إعادة تعيين كلمة المرور',
'RESET_INVALID_LINK' => 'اللينك خاطئ ، الرجاء المحاولة مرة أخرى',
'FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL' => 'تم إرسال إرشادات إعادة تعيين كلمة المرور الخاصة بك عبر البريد الإلكتروني إلى %s',
'FORGOT_FAILED_TO_EMAIL' => 'فشل في تعليمات البريد الإلكتروني، الرجاء المحاولة مرة أخرى لاحقاً',
'FORGOT_CANNOT_RESET_EMAIL_NO_EMAIL' => 'لا يمكن إعادة تعيين كلمة المرور ل %s، لم يتم تعيين عنوان البريد الإلكتروني',
'FORGOT_USERNAME_DOES_NOT_EXIST' => 'لا يوجد المستخدم مع اسم المستخدم <b>%s</b>',
'FORGOT_EMAIL_NOT_CONFIGURED' => 'لا يمكن إعادة تعيين كلمة المرور. لم يتم تكوين هذا الموقع لإرسال رسائل البريد الإلكتروني',
'FORGOT_EMAIL_SUBJECT' => 'طلب إعادة تعيين كلمة المرور %s',
'MANAGE_PAGES' => 'إدارة الصفحات',
'PAGES' => 'الصفحات',
'PLUGINS' => 'البرامج الإضافية',
'PLUGIN' => 'البرنامج الإضافي',
'THEMES' => 'المواضيع',
'LOGOUT' => 'تسجيل الخروج',
'BACK' => 'الرجوع',
'ADD_PAGE' => 'إضافة صفحة',
'ADD_MODULAR' => 'إضافة وحدة',
'MOVE' => 'انقل',
'DELETE' => 'حذف',
'SAVE' => 'حفظ',
'NORMAL' => 'عادي',
'EXPERT' => 'خبير',
'EXPAND_ALL' => 'عرض الكل',
'COLLAPSE_ALL' => 'طي الكل',
'ERROR' => 'خطأ',
'CLOSE' => 'أغلق',
'CANCEL' => 'إلغاء',
'CONTINUE' => 'المتابعة',
'MODAL_DELETE_PAGE_CONFIRMATION_REQUIRED_TITLE' => 'التأكيد مطلوب',
'MODAL_CHANGED_DETECTED_TITLE' => 'تم الكشف عن التغييرات',
'MODAL_CHANGED_DETECTED_DESC' => 'وقد تغييرات غير محفوظة. هل أنت متأكد من أنك تريد ترك دون الحفظ؟',
'MODAL_DELETE_FILE_CONFIRMATION_REQUIRED_TITLE' => 'التأكيد مطلوب',
'MODAL_DELETE_FILE_CONFIRMATION_REQUIRED_DESC' => 'هل أنت متأكد من حذف هذا الملف؟ لا يمكن التراجع عن هذا الإجراء.',
'ADD_FILTERS' => 'إضافة عامل تصفية',
'SEARCH_PAGES' => 'صفحات البحث',
'VERSION' => 'النسخة',
'WAS_MADE_WITH' => 'تم عمله مع',
'BY' => 'بواسطة',
'UPDATE_THEME' => 'تحديث الموضوع',
'UPDATE_PLUGIN' => 'تحديث البرنامج الإضافي',
'AUTHOR' => 'المؤلّف',
'HOMEPAGE' => 'الصفحة الرئيسية',
'DEMO' => 'عرض تجريبي',
'BUG_TRACKER' => 'متتبع الأخطاء',
'KEYWORDS' => 'الكلمات الرئيسية',
'LICENSE' => 'الرخصة',
'DESCRIPTION' => 'الوصف',
'README' => 'الملف التمهيدي',
'REMOVE_THEME' => 'إزالة الموضوع',
'INSTALL_THEME' => 'تثبيت الموضوع',
'THEME' => 'الموضوع',
'BACK_TO_THEMES' => 'العودة إلى المواضيع',
'BACK_TO_PLUGINS' => 'العودة إلى البرامج الإضافية',
'CHECK_FOR_UPDATES' => 'التحقق من وجود تحديثات',
'ADD' => 'أَضِف',
'CLEAR_CACHE' => 'مسح ذاكرة التخزين المؤقتة',
'CLEAR_CACHE_IMAGES_ONLY' => 'الصور فقط',
'DASHBOARD' => 'لوحة المعلومات',
'UPDATES_AVAILABLE' => 'تحديثات متوفّرة',
'DAYS' => 'أيام',
'UPDATE' => 'تحديث',
'STATISTICS' => 'إحصائيات',
'TODAY' => 'اليوم',
'WEEK' => 'اسبوع',
'MONTH' => 'شهر',
'MAINTENANCE' => 'الصيانه',
'MON' => 'الإثنين',
'TUE' => 'الثلاثاء',
'WED' => 'الإربعاء',
'THU' => 'الخميس',
'FRI' => 'الجمعة',
'SAT' => 'السبت',
'SUN' => 'الأحد',
'COPY' => 'نسخ',
'EDIT' => 'تحرير',
'CREATE' => 'انشاء'
]
]
];
|
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
namespace Hyperfriendly.WebApi.ErrorHandling
{
public class HyperfriendlyExceptionHandler : ExceptionHandler
{
private readonly ExceptionTransformer _transformer;
public HyperfriendlyExceptionHandler(ExceptionTransformer transformer)
{
_transformer = transformer;
}
public override void Handle(ExceptionHandlerContext context)
{
var errorResponse = _transformer.Transform(context.Exception);
var errorResource = new ErrorResource();
errorResource.Errors.Add(new ErrorEntryResource(errorResponse.Title, errorResponse.Message));
var resp = new HttpResponseMessage(errorResponse.HttpStatusCode)
{
Content = new ObjectContent(typeof(ErrorResource), errorResource, new HyperfriendlyJsonMediaTypeFormatter())
};
context.Result = new HyperfriendlyErrorMessageResult(resp);
}
public class HyperfriendlyErrorMessageResult : IHttpActionResult
{
private readonly HttpResponseMessage _httpResponseMessage;
public HyperfriendlyErrorMessageResult(HttpResponseMessage httpResponseMessage)
{
_httpResponseMessage = httpResponseMessage;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(_httpResponseMessage);
}
}
}
} |
import React, { Component } from 'react';
import CatagoryBox1 from '../CatagoryBox1';
import { BgBox } from './style';
function BackgroundBox (props) {
const {bcolor} = props;
const {data} = props;
const cata = data.map((d,i) => <CatagoryBox1 data={d} key={i} />);
return (
<BgBox bcolor={bcolor}>
{cata}
</BgBox>
);
};
export default BackgroundBox;
|
<?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = [
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AppBundle\AppBundle(),
new WebserviceBundle\WebserviceBundle(),
new FOS\RestBundle\FOSRestBundle(),
new JMS\SerializerBundle\JMSSerializerBundle(),
new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
new Nelmio\CorsBundle\NelmioCorsBundle(),
];
if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function getRootDir()
{
return __DIR__;
}
public function getCacheDir()
{
return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
}
public function getLogDir()
{
return dirname(__DIR__).'/var/logs';
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
}
|
# logparser
A generic log parser that reads in a configuration file before reading logs. The configuration file specifies what information the user is looking for and how to display the information.
This totally doesn't work at all, I barely started it.
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BodeAbp.Scaffolding.Models
{
public enum euColumnType
{
/// <summary>
/// int
/// </summary>
intCT = 0x1
,
/// <summary>
/// decimal
/// </summary>
decimalCT = 0x3
,
/// <summary>
/// decimal
/// </summary>
longCT = 0x5
,
/// <summary>
/// float
/// </summary>
floatCT = 0x7
,
/// <summary>
/// double
/// </summary>
doubleCT = 0x9
,
/// <summary>
/// string
/// </summary>
stringCT = 0x0
,
/// <summary>
/// DateTime
/// </summary>
datetimeCT = 0x2
,
boolCT = 0x4
,
guidCT = 0x10
,
/// <summary>
/// RelatedModel
/// </summary>
RelatedModel = 0x20
}
}
|
var playState = {
create: function(){
var background = game.add.sprite(0, 0, 'cidade');
background.width = 1300;
background.height = 650;
graphics = game.add.graphics(0, 0);
groupCidade = game.add.group();
groupCidade.inputEnableChildren = true;
var x = 100;
for (var i = 0; i < 3; i++){
// Gera os retangulos que ficarão atras das imagens
graphics.beginFill(0xFFFFFF);
graphics.lineStyle(3, 0x05005e, 1);
graphics.drawRoundedRect(x, 200, 315, 190, 10);
graphics.endFill();
var button = groupCidade.create(x, 200, graphics.generateTexture());
button.tint = 0xff8800;
button.name = 'groupCidade-child-' + i;
x = x + 400;
}
graphics.destroy();
var cachorro = game.add.sprite(110, 210, 'cachorro');
cachorro.width = 300;
cachorro.height = 170;
// Desenha o gato e a borda da box
var gato = game.add.sprite(510, 210, 'gato');
gato.width = 300;
gato.height = 170;
// Desenha o passaro e a borda da box
var passaro = game.add.sprite(910, 210, 'passaro');
passaro.width = 300;
passaro.height = 170;
start();
// groupCidade.onChildInputDown.add(onDown, this);
// groupCidade.onChildInputOver.add(onOver, this);
// groupCidade.onChildInputOut.add(onOut, this);
function start(){
}
function onDown (sprite) {
sprite.tint = 0x00ff00;
}
function onOver (sprite) {
sprite.tint = 0xffff00;
}
function onOut (sprite) {
sprite.tint = 0xff8800;
// sprite.tint = Math.random() * 0xffffff;
}
},
update: function(){
},
start: function(int: id){
groupCidade.children[1].tint = 0x000000;
groupCidade.children[2].tint = 0x000000;
gato.tint = 0x000000;
passaro.tint = 0x000000;
background.tint = 0x888888;
},
Win: function(){
game.state.start('win');
}
}; |
/* Google Fonts to use. See the following page for more fonts:
http://cssdeck.com/labs/cool-and-professional-google-web-fonts-for-use
*/
@import url(//fonts.googleapis.com/css?family=Ubuntu);
@import url(//fonts.googleapis.com/css?family=Advent+Pro);
html {
min-height: 100%;
position: relative;
}
body {
/*padding-bottom: 60px;*/
/* This is the same as the sky in background 4, to make the mobile display look better. */
background-color: #376BD0;
background-image: url('../img/background4.jpg');
background-position: center;
background-repeat: no-repeat;
margin: 0px;
padding: 0px;
height: 100%;
width: 100%;
font-family: "Advent Pro", Times, sans-serif;
}
body > .container {
padding: 65px 10px 0;
}
body > .row {
margin: 10px;
}
.easy_text {
color: white;
text-align: center;
background-color:black;
z-index:0;
opacity:0.5;
}
/* About / Header name */
.about {
color: white;
text-align: center;
}
a:link {
}
h1.name {
color: white;
text-align: center;
font-family: "Ubuntu";
font-size: 750%;
}
.black {
background-color: black;
}
object {
width: 100%;
height: 100%;
border: 0;
}
/* Center text with no background. */
.center_text_nohighlight {
color: black;
text-align: center;
font-size: 200%;
}
/* Center text */
.center_text {
color: white;
text-align: center;
font-family: "Advent Pro";
font-weight:900;
font-size: 200%;
}
.center_text_small {
color: white;
text-align: center;
font-family: "Advent Pro";
font-weight:900;
font-size: 120%;
}
/* Highlight just the text. */
.highlight {
background-color: black;
}
/* Left align text */
.left_align {
color: black;
text-align: left;
font-family: "Advent Pro";
font-size: 150%;
}
.content {
width: 70%;
margin: 0px auto;
padding: 0px;
border: 0px;
background-color: transparent;
}
.embed-container {
height: 0;
width: 100%;
padding-bottom: 130%; /* play with this until right */
overflow: hidden;
position: relative;
}
.embed-container iframe {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
} |
version https://git-lfs.github.com/spec/v1
oid sha256:d33a38aa03c6c04c3b54d84dbf40da10270e517a1f2ca5ed32486bd757d16cd0
size 455
|
---
layout: post
title: The doodle
date: 2016-06-24 01:40:00.810Z
description: "Maggie"
---

|
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "vm.h"
ProcessorState * ProcessorState_new() {
// State box for this processor
ProcessorState *new_procstate = (ProcessorState *) malloc(sizeof(ProcessorState));
// Setup the processor
Processor *new_proc = (Processor *) malloc(sizeof(Processor));
memset(new_proc, 0, sizeof(Processor));
new_proc->ra = malloc(LONG_SIZE);
new_proc->rb = malloc(LONG_SIZE);
new_proc->rr = malloc(LONG_SIZE);
new_procstate->processor = new_proc;
return new_procstate;
}
// Iteration functions
byte next_byte(const Program *program, Processor *proc) {
return program->data[proc->pc++];
}
int machine_start(const byte *code, const size_t program_size) {
const Program program = {
code, program_size
};
ProcessorState *cpu_state = ProcessorState_new();
Processor *tcpu = cpu_state->processor;
int retval = 0;
// Timing
struct timespec last_checkin, now;
int perf_counter = 0;
clock_gettime(CLOCK_REALTIME, &last_checkin);
while (tcpu->pc < program_size) {
const byte next_op = next_byte(&program, tcpu);
#ifdef PC_TRACE
printf("PC[%d] -> OPCODE %d\n", cpu_state->processor->pc - 1, next_op);
#endif
switch (next_op) {
case OPCODE_START:
break;
case OPCODE_STOP:
goto EXIT;
case OPCODE_LOAD_BYTE:
register_load_long(program, tcpu, byte);
break;
case OPCODE_LOAD_SHORT:
register_load_long(program, tcpu, short);
break;
case OPCODE_LOAD_INT:
register_load_long(program, tcpu, int);
break;
case OPCODE_LOAD_LONG:
register_load_long(program, tcpu, long);
break;
case OPCODE_LOAD_DOUBLE:
register_load_double(program, tcpu, double);
break;
case OPCODE_JUMP:
memcpy(&tcpu->pc, &program.data[tcpu->pc], REGISTER_SIZE);
break;
case OPCODE_JUMP_IF_ZERO:
if (coerce(tcpu->rr, long) == 0) {
memcpy(&tcpu->pc, &program.data[tcpu->pc], REGISTER_SIZE);
} else {
pc_advance(tcpu, INT_SIZE);
}
break;
case OPCODE_ADD:
memcpy(tcpu->rr, tcpu->ra, REGISTER_SIZE);
coerce(tcpu->rr, long) += coerce(tcpu->rb, long);
break;
case OPCODE_SUBTRACT:
memcpy(tcpu->rr, tcpu->ra, REGISTER_SIZE);
coerce(tcpu->rr, long) -= coerce(tcpu->rb, long);
break;
case OPCODE_PRODUCT:
memcpy(tcpu->rr, tcpu->ra, REGISTER_SIZE);
coerce(tcpu->rr, long) *= coerce(tcpu->rb, long);
break;
case OPCODE_QUOTIENT:
memcpy(tcpu->rr, tcpu->ra, REGISTER_SIZE);
coerce(tcpu->rr, long) /= coerce(tcpu->rb, long);
break;
case OPCODE_DOUBLE_ADD:
memcpy(tcpu->rr, tcpu->ra, REGISTER_SIZE);
coerce(tcpu->rr, double) += coerce(tcpu->rb, double);
break;
case OPCODE_DOUBLE_SUBTRACT:
memcpy(tcpu->rr, tcpu->ra, REGISTER_SIZE);
coerce(tcpu->rr, double) -= coerce(tcpu->rb, double);
break;
case OPCODE_DOUBLE_PRODUCT:
memcpy(tcpu->rr, tcpu->ra, REGISTER_SIZE);
coerce(tcpu->rr, double) *= coerce(tcpu->rb, double);
break;
case OPCODE_DOUBLE_QUOTIENT:
memcpy(tcpu->rr, tcpu->ra, REGISTER_SIZE);
coerce(tcpu->rr, double) /= coerce(tcpu->rb, double);
break;
}
#ifdef PC_TRACE
printf("PC[%d]\n", cpu_state->processor->pc);
#endif
// Timing
if (++perf_counter == PERF_ITERATIONS) {
perf_counter = 0;
clock_gettime(CLOCK_REALTIME, &now);
long difference_in_seconds = now.tv_sec - last_checkin.tv_sec;
long difference_in_nanos = now.tv_nsec - last_checkin.tv_nsec;
if (difference_in_nanos < 0) {
difference_in_seconds--;
difference_in_nanos += SEC_IN_NANOS;
}
printf("Average VM loop runtime %f\n", ((double) difference_in_nanos / (double) PERF_ITERATIONS));
// Copy into the last checkin
last_checkin = now;
}
}
EXIT:
return retval;
} |
using System;
using System.Globalization;
using Newtonsoft.Json;
using HolisticWare.Ph4ct3x.Sports.Judo.InternationalJudoFederation.Internal;
namespace HolisticWare.Ph4ct3x.Sports.Judo.InternationalJudoFederation.Internal
{
public class SearchAllResult
{
[JsonProperty("module")]
public Module Module { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("id")]
[JsonConverter(typeof(ParseStringConverter))]
public long Id { get; set; }
public static SearchAllResult[] FromJson(string json)
=>
JsonConvert.DeserializeObject<SearchAllResult[]>(json, Converter.Settings);
}
public enum Module
{
Competition,
Competitor,
Country,
Weight,
Tags
}
internal class ParseStringConverter : JsonConverter
{
public override bool CanConvert(Type t) => t == typeof(long) || t == typeof(long?);
public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null) return null;
var value = serializer.Deserialize<string>(reader);
long l;
if (Int64.TryParse(value, out l))
{
return l;
}
throw new Exception("Cannot unmarshal type long");
}
public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
{
if (untypedValue == null)
{
serializer.Serialize(writer, null);
return;
}
var value = (long)untypedValue;
serializer.Serialize(writer, value.ToString());
return;
}
public static readonly ParseStringConverter Singleton = new ParseStringConverter();
}
internal class ModuleConverter : JsonConverter
{
public override bool CanConvert(Type t) => t == typeof(Module) || t == typeof(Module?);
public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null) return null;
var value = serializer.Deserialize<string>(reader);
switch (value)
{
case "competition":
return Module.Competition;
case "competitor":
return Module.Competitor;
case "country":
return Module.Country;
case "weight":
return Module.Weight;
case "tags":
return Module.Tags;
}
throw new Exception("Cannot unmarshal type Module");
}
public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
{
if (untypedValue == null)
{
serializer.Serialize(writer, null);
return;
}
var value = (Module)untypedValue;
switch (value)
{
case Module.Competition:
serializer.Serialize(writer, "competition");
return;
case Module.Competitor:
serializer.Serialize(writer, "competitor");
return;
case Module.Country:
serializer.Serialize(writer, "country");
return;
case Module.Tags:
serializer.Serialize(writer, "tags");
return;
case Module.Weight:
serializer.Serialize(writer, "weight");
return;
}
throw new Exception("Cannot marshal type Module");
}
public static readonly ModuleConverter Singleton = new ModuleConverter();
}
}
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Exam Schema
*/
var GroupSchema = new Schema({
group_name: {//分组名称
type: String,
default: ''
},
group_type: { //分组类型
type: String,
default: '',
trim: true
},
group_created:{//分组数据入库时间(时间戳)
type: Date,
default: Date.now
},
group_desc:{//分组的描述
type: String,
default: '',
trim: true
}
});
mongoose.model('Group', GroupSchema); |
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package org
import (
"strings"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/routers/user"
)
const (
SETTINGS_OPTIONS base.TplName = "org/settings/options"
SETTINGS_DELETE base.TplName = "org/settings/delete"
SETTINGS_HOOKS base.TplName = "org/settings/hooks"
)
func Settings(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("org.settings")
ctx.Data["PageIsSettingsOptions"] = true
ctx.HTML(200, SETTINGS_OPTIONS)
}
func SettingsPost(ctx *context.Context, form auth.UpdateOrgSettingForm) {
ctx.Data["Title"] = ctx.Tr("org.settings")
ctx.Data["PageIsSettingsOptions"] = true
if ctx.HasError() {
ctx.HTML(200, SETTINGS_OPTIONS)
return
}
org := ctx.Org.Organization
// Check if organization name has been changed.
if org.LowerName != strings.ToLower(form.Name) {
isExist, err := models.IsUserExist(org.Id, form.Name)
if err != nil {
ctx.Handle(500, "IsUserExist", err)
return
} else if isExist {
ctx.Data["OrgName"] = true
ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SETTINGS_OPTIONS, &form)
return
} else if err = models.ChangeUserName(org, form.Name); err != nil {
if err == models.ErrUserNameIllegal {
ctx.Data["OrgName"] = true
ctx.RenderWithErr(ctx.Tr("form.illegal_username"), SETTINGS_OPTIONS, &form)
} else {
ctx.Handle(500, "ChangeUserName", err)
}
return
}
// reset ctx.org.OrgLink with new name
ctx.Org.OrgLink = setting.AppSubUrl + "/org/" + form.Name
log.Trace("Organization name changed: %s -> %s", org.Name, form.Name)
}
// In case it's just a case change.
org.Name = form.Name
org.LowerName = strings.ToLower(form.Name)
if ctx.User.IsAdmin {
org.MaxRepoCreation = form.MaxRepoCreation
}
org.FullName = form.FullName
org.Description = form.Description
org.Website = form.Website
org.Location = form.Location
if err := models.UpdateUser(org); err != nil {
ctx.Handle(500, "UpdateUser", err)
return
}
log.Trace("Organization setting updated: %s", org.Name)
ctx.Flash.Success(ctx.Tr("org.settings.update_setting_success"))
ctx.Redirect(ctx.Org.OrgLink + "/settings")
}
func SettingsAvatar(ctx *context.Context, form auth.UploadAvatarForm) {
form.Enable = true
if err := user.UpdateAvatarSetting(ctx, form, ctx.Org.Organization); err != nil {
ctx.Flash.Error(err.Error())
} else {
ctx.Flash.Success(ctx.Tr("org.settings.update_avatar_success"))
}
ctx.Redirect(ctx.Org.OrgLink + "/settings")
}
func SettingsDeleteAvatar(ctx *context.Context) {
if err := ctx.Org.Organization.DeleteAvatar(); err != nil {
ctx.Flash.Error(err.Error())
}
ctx.Redirect(ctx.Org.OrgLink + "/settings")
}
func SettingsDelete(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("org.settings")
ctx.Data["PageIsSettingsDelete"] = true
org := ctx.Org.Organization
if ctx.Req.Method == "POST" {
if _, err := models.UserSignIn(ctx.User.Name, ctx.Query("password")); err != nil {
if models.IsErrUserNotExist(err) {
ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_password"), SETTINGS_DELETE, nil)
} else {
ctx.Handle(500, "UserSignIn", err)
}
return
}
if err := models.DeleteOrganization(org); err != nil {
if models.IsErrUserOwnRepos(err) {
ctx.Flash.Error(ctx.Tr("form.org_still_own_repo"))
ctx.Redirect(ctx.Org.OrgLink + "/settings/delete")
} else {
ctx.Handle(500, "DeleteOrganization", err)
}
} else {
log.Trace("Organization deleted: %s", org.Name)
ctx.Redirect(setting.AppSubUrl + "/")
}
return
}
ctx.HTML(200, SETTINGS_DELETE)
}
func Webhooks(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("org.settings")
ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["BaseLink"] = ctx.Org.OrgLink
ctx.Data["Description"] = ctx.Tr("org.settings.hooks_desc")
ws, err := models.GetWebhooksByOrgID(ctx.Org.Organization.Id)
if err != nil {
ctx.Handle(500, "GetWebhooksByOrgId", err)
return
}
ctx.Data["Webhooks"] = ws
ctx.HTML(200, SETTINGS_HOOKS)
}
func DeleteWebhook(ctx *context.Context) {
if err := models.DeleteWebhookByOrgID(ctx.Org.Organization.Id, ctx.QueryInt64("id")); err != nil {
ctx.Flash.Error("DeleteWebhookByOrgID: " + err.Error())
} else {
ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success"))
}
ctx.JSON(200, map[string]interface{}{
"redirect": ctx.Org.OrgLink + "/settings/hooks",
})
}
|
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import fnmatch
import os
import re
import sys
from setuptools import find_packages, setup, Command
from setuptools.command.install import install as InstallCommandBase
from setuptools.dist import Distribution
# This version string is semver compatible, but incompatible with pip.
# For pip, we will remove all '-' characters from this string, and use the
# result for pip.
_VERSION = '1.8.0'
REQUIRED_PACKAGES = [
'absl-py >= 0.1.6',
'astor >= 0.6.0',
'gast >= 0.2.0',
'numpy >= 1.13.3',
'six >= 1.10.0',
'protobuf >= 3.4.0',
'tensorboard >= 1.8.0, < 1.9.0',
'termcolor >= 1.1.0',
]
if sys.byteorder == 'little':
# grpcio does not build correctly on big-endian machines due to lack of
# BoringSSL support.
# See https://github.com/tensorflow/tensorflow/issues/17882.
REQUIRED_PACKAGES.append('grpcio >= 1.8.6')
project_name = 'tensorflow'
if '--project_name' in sys.argv:
project_name_idx = sys.argv.index('--project_name')
project_name = sys.argv[project_name_idx + 1]
sys.argv.remove('--project_name')
sys.argv.pop(project_name_idx)
# python3 requires wheel 0.26
if sys.version_info.major == 3:
REQUIRED_PACKAGES.append('wheel >= 0.26')
else:
REQUIRED_PACKAGES.append('wheel')
# mock comes with unittest.mock for python3, need to install for python2
REQUIRED_PACKAGES.append('mock >= 2.0.0')
# tf-nightly should depend on tb-nightly
if 'tf_nightly' in project_name:
for i, pkg in enumerate(REQUIRED_PACKAGES):
if 'tensorboard' in pkg:
REQUIRED_PACKAGES[i] = 'tb-nightly >= 1.8.0a0, < 1.9.0a0'
break
# weakref.finalize and enum were introduced in Python 3.4
if sys.version_info < (3, 4):
REQUIRED_PACKAGES.append('backports.weakref >= 1.0rc1')
REQUIRED_PACKAGES.append('enum34 >= 1.1.6')
# pylint: disable=line-too-long
CONSOLE_SCRIPTS = [
'freeze_graph = tensorflow.python.tools.freeze_graph:run_main',
'toco_from_protos = tensorflow.contrib.lite.toco.python.toco_from_protos:main',
'toco = tensorflow.contrib.lite.toco.python.toco_wrapper:main',
'saved_model_cli = tensorflow.python.tools.saved_model_cli:main',
# We need to keep the TensorBoard command, even though the console script
# is now declared by the tensorboard pip package. If we remove the
# TensorBoard command, pip will inappropriately remove it during install,
# even though the command is not removed, just moved to a different wheel.
'tensorboard = tensorboard.main:run_main',
]
# pylint: enable=line-too-long
# remove the tensorboard console script if building tf_nightly
if 'tf_nightly' in project_name:
CONSOLE_SCRIPTS.remove('tensorboard = tensorboard.main:run_main')
TEST_PACKAGES = [
'scipy >= 0.15.1',
]
class BinaryDistribution(Distribution):
def has_ext_modules(self):
return True
class InstallCommand(InstallCommandBase):
"""Override the dir where the headers go."""
def finalize_options(self):
ret = InstallCommandBase.finalize_options(self)
self.install_headers = os.path.join(self.install_purelib,
'tensorflow', 'include')
return ret
class InstallHeaders(Command):
"""Override how headers are copied.
The install_headers that comes with setuptools copies all files to
the same directory. But we need the files to be in a specific directory
hierarchy for -I <include_dir> to work correctly.
"""
description = 'install C/C++ header files'
user_options = [('install-dir=', 'd',
'directory to install header files to'),
('force', 'f',
'force installation (overwrite existing files)'),
]
boolean_options = ['force']
def initialize_options(self):
self.install_dir = None
self.force = 0
self.outfiles = []
def finalize_options(self):
self.set_undefined_options('install',
('install_headers', 'install_dir'),
('force', 'force'))
def mkdir_and_copy_file(self, header):
install_dir = os.path.join(self.install_dir, os.path.dirname(header))
# Get rid of some extra intervening directories so we can have fewer
# directories for -I
install_dir = re.sub('/google/protobuf_archive/src', '', install_dir)
# Copy eigen code into tensorflow/include.
# A symlink would do, but the wheel file that gets created ignores
# symlink within the directory hierarchy.
# NOTE(keveman): Figure out how to customize bdist_wheel package so
# we can do the symlink.
if 'external/eigen_archive/' in install_dir:
extra_dir = install_dir.replace('external/eigen_archive', '')
if not os.path.exists(extra_dir):
self.mkpath(extra_dir)
self.copy_file(header, extra_dir)
if not os.path.exists(install_dir):
self.mkpath(install_dir)
return self.copy_file(header, install_dir)
def run(self):
hdrs = self.distribution.headers
if not hdrs:
return
self.mkpath(self.install_dir)
for header in hdrs:
(out, _) = self.mkdir_and_copy_file(header)
self.outfiles.append(out)
def get_inputs(self):
return self.distribution.headers or []
def get_outputs(self):
return self.outfiles
def find_files(pattern, root):
"""Return all the files matching pattern below root dir."""
for path, _, files in os.walk(root):
for filename in fnmatch.filter(files, pattern):
yield os.path.join(path, filename)
matches = ['../' + x for x in find_files('*', 'external') if '.py' not in x]
so_lib_paths = [
i for i in os.listdir('.')
if os.path.isdir(i) and fnmatch.fnmatch(i, '_solib_*')
]
for path in so_lib_paths:
matches.extend(
['../' + x for x in find_files('*', path) if '.py' not in x]
)
if os.name == 'nt':
EXTENSION_NAME = 'python/_pywrap_tensorflow_internal.pyd'
else:
EXTENSION_NAME = 'python/_pywrap_tensorflow_internal.so'
headers = (list(find_files('*.h', 'tensorflow/core')) +
list(find_files('*.h', 'tensorflow/stream_executor')) +
list(find_files('*.h', 'google/protobuf_archive/src')) +
list(find_files('*', 'third_party/eigen3')) +
list(find_files('*', 'external/eigen_archive')))
setup(
name=project_name,
version=_VERSION.replace('-', ''),
description='TensorFlow helps the tensors flow',
long_description='',
url='https://www.tensorflow.org/',
author='Google Inc.',
author_email='opensource@google.com',
# Contained modules and scripts.
packages=find_packages(),
entry_points={
'console_scripts': CONSOLE_SCRIPTS,
},
headers=headers,
install_requires=REQUIRED_PACKAGES,
tests_require=REQUIRED_PACKAGES + TEST_PACKAGES,
# Add in any packaged data.
include_package_data=True,
package_data={
'tensorflow': [
EXTENSION_NAME,
] + matches,
},
zip_safe=False,
distclass=BinaryDistribution,
cmdclass={
'install_headers': InstallHeaders,
'install': InstallCommand,
},
# PyPI package information.
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
],
license='Apache 2.0',
keywords='tensorflow tensor machine learning',)
|
using System.Reflection;
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("SheepAspect.Commons.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("SheepAspect.Commons.Test")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[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("18151f70-e4c1-47e6-ab59-1ade47493be3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.0.15")]
[assembly: AssemblyFileVersion("0.3.0.15")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("TextBox_")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TextBox_")]
[assembly: AssemblyCopyright("Copyright (C) 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントには
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid("050fa39c-6e2b-4483-acf2-7fe4a5788917")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
//-----------------------------------------------------------------------
// <copyright file="Reserve.cs" company="ShareKnowledge">
// Copyright (c) ShareKnowledge. All rights reserved.
// </copyright>
// <author>Alejandro Perdomo</author>
//-----------------------------------------------------------------------
namespace Testing.SingletonPattern.Entity
{
using System.Collections.Generic;
#region Imports
using System.Collections.ObjectModel;
#endregion Imports
public class Reserve
{
#region Properties
public Reserve(Collection<Seat> seats)
{
this.Seats = new ReadOnlyCollection<Seat>(seats);
}
public string Film { get; set; }
public string Function { get; set; }
public ReadOnlyCollection<Seat> Seats { get; }
#endregion Properties
}
}
|
/**
* Example
* @version 0.0.1
*/
var MetaReponse = require('./MetaResponse');
var MetaData = require('./MetaData');
var MetaError = require('./MetaError');
var data1 = new MetaData();
var mr = new MetaReponse();
data1.setId(3);
data1.setType('recipe');
data1.addAttribute('title', 'Risotto al funghi');
data1.addAttribute('time', '45mins');
data1.addLink('self', 'http://www.monsite.com/recipe/3');
data1.addLink('next', 'http://www.monsite.com/recipe/4');
data1.addLink('prev', 'http://www.monsite.com/recipe/2');
mr.addLink('self', 'http://www.monsite.com/');
mr.addLink('next', 'http://www.monsite.com/next');
mr.addData(data1.getResponse());
mr.addData(data1);
console.log(data1.getResponse());
console.log(mr.getResponse());
var error = new MetaError();
error
.setStatusCode(401)
.setStatus("401 Unauthorized");
var response = new MetaReponse();
response.addError(error);
console.log(response.getResponse().errors); |
<?php
// library for using escaped sql
class DB {
protected static $db;
static function getDB() {
return self::$db;
}
// choose database
static function init($databaseName) {
//insert MySQL server, user, password
self/* or DB */::$db = mysqli_connect("yourServer", "yourUser", "yourPassword");
if (self::$db == false) {
throw new Exception("Pripojeni k databazi se nezdarilo. " . mysqli_connect_error());
}
mysqli_set_charset(self::$db, "utf8");
mysqli_select_db(self::$db, $databaseName);
}
// do sql request, if it's not valid - throw exception
// if SELECT - return array of rows
static function doSql($sql) {
$result = mysqli_query(self::$db, $sql);
// wrong sql - false
if ($result === false) {
throw new Exception("Spatny sql: (".$sql.") Err: " . mysqli_error(self::$db));
}
// sql ok, but we don't need any return value (UPDATE, INSERT etc.)
elseif ($result === true) {
} else {
// SELECT - return array of rows
$rows = array();
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
}
// convert value to sql request
static function toSql($value, $notnumeric=FALSE) {
// NULL to 'NULL'
if (is_null($value)) {
return "NULL";
}
// number to string
elseif (is_numeric($value) && !$notnumeric) {
return $value;
}
// escape text and add apostrophes
elseif (is_string($value)) {
$escape = mysqli_real_escape_string(self::$db, $value);
return "'$escape'";
} else {
throw new Exception("Neznamy datovy typ pro prevod do SQL.");
}
}
} |
//=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "dll/neural/lstm/dyn_lstm_layer.hpp"
#include "dll/neural/lstm/lstm_layer_impl.hpp"
#include "dll/neural/lstm/lstm_layer_desc.hpp"
|
# About Kohana Cache
[Kohana_Cache] provides a common interface to a variety of caching engines. [Cache_Tagging] is
supported where available natively to the cache system. Kohana Cache supports multiple
instances of cache engines through a grouped singleton pattern.
## Supported cache engines
* APC ([Cache_Apc])
* File ([Cache_File])
* Memcached ([Cache_Memcache])
* Memcached-tags ([Cache_Memcachetag])
* SQLite ([Cache_Sqlite])
* Wincache
## Introduction to caching
Caching should be implemented with consideration. Generally, caching the result of resources
is faster than reprocessing them. Choosing what, how and when to cache is vital. [PHP APC](http://php.net/manual/en/book.apc.php) is one of the fastest caching systems available, closely followed by [Memcached](http://memcached.org/). [SQLite](http://www.sqlite.org/) and File caching are two of the slowest cache methods, however usually faster than reprocessing
a complex set of instructions.
Caching engines that use memory are considerably faster than file based alternatives. But
memory is limited whereas disk space is plentiful. If caching large datasets, such as large database result sets, it is best to use file caching.
[!!] Cache drivers require the relevant PHP extensions to be installed. APC, eAccelerator, Memecached and Xcache all require non-standard PHP extensions.
## What the Kohana Cache module does (and does not do)
This module provides a simple abstracted interface to a wide selection of popular PHP cache engines. The caching API provides the basic caching methods implemented across all solutions, memory, network or disk based. Basic key / value storing is supported by all drivers, with additional tagging and garbage collection support where implemented or required.
_Kohana Cache_ does not provide HTTP style caching for clients (web browsers) and/or proxies (_Varnish_, _Squid_). There are other Kohana modules that provide this functionality.
## Choosing a cache provider
Getting and setting values to cache is very simple when using the _Kohana Cache_ interface. The hardest choice is choosing which cache engine to use. When choosing a caching engine, the following criteria must be considered:
1. __Does the cache need to be distributed?__
This is an important consideration as it will severely limit the options available to solutions such as Memcache when a distributed solution is required.
2. __Does the cache need to be fast?__
In almost all cases retrieving data from a cache is faster than execution. However generally memory based caching is considerably faster than disk based caching (see table below).
3. __How much cache is required?__
Cache is not endless, and memory based caches are subject to a considerably more limited storage resource.
Driver | Storage | Speed | Tags | Distributed | Automatic Garbage Collection | Notes
---------------- | ------------ | --------- | -------- | ----------- | ---------------------------- | -----------------------
APC | __Memory__ | Excellent | No | No | Yes | Widely available PHP opcode caching solution, improves php execution performance
Wincache | __Memory__ | Excellent | No | No | Yes | Windows variant of APC
File | __Disk__ | Poor | No | No | No | Marginally faster than execution
Memcache (tag) | __Memory__ | Good | No (yes) | Yes | Yes | Generally fast distributed solution, but has a speed hit due to variable network latency and serialization
Sqlite | __Disk__ | Poor | Yes | No | No | Marginally faster than execution
It is possible to have hybrid cache solutions that use a combination of the engines above in different contexts. This is supported with _Kohana Cache_ as well
## Minimum requirements
* Kohana 3.0.4
* PHP 5.2.4 or greater |
import { Class as Model } from 'meteor/jagi:astronomy';
import * as Errors from './errors.js';
export function init(config) {
config.collection = new Mongo.Collection(config.collectionName);
config.model = Model.create({
name: config.modelName,
collection: config.collection,
fields: config.modelFields,
});
config.saveMethod = 'save' + config.modelName;
config.removeMethod = 'remove' + config.modelName;
var methods = {};
methods[config.saveMethod] = saveDoc;
methods[config.removeMethod] = removeDoc;
Meteor.methods(methods);
let colFieldsFunc = function () {
result = [];
for (var i = 0; i < config.formFields.length; i++) {
if (config.formFields[i].colClass) {
result[i] = config.formFields[i];
}
}
return result;
}
config.colFields = colFieldsFunc();
}
export function saveDoc (doc) {
if ( !Meteor.userId() ) {
return;
}
try {
doc.save();
} catch (e) {
Errors.handle(e);
}
}
export function removeDoc (doc) {
if ( !Meteor.userId() ) {
return;
}
doc.remove();
} |
~~~ {.html #id .codeclass}
<b>bold</b>
~~~
|
"use strict";
/* tslint:disable */
var load_themed_styles_1 = require("@microsoft/load-themed-styles");
var styles = {};
load_themed_styles_1.loadStyles([{ "rawString": ".ms-FocusTrapZoneBoxExample{border:dashed 1px #ababab}.ms-FocusTrapComponent{border:#000 2px solid;padding:5px}" }]);
module.exports = styles;
/* tslint:enable */
//# sourceMappingURL=FocusTrapZone.Box.Example.scss.js.map
|
export default function VuxTableColumnDefinition (options) {
return {
...{
key: 'id',
label: 'Id',
isDisabled: false,
isHidden: false,
isSortable: false,
isSorting: false,
sortDirection: 'desc',
isFilterable: false,
displayComponent: null,
editComponent: null,
span: 1
},
...options
}
}
|
/*
UrchinTSS
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// Note: This code was derived from the TCG TPM 2.0 Library Specification at
// http://www.trustedcomputinggroup.org/resources/tpm_library_specification
#include "stdafx.h"
UINT16
TPM2_Startup_Marshal(
SESSION *sessionTable,
UINT32 sessionCnt,
Marshal_Parms *parms,
BYTE **buffer,
INT32 *size
)
{
if((parms == NULL) ||
// (parms->objectCntIn < TPM2_Startup_HdlCntIn) ||
(parms->objectCntOut < TPM2_Startup_HdlCntOut) ||
(parms->parmIn == NULL) ||
(parms->parmOut == NULL))
{
return TPM_RC_FAILURE;
}
return Command_Marshal(
TPM_CC_Startup,
sessionTable,
sessionCnt,
TPM2_Startup_Parameter_Marshal,
parms,
buffer,
size);
}
TPM_RC
TPM2_Startup_Unmarshal(
SESSION *sessionTable,
UINT32 sessionCnt,
Marshal_Parms *parms,
BYTE **buffer,
INT32 *size
)
{
TPM_RC result = TPM_RC_SUCCESS;
// Startup_In *in = (Startup_In *)parms->parmIn;
// Startup_Out *out = (Startup_Out *)parms->parmOut;
if((parms == NULL) ||
// (parms->objectCntIn < TPM2_Startup_HdlCntIn) ||
(parms->objectCntOut < TPM2_Startup_HdlCntOut) ||
(parms->parmIn == NULL) ||
(parms->parmOut == NULL))
{
return TPM_RC_FAILURE;
}
if((result = Command_Unmarshal(
TPM_CC_Startup,
sessionTable,
sessionCnt,
TPM2_Startup_Parameter_Unmarshal,
parms,
buffer,
size)) == TPM_RC_SUCCESS)
{
}
return result;
}
UINT16
TPM2_Startup_Parameter_Marshal(
Marshal_Parms *parms,
BYTE **buffer,
INT32 *size
)
{
Startup_In *in = (Startup_In *)parms->parmIn;
// Startup_Out *out = (Startup_Out *)parms->parmOut;
UINT16 parameterSize = 0;
// Create the parameter buffer
parameterSize += TPM_SU_Marshal(&in->startupType, buffer, size);
if(size < 0) return TPM_RC_SIZE;
return parameterSize;
}
TPM_RC
TPM2_Startup_Parameter_Unmarshal(
Marshal_Parms *parms,
BYTE **buffer,
INT32 *size
)
{
TPM_RC result = TPM_RC_SUCCESS;
// Startup_In *in = (Startup_In *)parms->parmIn;
// Startup_Out *out = (Startup_Out *)parms->parmOut;
// Unmarshal the parameters
UNREFERENCED_PARAMETER(parms);
UNREFERENCED_PARAMETER(buffer);
UNREFERENCED_PARAMETER(size);
return result;
}
|
/*******************************************************************************
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package com.ibm.wala.demandpa.alg;
import com.ibm.wala.demandpa.alg.statemachine.StateMachine;
import com.ibm.wala.demandpa.alg.statemachine.StateMachineFactory;
import com.ibm.wala.demandpa.flowgraph.AbstractFlowLabelVisitor;
import com.ibm.wala.demandpa.flowgraph.IFlowLabel;
import com.ibm.wala.demandpa.flowgraph.ParamBarLabel;
import com.ibm.wala.demandpa.flowgraph.ParamLabel;
import com.ibm.wala.demandpa.flowgraph.ReturnBarLabel;
import com.ibm.wala.demandpa.flowgraph.ReturnLabel;
/**
* State machine that only allows intraprocedural paths. Mainly for testing
* purposes.
*
* @author Manu Sridharan
*
*/
public class IntraProcFilter implements StateMachine<IFlowLabel> {
private static final State DUMMY = new State() {
};
@Override
public State getStartState() {
return DUMMY;
}
private static class InterprocFilterVisitor extends AbstractFlowLabelVisitor {
@Override
public void visitParamBar(ParamBarLabel label, Object dst) {
interprocEdge = true;
}
@Override
public void visitParam(ParamLabel label, Object dst) {
interprocEdge = true;
}
@Override
public void visitReturn(ReturnLabel label, Object dst) {
interprocEdge = true;
}
@Override
public void visitReturnBar(ReturnBarLabel label, Object dst) {
interprocEdge = true;
}
boolean interprocEdge = false;
}
@Override
public State transition(State prevState, IFlowLabel label) throws IllegalArgumentException {
if (label == null) {
throw new IllegalArgumentException("label == null");
}
// filter out all interprocedural edges
InterprocFilterVisitor v = new InterprocFilterVisitor();
label.visit(v, null);
return v.interprocEdge ? ERROR : DUMMY;
}
private IntraProcFilter() {
}
public static class Factory implements StateMachineFactory<IFlowLabel> {
@Override
public StateMachine<IFlowLabel> make() {
return new IntraProcFilter();
}
}
}
|
# frozen_string_literal: true
require 'spec_helper'
shared_examples_for 'AtomicInternalId' do |validate_presence: true|
describe '.has_internal_id' do
describe 'Module inclusion' do
subject { described_class }
it { is_expected.to include_module(AtomicInternalId) }
end
describe 'Validation' do
before do
allow_any_instance_of(described_class).to receive(:"ensure_#{scope}_#{internal_id_attribute}!")
instance.valid?
end
context 'when presence validation is required' do
before do
skip unless validate_presence
end
it 'validates presence' do
expect(instance.errors[internal_id_attribute]).to include("can't be blank")
end
end
context 'when presence validation is not required' do
before do
skip if validate_presence
end
it 'does not validate presence' do
expect(instance.errors[internal_id_attribute]).to be_empty
end
end
end
describe 'Creating an instance' do
subject { instance.save! }
it 'saves a new instance properly' do
expect { subject }.not_to raise_error
end
end
describe 'internal id generation' do
subject { instance.save! }
it 'calls InternalId.generate_next and sets internal id attribute' do
iid = rand(1..1000)
expect(InternalId).to receive(:generate_next).with(instance, scope_attrs, usage, any_args).and_return(iid)
subject
expect(read_internal_id).to eq(iid)
end
it 'does not overwrite an existing internal id' do
write_internal_id(4711)
expect { subject }.not_to change { read_internal_id }
end
context 'when the instance has an internal ID set' do
let(:internal_id) { 9001 }
it 'calls InternalId.update_last_value and sets the `last_value` to that of the instance' do
write_internal_id(internal_id)
expect(InternalId)
.to receive(:track_greatest)
.with(instance, scope_attrs, usage, internal_id, any_args)
.and_return(internal_id)
subject
end
end
end
describe "#reset_scope_internal_id_attribute" do
it 'rewinds the allocated IID' do
expect { ensure_scope_attribute! }.not_to raise_error
expect(read_internal_id).not_to be_nil
expect(reset_scope_attribute).to be_nil
expect(read_internal_id).to be_nil
end
it 'allocates the same IID' do
internal_id = ensure_scope_attribute!
reset_scope_attribute
expect(read_internal_id).to be_nil
expect(ensure_scope_attribute!).to eq(internal_id)
end
end
def ensure_scope_attribute!
instance.public_send(:"ensure_#{scope}_#{internal_id_attribute}!")
end
def reset_scope_attribute
instance.public_send(:"reset_#{scope}_#{internal_id_attribute}")
end
def read_internal_id
instance.public_send(internal_id_attribute)
end
def write_internal_id(value)
instance.public_send(:"#{internal_id_attribute}=", value)
end
end
end
|
#ifdef DEBUG
#if(DEBUG)
#define DBGPRINTF(...) fprintf(stderr,__VA_ARGS__);
#else
#define DBGPRINTF(...) 0
#endif
#endif
|
<?php
@ini_set("display_errors","1");
@ini_set("display_startup_errors","1");
require_once("include/dbcommon.php");
$table = postvalue("table");
if (!checkTableName($table))
{
exit(0);
}
require_once("include/".$table."_variables.php");
if((!isLogged() || !CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Search")) && @$_GET["action"]<>"add")
{
return;
}
$ptype = postvalue("ptype");
$field = postvalue("field");
$pSet = new ProjectSettings($strTableName, $ptype);
if(!$pSet->checkFieldPermissions($field) && @$_GET["action"] <> "add")
return;
$_connection = $cman->byTable( $strTableName );
// construct sql
$data = false;
if(@$_GET["action"] <> "add")
{
$keysArr = $pSet->getTableKeys();
$keys = array();
foreach ($keysArr as $ind=>$k)
{
$keys[$k]=postvalue("key".($ind+1));
}
$where = KeyWhere($keys);
if ($pSet->getAdvancedSecurityType() == ADVSECURITY_VIEW_OWN)
{
$where = whereAdd($where,SecuritySQL("Search", $strTableName));
}
$sql = $gQuery->gSQLWhere($where);
$qResult = $_connection->query( $sql );
if(!$qResult)
return;
$data = $qResult->fetchAssoc();
}
else
{
$data = array();
$data[$field] = @$_SESSION[$strTableName."_".$field."_rte"];
}
$nWidth = $pSet->getNCols($field);
$nHeight = $pSet->getNRows($field);
$id = postvalue("id");
$cfield = "value_".GoodFieldName($field)."_".($id!=='' ? $id : '1');
if(@$_REQUEST["browser"]=="ie")
$onsubmit = "onsubmit=\"updateRTEs();\"";
else
$onsubmit = "onsubmit=\"updateRTEs();return this.elements['".$cfield."'].value;\"";
echo "<html><body style=\"margin:0;\"><form name=\"rteform\" ".$onsubmit.">";
echo "<script type=\"text/javascript\" src=\"".GetRootPathForResources("include/rte/richtext.js")."\"></script>\r\n";
echo "<script language=\"JavaScript\" type=\"text/javascript\">";
echo "initRTE('include/rte/images/', 'include/rte/', '');\r\n";
echo "{var rte = new richTextEditor('".$cfield."');";
echo "rte.width= ".$nWidth.";";
echo "rte.height= ".$nHeight.";";
echo "rte.html = '";
if($data && $data[$field] != null)
echo jsreplace($data[$field]);
echo "';";
echo "rte.build();}";
echo "</script>";
echo "</form></body></html>";
return;
?>
|
---
layout: post
title: Request Routing
categories: magento-certification-notes request-flow
---
##Describe request routing/request flow in Magento
https://up.kibakoapp.com/QXvgswmXcs
Once the Magento application has instantiated front controller and matched a router in the database it should be able to match the URL to a module controller and action name. This action will instantiate a layout object which is defined in layout XML. The layout XML will define which blocks to use and start rendering content, Blocks refer directly to models for their data and sometimes helpers.
##Describe how Magento determines which controller to use and how to customize route-to-controller resolution
Magento checks the `core_url_rewrite` database to find a match for the route or a router may be added during the events fired. Magento then references the configuration XML to find a match or the route. The naming convention for this is `{base_url}/{front_name}/{controller_name}/{action_name}/{other_params}`.
Starting with the front controller delegating the process of mapping a request to a controller action, study the steps that occur until a controller action is dispatched.
###Which routers exist in a native Magento implementation?
- admin
- Process Admin Scope Requests
- `Mage_Core_Controller_Varien_Router_Admin`
- standard
- Process Front-end Scope Requests
- `Mage_Core_Controller_Varien_Router_Standard`
- custom
- CMS Pages for example
- default
- Process no-route action, 404 Page
- `Mage_Core_Controller_Varien_Router_Default`
###How does the standard router map a request to a controller class?
If there is no module specified in the url (in the case of the base URL only) it will use default from config `Mage::getStoreConfig('web/default/front');` which is mapped to a cms page, usually the homepage. You could also access this page by accessing `{base_url}/cms/index/index`.
`{base_url}/{front_name}/{controller_name}/{action_name}/{other_params}`.
###How does the standard router build the filesystem path to a file that might contain a matching action controller?
- `{base_url}/{front_name}/{controller_name}/{action_name}/{other_params}`
###How does Magento process requests that cannot be mapped?
Magento will fall back to the default router class `Mage_Core_Controller_Varien_Router_Default` and throw a 404 error, this is defined in configuration.
###After a matching action controller is found, what steps occur before the action method is executed?
- Module, Controller and Action names are reset to the found module ones. Also SetControllerModule is set to the found module name
- URL params are added to the request
- the request is set to dispatch to true
Mage_Core_Controller_Varien_Router_Standard->match(()
These code references can be used as an entry point to find answers to the questions above:
- `Mage_Core_Controller_Varien_Front::init()`
- `Mage_Core_Controller_Varien_Router_Standard::collectRoutes()` and `match()`
|
/*
Algorithm for Influence Estimation and Maximization
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <vector>
#include <iostream>
#include "SharedMemoryManager.h"
#include "FancyProgressBar.h"
#include "FileSize.h"
#include "GraphStream.h"
#include "Conversion.h"
#include "Split.h"
using namespace std;
namespace RawData {
// Build a metis graph directly into a fast unweighted graph.
template<typename graphType>
void BuildMetisGraph(const string inFilename, graphType &outGraph, const bool ignoreSelfLoops, const bool transpose, const bool directed, const bool buildIncomingArcs, const bool removeParallelArcs, const bool verbose) {
typedef typename graphType::VertexIdType vertexIdType;
// Get the file size of the input filestream.
Types::SizeType fileSize = IO::FileSize(inFilename);
// Open the input file as a stream.
IO::FileStream inStream;
inStream.OpenForReading(inFilename);
// Create timer and progress bar.
if (verbose) cout << "Streaming from " << inFilename << " (" << (fileSize / 1024.0 / 1024.0) << " MiB): " << endl;
Tools::FancyProgressBar bar(fileSize, "", verbose);
// Read the file line-by-line.
string line;
uint64_t lineNumber = 0;
bool headerParsed = false;
vector<const char*> tokens;
vertexIdType numVertices = 0;
Types::SizeType numArcs = 0;
vertexIdType fromVertexId = 0;
typedef pair<vertexIdType, vertexIdType> arcType;
vector<arcType> arcs;
// Read line-by-line.
while (!inStream.Finished()) {
inStream.ExtractLine(line);
++lineNumber;
bar.IterateTo(inStream.NumBytesRead());
// Skip lines that begin with a %-symbol.
if (line[0] == '%') continue;
// The header contains the number of vertices and arcs.
if (!headerParsed) {
// Skip empty lines.
if (line.empty()) continue;
// Parse the header.
Tools::DynamicSplitInline(line, tokens, ' ');
// We need at least two tokens for the file format to be correct.
Assert(tokens.size() >= 2);
// The first token indicates the number of vertices.
numVertices = Tools::LexicalCast<vertexIdType>(tokens[0]);
headerParsed = true;
}
else {
if (!line.empty()) {
// Parse head vertices.
Tools::DynamicSplitInline(line, tokens, ' ');
// Go over the tokens, and add an arc for each (that is non-empty).
for (size_t i = 0; i < tokens.size(); ++i) {
if (strlen(tokens[i]) == 0) continue;
typename graphType::VertexIdType toVertexId = Tools::LexicalCast<typename graphType::VertexIdType>(tokens[i]);
--toVertexId; // In the text file vertex ids are one-based.
Assert(fromVertexId < numVertices);
Assert(toVertexId < numVertices);
if (ignoreSelfLoops && fromVertexId == toVertexId)
continue;
if (transpose) {
if (directed || toVertexId <= fromVertexId)
arcs.push_back(arcType(toVertexId, fromVertexId));
}
else {
if (directed || fromVertexId <= toVertexId)
arcs.push_back(arcType(fromVertexId, toVertexId));
}
}
}
// The tail vertices are actually consecutive and zero-based.
++fromVertexId;
}
}
bar.Finish();
// Remove parallel arcs?
if (removeParallelArcs) {
if (verbose) cout << "Removing parallel arcs... " << flush;
sort(arcs.begin(), arcs.end(), [](const arcType &a, const arcType &b) {
if (a.first == b.first)
return a.second < b.second;
else
return a.first < b.first;
});
arcs.erase(unique(arcs.begin(), arcs.end()), arcs.end());
if (verbose) cout << "done." << endl;
}
if (verbose) cout << endl;
// Determine identifier.
const string identifier = Platform::SharedMemoryManager::GetIdentifierFromFilename(inFilename);
// Build the graph.
outGraph.BuildFromArcList(identifier, numVertices, arcs, directed, buildIncomingArcs, verbose);
}
// Stream a graph.
template<typename graphType>
void StreamMetisGraph(const string inFilename, const string outFilename, const bool ignoreSelfLoops, const bool undirected, const bool transpose, const bool verbose) {
// Get the file size of the input filestream.
Types::SizeType fileSize = IO::FileSize(inFilename);
// Define the type of the out stream.
typedef IO::GraphStream<graphType> graphStreamType;
// Open the input file as a stream.
IO::FileStream inStream;
inStream.OpenForReading(inFilename);
// Create a new graph stream.
graphStreamType outStream;
outStream.New(outFilename);
outStream.SetDirectedness(!undirected);
// Create timer and progress bar.
cout << "Streaming from " << inFilename << " (" << (fileSize / 1024.0 / 1024.0) << " MiB): " << endl;
Tools::FancyProgressBar bar(fileSize, "", verbose);
// Read the file line-by-line.
string line;
uint64_t lineNumber = 0;
bool headerParsed = false;
vector<const char*> tokens;
Types::SizeType numVertices = 0;
typename graphType::VertexIdType fromVertexId = 0;
// Read line-by-line.
while (!inStream.Finished()) {
inStream.ExtractLine(line);
++lineNumber;
bar.IterateTo(inStream.NumBytesRead());
// Skip lines that begin with a %-symbol.
if (line[0] == '%') continue;
// The header contains the number of vertices and arcs.
if (!headerParsed) {
// Skip empty lines.
if (line.empty()) continue;
// Parse the header.
Tools::DynamicSplitInline(line, tokens, ' ');
// We need at least two tokens for the file format to be correct.
Assert(tokens.size() >= 2);
// The first token indicates the number of vertices.
numVertices = Tools::LexicalCast<Types::SizeType>(tokens[0]);
outStream.SetNumVertices(numVertices);
headerParsed = true;
} else {
if (!line.empty()) {
// Parse head vertices.
Tools::DynamicSplitInline(line, tokens, ' ');
// Go over the tokens, and add an arc for each (that is non-empty).
for (size_t i = 0; i < tokens.size(); ++i) {
if (strlen(tokens[i]) == 0) continue;
typename graphType::VertexIdType toVertexId = Tools::LexicalCast<typename graphType::VertexIdType>(tokens[i]);
--toVertexId; // In the text file vertex ids are one-based.
Assert(fromVertexId < numVertices);
Assert(toVertexId < numVertices);
if (ignoreSelfLoops && fromVertexId == toVertexId)
continue;
if (transpose) {
if (!undirected || toVertexId <= fromVertexId)
outStream.AddArc(toVertexId, fromVertexId, typename graphType::ArcMetaDataType(1));
}
else {
if (!undirected || fromVertexId <= toVertexId)
outStream.AddArc(fromVertexId, toVertexId, typename graphType::ArcMetaDataType(1));
}
}
}
// The tail vertices are actually consecutive and zero-based.
++fromVertexId;
}
}
bar.Finish();
// Close graph stream.
outStream.Close();
// Dump statistics.
if (verbose) outStream.DumpStatistics(cout);
}
} |
.pure-danger{
background: red;
}
.right{
float: right;
}
/* Put your CSS here */
.inlineblock{
display: inline-block;
}
.loading{
background-image: url("../images/loader.gif");
background-color: #fffffff;
display: inline-block;
width: 32px;
height: 32px;
}
.footer{
position: fixed;
bottom: 0;
height: 50px;
width: 100%;
z-index: 4;
}
.footer a{
color: #1F8DD6;
}
#outlet{
margin: 70px 0;
}
.page{
margin: 15px;
}
a[data-toggle]{
color: #1F8DD6;
text-decoration: none;
}
a[data-toggle].active{
color: black;
text-decoration: underline;
}
[data-toggle-id]{
display: none;
}
[data-toggle-id].active{
display: block;
}
textarea.editor{
min-height: 300px;
height: 70%;
width: 100%;
}
/* Breadcrumbs Styles */
.breadcrumb {
list-style: none;
overflow: hidden;
font: 18px;
position: fixed;
top: 38px;
background: gray;
z-index: 6;
width: 100%;
padding: 0px;
}
.breadcrumb li {
float: left;
}
.breadcrumb li a {
color: white;
text-decoration: none;
padding: 0px 0 0px 40px;
background: #2d3e50; /* fallback color */
background: hsla(204, 75%, 48%,1);
position: relative;
display: block;
float: left;
}
.breadcrumb li a:after {
content: " ";
display: block;
width: 0;
height: 0;
border-top: 50px solid transparent; /* Go big on the size, and let overflow hide */
border-bottom: 50px solid transparent;
border-left: 30px solid hsla(204, 75%, 48%,1);
position: absolute;
top: 50%;
margin-top: -50px;
left: 100%;
z-index: 2;
}
.breadcrumb li a:before {
content: " ";
display: block;
width: 0;
height: 0;
border-top: 50px solid transparent; /* Go big on the size, and let overflow hide */
border-bottom: 50px solid transparent;
border-left: 30px solid white;
position: absolute;
top: 50%;
margin-top: -50px;
margin-left: 1px;
left: 100%;
z-index: 1;
}
.breadcrumb li:first-child a {
padding-left: 10px;
}
/*
.breadcrumb li:nth-child(2) a { background: hsla(34,85%,45%,1); }
.breadcrumb li:nth-child(2) a:after { border-left-color: hsla(34,85%,45%,1); }
.breadcrumb li:nth-child(3) a { background: hsla(34,85%,55%,1); }
.breadcrumb li:nth-child(3) a:after { border-left-color: hsla(34,85%,55%,1); }
.breadcrumb li:nth-child(4) a { background: hsla(34,85%,65%,1); }
.breadcrumb li:nth-child(4) a:after { border-left-color: hsla(34,85%,65%,1); }
.breadcrumb li:nth-child(5) a { background: hsla(34,85%,75%,1); }
.breadcrumb li:nth-child(5) a:after { border-left-color: hsla(34,85%,75%,1); }
*/
.breadcrumb li:last-child a {
background: transparent !important;
color: white;
pointer-events: none;
cursor: default;
}
.breadcrumb li:last-child a:after {
border: 0;
}
.breadcrumb li:last-child a:before {
border: 0;
}
.breadcrumb li a:hover {
background: hsla(211, 28%, 25%,1);
}
.breadcrumb li a:hover:after {
border-left-color: hsla(211, 28%, 25%,1) !important;
}
.page.w-breadcrumb{
margin-top: 90px;
}
/*
ul.breadcrumb {
position: fixed;
top: 39px;
background: silver;
z-index: 6;
width: 100%;
list-style: none;
margin: 0;
padding: 0;
}
ul.breadcrumb li {
margin: 0;
padding: 0;
float: left;
}
ul.breadcrumb li a {
background: white;
display: inline-block;
padding: 0px 5px;
border: 1px solid silver;
text-decoration: none;
color: black;
}
ul.breadcrumb li a:hover{
background: gray;
color: white;
}
.page.w-breadcrumb{
margin-top: 80px;
}
*/
/* Switches */
.editswitch {
font-size: 16px;
font-weight: normal;
position: relative; width: 90px;
-webkit-user-select:none;
-moz-user-select:none;
-ms-user-select: none;
}
.editswitch-checkbox {
position: absolute;
left: -999px;
top: -999px;
}
.editswitch-label {
display: block;
overflow: hidden;
cursor: pointer;
border: 2px solid #cccccc;
border-radius: 0px;
height: 30px;
}
.editswitch-inner {
width: 200%; margin-left: -100%;
-moz-transition: margin 0.3s ease-in 0s;
-webkit-transition: margin 0.3s ease-in 0s;
-o-transition: margin 0.3s ease-in 0s;
transition: margin 0.3s ease-in 0s;
}
.editswitch-inner:before, .editswitch-inner:after {
float: left;
width: 50%;
height: 30px;
padding: 0;
line-height: 26px;
font-size: 14px;
color: white;
font-family: Trebuchet, Arial, sans-serif; font-weight: bold;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box; box-sizing: border-box;
border: 2px solid transparent;
background-clip: padding-box;
}
.editswitch-inner .on {
padding-left: 10px;
background-color: #1F8DD6;
color: #FFFFFF;
width: 90px;
display: inline-block;
}
.editswitch-inner .off {
padding-right: 10px;
background-color: #999999;
color: #FFFFFF;
text-align: right;
position: relative;
top: -27px;
left: 86px;
display: inline-block;
height: 27px;
width: 90px;
}
.editswitch-switch {
width: 25px;
margin: 0px;
background: #CCCCCC;
position: absolute;
top: 0;
bottom: 0;
right: 65px;
-moz-transition: all 0.3s ease-in 0s; -webkit-transition: all 0.3s ease-in 0s;
-o-transition: all 0.3s ease-in 0s; transition: all 0.3s ease-in 0s;
}
.editswitch-checkbox:checked + .editswitch-label .editswitch-inner {
margin-left: 0;
}
.editswitch-checkbox:checked + .editswitch-label .editswitch-switch {
right: 0px;
} |
<?php
return array(
'modules' => array(
'LammStorage',
'LammRedis',
),
'module_listener_options' => array(
'config_glob_paths' => array('../../../config/autoload/{,*.}{global,local}.php'),
'module_paths' => array('module','vendor'),
),
);
|
Plugins
=========
Each one of the following CUDA programs can be generated in two ways:
- as a dynamic shared object (*.so files): `make plugins` (or simply `make`)
- as a standalone program: `make executables`
The difference between them is that the standalone programs take their parameters through ARGV, while the *.so files must be loaded, set and run through the Plugin Engine (`../gpgpu`)
matrix.so
----
Default parameters:
```
matrix:
PARAM NAME => PARAM_VALUE
inputFileMatrixA => inputFileMatrixA.txt
inputFileMatrixB => inputFileMatrixB.txt
OutputFileMatrixC => OutputFileMatrixC.txt
displayResult => 0
```
prime.so
----
Default parameters:
```
prime:
PARAM NAME => PARAM_VALUE
outputFile => prime_numbers.txt
limit => 101
```
graph.so
-----------
Default parameters:
```
graph:
PARAM NAME => PARAM_VALUE
searchMode => bfs
inputFile => inputGraph.txt
outputFile => resultGraph.txt
sourceNode => 0
displayResult => 1
```
|
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2016 Francois Beaune, The appleseedhq Organization
//
// 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.
//
#ifndef APPLESEED_FOUNDATION_UTILITY_COMMANDLINEPARSER_FLAGOPTIONHANDLER_H
#define APPLESEED_FOUNDATION_UTILITY_COMMANDLINEPARSER_FLAGOPTIONHANDLER_H
// appleseed.foundation headers.
#include "foundation/platform/compiler.h"
#include "foundation/utility/commandlineparser/messagelist.h"
#include "foundation/utility/commandlineparser/optionhandler.h"
#include "foundation/utility/commandlineparser/parseresults.h"
#include "foundation/utility/log.h"
// Standard headers.
#include <cassert>
#include <cstddef>
#include <string>
namespace foundation
{
//
// Flag option handler.
//
class FlagOptionHandler
: public OptionHandler
{
private:
// Return the maximum number of values this option can handle.
virtual size_t get_max_value_count() const APPLESEED_OVERRIDE;
// Parse a vector of values.
virtual void parse(
const std::string& name,
const StringVector& values,
ParseResults& results) APPLESEED_OVERRIDE;
// Print this option to a string.
virtual void print(std::string& s) const APPLESEED_OVERRIDE;
};
//
// FlagOptionHandler class implementation.
//
inline size_t FlagOptionHandler::get_max_value_count() const
{
return 0;
}
inline void FlagOptionHandler::parse(
const std::string& name,
const StringVector& values,
ParseResults& results)
{
assert(values.empty());
if ((m_flags & OptionHandler::Repeatable) == 0 && m_occurrence_count == 1)
{
// Error: option already specified.
results.m_messages.add(
LogMessage::Error,
"flag '%s' already specified, ignoring all extra occurrences.",
name.c_str());
++results.m_errors;
++m_occurrence_count;
return;
}
// The option was successfully parsed.
++m_occurrence_count;
}
inline void FlagOptionHandler::print(std::string& s) const
{
// Print the first name of the option.
s += m_names.front();
}
} // namespace foundation
#endif // !APPLESEED_FOUNDATION_UTILITY_COMMANDLINEPARSER_FLAGOPTIONHANDLER_H
|
#include "stdafx.h"
#include "Help.h"
namespace LiteCppDB_Console_Commands
{
DataAccess Help::getAccess() noexcept
{
return DataAccess::None;
}
bool Help::IsCommand(LiteCppDB::StringScanner& s) noexcept
{
return s.Scan("help[[:s:]]*").length() > 0;
}
void Help::Execute(LiteCppDB::LiteEngine engine, LiteCppDB::StringScanner& s, LiteCppDB_Console::Display d, LiteCppDB_Console::InputCommand input, LiteCppDB_Console::Env env) noexcept
{
const auto full = s.Match("full");
if (!full)
{
d.WriteHelp();
d.WriteHelp("Basic Shell Commands - try `help full` for all commands");
d.WriteHelp("=======================================================");
d.WriteHelp("> open <filename>|<connectionString>", "Open/Crete a new database");
d.WriteHelp("> show collections", "List all collections inside database");
d.WriteHelp("> db.<collection>.insert <jsonDoc>", "Insert a new document into collection");
d.WriteHelp("> db.<collection>.update <jsonDoc>", "Update a document inside collection");
d.WriteHelp("> db.<collection>.delete <filter>", "Delete documents using a filter clausule (see find)");
d.WriteHelp("> db.<collection>.find <filter> [skip N][limit N]", "Show filtered documents based on index search");
d.WriteHelp("> db.<collection>.count <filter>", "Show count rows according query filter");
d.WriteHelp("> db.<collection>.ensureIndex <field> [true|{options}]", "Create a new index document field. For unique key, use true");
d.WriteHelp("> db.<collection>.indexes", "List all indexes in this collection");
d.WriteHelp("<filter> = <field> [=|>|>=|<|<=|!=|like|between] <jsonValue>", "Filter query syntax");
d.WriteHelp("<filter> = (<filter> [and|or] <filter> [and|or] ...)", "Multi queries syntax");
d.WriteHelp("Try:");
d.WriteHelp(" > db.customers.insert { _id:1, name:\"John Doe\", age: 37 }");
d.WriteHelp(" > db.customers.ensureIndex name");
d.WriteHelp(" > db.customers.find name like \"John\"");
d.WriteHelp(" > db.customers.find name like \"John\" and _id between [0, 100] limit 10");
}
else
{
d.WriteHelp("Shell commands");
d.WriteHelp("==============");
d.WriteHelp("> open <filename>|<connectionString>", "Open a new database");
d.WriteHelp("> run <filename>", "Run commands inside filename");
d.WriteHelp("> pretty on|off", "Turns on/off pretty json format");
d.WriteHelp("> timer", "Show timer before prompt");
d.WriteHelp("> ed", "Open notepad with last command to edit and execute");
d.WriteHelp("> spool on|off", "Spool all output in a spool file");
d.WriteHelp("> -- comment", "Do nothing, its just a comment");
d.WriteHelp("> /<command>/", "Support for multi line command");
d.WriteHelp("> debug on|off", "Enabled debug messages from dbengine");
d.WriteHelp("> upgrade <connectionString>", "Upgrade an old datafile (LiteDB v2) to new LiteDB v3 format.");
d.WriteHelp("> version", "Show LiteDB version");
d.WriteHelp("> exit", "Close LiteDB shell");
d.WriteHelp();
d.WriteHelp("Collections commands");
d.WriteHelp("====================");
d.WriteHelp("> show collections", "List all collections inside database");
d.WriteHelp("> db.<collection>.insert <jsonDoc>", "Insert a new document into collection");
d.WriteHelp("> db.<collection>.update <jsonDoc>", "Update a document inside collection");
d.WriteHelp("> db.<collection>.delete <filter>", "Delete documents using a filter clausule (see find)");
d.WriteHelp("> db.<collection>.bulk <filename>", "Bulk insert a json file as documents");
d.WriteHelp("> db.<collection>.find [skip N][limit N]", "Show all documents. Can limit/skip results");
d.WriteHelp("> db.<collection>.find <filter> [skip N][limit N]", "Show filtered documents based on index search. See <filter> syntax below");
d.WriteHelp("> db.<collection>.count <filter>", "Show count rows according query filter");
d.WriteHelp("> db.<collection>.ensureIndex <field> [unique]", "Create a new index document field");
d.WriteHelp("> db.<collection>.indexes", "List all indexes in this collection");
d.WriteHelp("> db.<collection>.drop", "Drop collection and destroy all documents inside");
d.WriteHelp("> db.<collection>.dropIndex <field>", "Drop a index and make index area free to use with another index");
d.WriteHelp("> db.<collection>.rename <newCollectionName>", "Rename a collection");
d.WriteHelp("> db.<collection>.min <field>", "Returns min/first value from collection using index field");
d.WriteHelp("> db.<collection>.max <field>", "Returns max/last value from collection using index field");
d.WriteHelp("<filter> = <field> [=|>|>=|<|<=|!=|like|contains|in|between] <jsonValue>", "Filter query syntax");
d.WriteHelp("<filter> = (<filter> [and|or] <filter> [and|or] ...)", "Multi queries syntax");
d.WriteHelp("<jsonDoc> = {_id: ... , key: value, key1: value1 }", "Represent a json (extended version) for a BsonDocument. See special data types");
d.WriteHelp("Json Date", "{ field: { $date :\"2015-01-01T23:59:59Z\"} }");
d.WriteHelp("Json Guid", "{ field: { $guid :\"3a1c34b3-9f66-4d8e-975a-d545d898a4ba\"} }");
d.WriteHelp("Json Int64", "{ field: { $numberLong :\"1234556788997\"} }");
d.WriteHelp("Json Decimal", "{ field: { $numberDecimal :\"123.456789\"} }");
d.WriteHelp("Json Binary", "{ field: { $binary :\"base64 byte array\"} }");
d.WriteHelp();
d.WriteHelp("File storage commands");
d.WriteHelp("=====================");
d.WriteHelp("> fs.find", "List all files on database");
d.WriteHelp("> fs.find <fileId>", "List file info from a key. Supports * for starts with key");
d.WriteHelp("> fs.upload <fileId> <filename>", "Insert a new file inside database");
d.WriteHelp("> fs.download <fileId> <filename>", "Save a file to disk passing a file key and filename");
d.WriteHelp("> fs.update <fileId> {key:value}", "Update metadata file");
d.WriteHelp("> fs.delete <fileId>", "Remove a file inside database");
d.WriteHelp();
d.WriteHelp("Other commands");
d.WriteHelp("==============");
d.WriteHelp("> db.userversion [N]", "Get/Set user database file version");
d.WriteHelp("> db.shrink [password]", "Reduce database removing empty pages and change password (optional)");
}
}
} |
package zfs_test
import (
"fmt"
"path/filepath"
"github.com/cerana/cerana/acomm"
zfsp "github.com/cerana/cerana/providers/zfs"
)
func (s *zfs) TestGet() {
tests := []struct {
args *zfsp.CommonArgs
err string
}{
{&zfsp.CommonArgs{Name: ""}, "missing arg: name"},
{&zfsp.CommonArgs{Name: "ds_no_exist"}, enoent},
{&zfsp.CommonArgs{Name: "fs"}, ""},
{&zfsp.CommonArgs{Name: "fs/1snap@snap"}, ""},
{&zfsp.CommonArgs{Name: "vol/1snap"}, ""},
}
for _, test := range tests {
if test.args.Name != "" {
test.args.Name = filepath.Join(s.pool, test.args.Name)
}
argsS := fmt.Sprintf("%+v", test.args)
req, err := acomm.NewRequest(acomm.RequestOptions{
Task: "zfs-get",
ResponseHook: s.responseHook,
Args: test.args,
})
s.Require().NoError(err, argsS)
res, streamURL, err := s.zfs.Get(req)
s.Empty(streamURL, argsS)
if test.err == "" {
s.NoError(err, argsS)
if !s.NotNil(res, argsS) {
continue
}
result, ok := res.(*zfsp.DatasetResult)
if !s.True(ok) {
continue
}
if !s.NotNil(result.Dataset) {
continue
}
s.Equal(test.args.Name, result.Dataset.Name, argsS)
} else {
s.Nil(res, argsS)
s.EqualError(err, test.err, argsS)
}
}
}
|
# docker-rustfmt
Docker image for rustfmt
|
//
// SBAppDelegate.h
// SBLibrary
//
// Created by NguyenTran on 08/24/2017.
// Copyright (c) 2017 NguyenTran. All rights reserved.
//
@import UIKit;
@interface SBAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
Silex Web Profiler Provider
===========================
A Silex Service and Controller provider to make use of Symfony's Web Profiler.
This is very Alpha, not to be depended on.
Contributing
------------
Get in touch before hacking on anything, I've no idea what I might be doing, the
whole library may have changed since my last push :)
Copyright
---------
Copyright (c) 2012 Dave Marshall. See LICENCE for further details
|
## Bookmarks tagged [[game-development]](https://www.codever.land/search?q=[game-development])
_<sup><sup>[www.codever.land/bookmarks/t/game-development](https://www.codever.land/bookmarks/t/game-development)</sup></sup>_
---
#### [SiegeLord/RustAllegro](https://github.com/SiegeLord/RustAllegro)
_<sup>https://github.com/SiegeLord/RustAllegro</sup>_
[Allegro 5](https://liballeg.org/) bindings [<img src="https://api.travis-ci.org/SiegeLord/RustAllegro.svg?branch=master">](https://travis-ci.org/SiegeLord/RustAllegro)
* **tags**: [rust](../tagged/rust.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/SiegeLord/RustAllegro)**
---
#### [lucidscape/corange-rs](https://github.com/lucidscape/corange-rs)
_<sup>https://github.com/lucidscape/corange-rs</sup>_
[Corange](https://github.com/orangeduck/Corange) bindings
* **tags**: [rust](../tagged/rust.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/lucidscape/corange-rs)**
---
#### [slide-rs/specs](https://github.com/slide-rs/specs)
_<sup>https://github.com/slide-rs/specs</sup>_
Specs Parallel ECS [<img src="https://api.travis-ci.org/slide-rs/specs.svg">](httpsL//github.com/travis-ci.org/slide-rs/specs)
* **tags**: [rust](../tagged/rust.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/slide-rs/specs)**
---
#### [Amethyst](https://amethyst.rs)
_<sup>https://amethyst.rs</sup>_
Data-oriented game engine [<img src="https://jenkins.amethyst-engine.org/job/amethyst/job/master/badge/icon">](https://jenkins.amethyst-engine.org/blue/organizations/jenkins/amethyst/activity/)
* **tags**: [rust](../tagged/rust.md), [game-development](../tagged/game-development.md)
---
#### [Piston](https://www.piston.rs/)
_<sup>https://www.piston.rs/</sup>_
[<img src="https://api.travis-ci.org/PistonDevelopers/piston.svg?branch=master">](https://travis-ci.org/PistonDevelopers/piston)
* **tags**: [rust](../tagged/rust.md), [game-development](../tagged/game-development.md)
---
#### [ggez](https://github.com/ggez/ggez)
_<sup>https://github.com/ggez/ggez</sup>_
A lightweight game framework for making 2D games with minimum friction [<img src="https://api.travis-ci.org/ggez/ggez.svg?branch=master">](https://travis-ci.org/ggez/ggez)
* **tags**: [rust](../tagged/rust.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/ggez/ggez)**
---
#### [Kiss3D](http://kiss3d.org/)
_<sup>http://kiss3d.org/</sup>_
A Keep It Simple, Stupid 3d graphics engine written with Rust
* **tags**: [rust](../tagged/rust.md), [game-development](../tagged/game-development.md)
---
#### [Unrust](https://github.com/unrust/unrust)
_<sup>https://github.com/unrust/unrust</sup>_
unrust — A pure rust based (webgl 2.0 / native) game engine
* **tags**: [rust](../tagged/rust.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/unrust/unrust)**
---
#### [Vulkust](https://github.com/Hossein-Noroozpour/vulkust)
_<sup>https://github.com/Hossein-Noroozpour/vulkust</sup>_
Vulkust — A safe, highly multithreaded, Vulkan based game engine written with Rust.
* **tags**: [rust](../tagged/rust.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/Hossein-Noroozpour/vulkust)**
---
#### [brson/rust-sdl](https://github.com/brson/rust-sdl)
_<sup>https://github.com/brson/rust-sdl</sup>_
SDL1 bindings [<img src="https://api.travis-ci.org/brson/rust-sdl.svg?branch=master">](https://travis-ci.org/brson/rust-sdl)
* **tags**: [rust](../tagged/rust.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/brson/rust-sdl)**
---
#### [Rust-SDL2/rust-sdl2](https://github.com/Rust-SDL2/rust-sdl2)
_<sup>https://github.com/Rust-SDL2/rust-sdl2</sup>_
SDL2 bindings [<img src="https://api.travis-ci.org/Rust-SDL2/rust-sdl2.svg?branch=master">](https://travis-ci.org/Rust-SDL2/rust-sdl2)
* **tags**: [rust](../tagged/rust.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/Rust-SDL2/rust-sdl2)**
---
#### [jeremyletang/rust-sfml](https://github.com/jeremyletang/rust-sfml)
_<sup>https://github.com/jeremyletang/rust-sfml</sup>_
[SFML](https://www.sfml-dev.org/) bindings [<img src="https://api.travis-ci.org/jeremyletang/rust-sfml.svg?branch=master">](https://travis-ci.org/jeremyletang/rust-sfml)
* **tags**: [rust](../tagged/rust.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/jeremyletang/rust-sfml)**
---
#### [tomassedovic/tcod-rs](https://github.com/tomassedovic/tcod-rs)
_<sup>https://github.com/tomassedovic/tcod-rs</sup>_
Libtcod bindings for Rust.
* **tags**: [rust](../tagged/rust.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/tomassedovic/tcod-rs)**
---
#### [bbodi/rust-voxlap](https://github.com/bbodi/rust-voxlap)
_<sup>https://github.com/bbodi/rust-voxlap</sup>_
[Voxlap](http://advsys.net/ken/voxlap.htm) bindings
* **tags**: [rust](../tagged/rust.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/bbodi/rust-voxlap)**
---
#### [Azul3D](https://github.com/azul3d/engine)
_<sup>https://github.com/azul3d/engine</sup>_
3D game engine written in Go.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/azul3d/engine)**
---
#### [Ebiten](https://github.com/hajimehoshi/ebiten)
_<sup>https://github.com/hajimehoshi/ebiten</sup>_
dead simple 2D game library in Go.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/hajimehoshi/ebiten)**
---
#### [engo](https://github.com/EngoEngine/engo)
_<sup>https://github.com/EngoEngine/engo</sup>_
Engo is an open-source 2D game engine written in Go. It follows the Entity-Component-System paradigm.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/EngoEngine/engo)**
---
#### [g3n](https://github.com/g3n/engine)
_<sup>https://github.com/g3n/engine</sup>_
Go 3D Game Engine.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/g3n/engine)**
---
#### [GarageEngine](https://github.com/vova616/GarageEngine)
_<sup>https://github.com/vova616/GarageEngine</sup>_
2d game engine written in Go working on OpenGL.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/vova616/GarageEngine)**
---
#### [glop](https://github.com/runningwild/glop)
_<sup>https://github.com/runningwild/glop</sup>_
Glop (Game Library Of Power) is a fairly simple cross-platform game library.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/runningwild/glop)**
---
#### [go-astar](https://github.com/beefsack/go-astar)
_<sup>https://github.com/beefsack/go-astar</sup>_
Go implementation of the A\* path finding algorithm.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/beefsack/go-astar)**
---
#### [go-collada](https://github.com/GlenKelley/go-collada)
_<sup>https://github.com/GlenKelley/go-collada</sup>_
Go package for working with the Collada file format.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/GlenKelley/go-collada)**
---
#### [go-sdl2](https://github.com/veandco/go-sdl2)
_<sup>https://github.com/veandco/go-sdl2</sup>_
Go bindings for the [Simple DirectMedia Layer](https://www.libsdl.org/).
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/veandco/go-sdl2)**
---
#### [go3d](https://github.com/ungerik/go3d)
_<sup>https://github.com/ungerik/go3d</sup>_
Performance oriented 2D/3D math package for Go.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/ungerik/go3d)**
---
#### [gonet](https://github.com/xtaci/gonet)
_<sup>https://github.com/xtaci/gonet</sup>_
Game server skeleton implemented with golang.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/xtaci/gonet)**
---
#### [goworld](https://github.com/xiaonanln/goworld)
_<sup>https://github.com/xiaonanln/goworld</sup>_
Scalable game server engine, featuring space-entity framework and hot-swapping.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/xiaonanln/goworld)**
---
#### [Leaf](https://github.com/name5566/leaf)
_<sup>https://github.com/name5566/leaf</sup>_
Lightweight game server framework.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/name5566/leaf)**
---
#### [nano](https://github.com/lonng/nano)
_<sup>https://github.com/lonng/nano</sup>_
Lightweight, facility, high performance golang based game server framework.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/lonng/nano)**
---
#### [Oak](https://github.com/oakmound/oak)
_<sup>https://github.com/oakmound/oak</sup>_
Pure Go game engine.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/oakmound/oak)**
---
#### [Pitaya](https://github.com/topfreegames/pitaya)
_<sup>https://github.com/topfreegames/pitaya</sup>_
Scalable game server framework with clustering support and client libraries for iOS, Android, Unity and others through the C SDK.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/topfreegames/pitaya)**
---
#### [Pixel](https://github.com/faiface/pixel)
_<sup>https://github.com/faiface/pixel</sup>_
Hand-crafted 2D game library in Go.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/faiface/pixel)**
---
#### [raylib-go](https://github.com/gen2brain/raylib-go)
_<sup>https://github.com/gen2brain/raylib-go</sup>_
Go bindings for [raylib](http://www.raylib.com/), a simple and easy-to-use library to learn videogames programming.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/gen2brain/raylib-go)**
---
#### [termloop](https://github.com/JoelOtter/termloop)
_<sup>https://github.com/JoelOtter/termloop</sup>_
Terminal-based game engine for Go, built on top of Termbox.
* **tags**: [go](../tagged/go.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/JoelOtter/termloop)**
---
#### [Gosu](http://www.libgosu.org)
_<sup>http://www.libgosu.org</sup>_
A 2D game development library for the Ruby and C++ programming languages.
* **tags**: [ruby](../tagged/ruby.md), [game-development](../tagged/game-development.md)
---
#### [Yeah](https://github.com/yeahrb/yeah)
_<sup>https://github.com/yeahrb/yeah</sup>_
Practical Ruby video game framework.
* **tags**: [ruby](../tagged/ruby.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/yeahrb/yeah)**
---
#### [Cocos2d](http://cocos2d.org/)
_<sup>http://cocos2d.org/</sup>_
cocos2d is a framework for building 2D games, demos, and other graphical/interactive applications. It is based on pyglet.
* **tags**: [python](../tagged/python.md), [game-development](../tagged/game-development.md)
---
#### [Harfang3D](http://www.harfang3d.com)
_<sup>http://www.harfang3d.com</sup>_
Python framework for 3D, VR and game development. Manage and display complex 3D scenes, with physics, video, sound and music, access VR devices. All written in C++.
* **tags**: [python](../tagged/python.md), [game-development](../tagged/game-development.md)
---
#### [Panda3D](https://www.panda3d.org/)
_<sup>https://www.panda3d.org/</sup>_
3D game engine developed by Disney and maintained by Carnegie Mellon's Entertainment Technology Center. Written in C++, completely wrapped in Python.
* **tags**: [python](../tagged/python.md), [game-development](../tagged/game-development.md)
---
#### [Pygame](http://www.pygame.org/news.html)
_<sup>http://www.pygame.org/news.html</sup>_
Pygame is a set of Python modules designed for writing games.
* **tags**: [python](../tagged/python.md), [game-development](../tagged/game-development.md)
---
#### [PyOgre](http://www.ogre3d.org/tikiwiki/PyOgre)
_<sup>http://www.ogre3d.org/tikiwiki/PyOgre</sup>_
Python bindings for the Ogre 3D render engine, can be used for games, simulations, anything 3D.
* **tags**: [python](../tagged/python.md), [game-development](../tagged/game-development.md)
---
#### [PyOpenGL](http://pyopengl.sourceforge.net/)
_<sup>http://pyopengl.sourceforge.net/</sup>_
Python ctypes bindings for OpenGL and it's related APIs.
* **tags**: [python](../tagged/python.md), [game-development](../tagged/game-development.md)
---
#### [PySDL2](https://pysdl2.readthedocs.io)
_<sup>https://pysdl2.readthedocs.io</sup>_
A ctypes based wrapper for the SDL2 library.
* **tags**: [python](../tagged/python.md), [game-development](../tagged/game-development.md)
---
#### [RenPy](https://www.renpy.org/)
_<sup>https://www.renpy.org/</sup>_
A Visual Novel engine.
* **tags**: [python](../tagged/python.md), [game-development](../tagged/game-development.md)
---
#### [FXGL](https://almasb.github.io/FXGL)
_<sup>https://almasb.github.io/FXGL</sup>_
JavaFX Game Development Framework.
* **tags**: [java](../tagged/java.md), [game-development](../tagged/game-development.md)
---
#### [jMonkeyEngine](http://jmonkeyengine.org)
_<sup>http://jmonkeyengine.org</sup>_
Game engine for modern 3D development.
* **tags**: [java](../tagged/java.md), [game-development](../tagged/game-development.md)
---
#### [libGDX](https://libgdx.badlogicgames.com)
_<sup>https://libgdx.badlogicgames.com</sup>_
All-round cross-platform, high-level framework.
* **tags**: [java](../tagged/java.md), [game-development](../tagged/game-development.md)
---
#### [LWJGL](https://www.lwjgl.org)
_<sup>https://www.lwjgl.org</sup>_
Robust framework that abstracts libraries like OpenGL/CL/AL.
* **tags**: [java](../tagged/java.md), [game-development](../tagged/game-development.md)
---
#### [awesome-magictools](https://github.com/ellisonleao/magictools#readme)
_<sup>https://github.com/ellisonleao/magictools#readme</sup>_
:video_game: :pencil: A list of Game Development resources to make magic happen. - ellisonleao/magictools
* **tags**: [awesome-list](../tagged/awesome-list.md), [game-development](../tagged/game-development.md)
* :octocat: **[source code](https://github.com/ellisonleao/magictools#readme)**
---
#### [awesome-Awesome-Game-Networking](https://github.com/MFatihMAR/Awesome-Game-Networking#readme)
_<sup>https://github.com/MFatihMAR/Awesome-Game-Networking#readme</sup>_
A Curated List of Game Network Programming Resources - MFatihMAR/Awesome-Game-Networking
* **tags**: [awesome-list](../tagged/awesome-list.md), [game-development](../tagged/game-development.md), [networking](../tagged/networking.md)
* :octocat: **[source code](https://github.com/MFatihMAR/Awesome-Game-Networking#readme)**
---
#### [awesome-gametalks](https://github.com/hzoo/awesome-gametalks#readme)
_<sup>https://github.com/hzoo/awesome-gametalks#readme</sup>_
:speech_balloon: A curated list of gaming talks (development, design, etc) - hzoo/awesome-gametalks
* **tags**: [awesome-list](../tagged/awesome-list.md), [game-development](../tagged/game-development.md), [talk](../tagged/talk.md)
* :octocat: **[source code](https://github.com/hzoo/awesome-gametalks#readme)**
---
#### [awesome-godot](https://github.com/Calinou/awesome-godot#readme)
_<sup>https://github.com/Calinou/awesome-godot#readme</sup>_
A curated list of free/libre plugins, scripts and add-ons for Godot - Calinou/awesome-godot
* **tags**: [awesome-list](../tagged/awesome-list.md), [game-development](../tagged/game-development.md), [godot](../tagged/godot.md)
* :octocat: **[source code](https://github.com/Calinou/awesome-godot#readme)**
---
#### [awesome-games](https://github.com/leereilly/games#readme)
_<sup>https://github.com/leereilly/games#readme</sup>_
:video_game: A list of popular/awesome videos games, add-ons, maps, etc. hosted on GitHub. Any genre. Any platform. Any engine. - leereilly/games
* **tags**: [awesome-list](../tagged/awesome-list.md), [game-development](../tagged/game-development.md), [open-source](../tagged/open-source.md)
* :octocat: **[source code](https://github.com/leereilly/games#readme)**
---
#### [awesome-unity](https://github.com/RyanNielson/awesome-unity#readme)
_<sup>https://github.com/RyanNielson/awesome-unity#readme</sup>_
A curated list of awesome Unity assets, resources, and more. - RyanNielson/awesome-unity
* **tags**: [awesome-list](../tagged/awesome-list.md), [game-development](../tagged/game-development.md), [unity](../tagged/unity.md)
* :octocat: **[source code](https://github.com/RyanNielson/awesome-unity#readme)**
---
#### [awesome-chess](https://github.com/hkirat/awesome-chess#readme)
_<sup>https://github.com/hkirat/awesome-chess#readme</sup>_
Chess! Contribute to hkirat/awesome-chess development by creating an account on GitHub.
* **tags**: [awesome-list](../tagged/awesome-list.md), [game-development](../tagged/game-development.md), [chess](../tagged/chess.md)
* :octocat: **[source code](https://github.com/hkirat/awesome-chess#readme)**
---
#### [awesome-love2d](https://github.com/love2d-community/awesome-love2d#readme)
_<sup>https://github.com/love2d-community/awesome-love2d#readme</sup>_
A curated list of amazingly awesome LÖVE libraries, resources and shiny things. - love2d-community/awesome-love2d
* **tags**: [awesome-list](../tagged/awesome-list.md), [game-development](../tagged/game-development.md), [löve](../tagged/löve.md)
* :octocat: **[source code](https://github.com/love2d-community/awesome-love2d#readme)**
---
#### [awesome-PICO-8](https://github.com/pico-8/awesome-PICO-8#readme)
_<sup>https://github.com/pico-8/awesome-PICO-8#readme</sup>_
A curated list of awesome PICO-8 resources, carts, tools and more - pico-8/awesome-PICO-8
* **tags**: [awesome-list](../tagged/awesome-list.md), [game-development](../tagged/game-development.md), [pico-8](../tagged/pico-8.md)
* :octocat: **[source code](https://github.com/pico-8/awesome-PICO-8#readme)**
---
#### [awesome-gbdev](https://github.com/gbdev/awesome-gbdev#readme)
_<sup>https://github.com/gbdev/awesome-gbdev#readme</sup>_
A curated list of Game Boy development resources such as tools, docs, emulators, related projects and open-source ROMs. - gbdev/awesome-gbdev
* **tags**: [awesome-list](../tagged/awesome-list.md), [game-development](../tagged/game-development.md), [gameboy](../tagged/gameboy.md)
* :octocat: **[source code](https://github.com/gbdev/awesome-gbdev#readme)**
---
#### [awesome-construct](https://github.com/WebCreationClub/awesome-construct#readme)
_<sup>https://github.com/WebCreationClub/awesome-construct#readme</sup>_
A curated list of tools, tutorials, examples, and much more, for the awesome game development engines Construct 2 and Construct 3 - WebCreationClub/awesome-construct
* **tags**: [awesome-list](../tagged/awesome-list.md), [game-development](../tagged/game-development.md), [construct-2](../tagged/construct-2.md)
* :octocat: **[source code](https://github.com/WebCreationClub/awesome-construct#readme)**
---
#### [awesome-gideros](https://github.com/stetso/awesome-gideros#readme)
_<sup>https://github.com/stetso/awesome-gideros#readme</sup>_
A curated list of awesome Gideros resources, classes and tips. - stetso/awesome-gideros
* **tags**: [awesome-list](../tagged/awesome-list.md), [game-development](../tagged/game-development.md), [gideros](../tagged/gideros.md)
* :octocat: **[source code](https://github.com/stetso/awesome-gideros#readme)**
---
#### [awesome-minecraft](https://github.com/bs-community/awesome-minecraft#readme)
_<sup>https://github.com/bs-community/awesome-minecraft#readme</sup>_
📝 The curated list of awesome things related to Minecraft. - bs-community/awesome-minecraft
* **tags**: [awesome-list](../tagged/awesome-list.md), [game-development](../tagged/game-development.md), [minecraft](../tagged/minecraft.md)
* :octocat: **[source code](https://github.com/bs-community/awesome-minecraft#readme)**
---
|
- https://twitter.com/zubkou/lists/flow/members
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div>
<?php echo validation_errors(); ?>
<?php if (isset($error)) : ?>
<div>
<?= $error ?>
</div>
<?php endif; ?>
<?= form_open('user/register') ?>
<div>
<label for="username">Username</label>
<input type="text" id="username" name="username" value = "<?php set_value('username'); ?>" placeholder="Enter a username">
</div>
<div>
<label for="email">Email</label>
<input type="email" id="email" name="email" value = "<?php set_value('email'); ?>" placeholder="Enter your email">
<p>A valid email address</p>
</div>
<div>
<input type="submit" value="Register">
</div>
</form>
</div>
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12).
//
// Copyright (C) 1997-2019 Steve Nygard.
//
#import <IDEKit/IDENavigableItemDomainProvider.h>
@interface IDENavigableItemSourceControlDomainProvider : IDENavigableItemDomainProvider
{
}
+ (id)domainObjectForWorkspace:(id)arg1;
@end
|
#if UNIT_TEST_PROG == true
#include "tests/unit_tests.hpp"
#endif
#include <utility>
#include "common/global/program_data.hpp"
#include "menus/budget_menu.hpp"
namespace
{
global::program_data load_program_data();
int start_prog();
/**
* @brief Returns a global::program_data that is initialized to program defaults.
* This function will also be the place where the data is loaded from files,
* should program_data be loaded from a file in the future.
* @return the default program data.
*/
inline global::program_data load_program_data()
{
//a place for future initialization, should that be added.
global::program_data pdat;
pdat.budget_files = std::move(global::budget_paths(pdat.budget_folder));
return pdat;
}
__attribute__((unused)) inline int start_prog()
{
global::program_data pdat(std::move(load_program_data()));
return !menu::budget_list_menu(pdat);
}
}
int main(int count __attribute__((unused)), char **vec __attribute__((unused)))
{
#if UNIT_TEST_PROG == true
run_tests();
return 0;
#else
return start_prog();
#endif
}
|
<?php
namespace EPFL\Menus\CLI;
if (! defined( 'ABSPATH' )) {
die( 'Access denied.' );
}
use \WP_CLI;
use \WP_CLI_Command;
require_once(dirname(__DIR__) . '/lib/i18n.php');
use function EPFL\I18N\___;
require_once(__DIR__ . '/epfl-menus.php');
use \EPFL\Menus\ExternalMenuItem;
class EPFLMenusCLICommand extends WP_CLI_Command
{
public static function hook () {
WP_CLI::add_command('epfl-menus', get_called_class());
}
public function refresh () {
WP_CLI::log(___('Enumerating menus on filesystem...'));
$local = ExternalMenuItem::load_from_filesystem();
WP_CLI::log(sprintf(___('... Success, found %d local menus'),
count($local)));
WP_CLI::log(___('Enumerating menus in config file...'));
$local = ExternalMenuItem::load_from_config_file();
WP_CLI::log(sprintf(___('... Success, found %d site-configured menus'),
count($local)));
$all = ExternalMenuItem::all();
WP_CLI::log(sprintf(___('Refreshing %d instances...'),
count($all)));
foreach ($all as $emi) {
try {
$emi->refresh();
WP_CLI::log(sprintf(___('✓ %s'), $emi));
} catch (\Throwable $t) {
WP_CLI::log(sprintf(___('\u001b[31m✗ %s\u001b[0m'), $emi));
}
}
}
/**
* @example wp epfl-menus add_external_menu_item --menu-location-slug=top urn:epfl:labs "laboratoires"
*/
public function add_external_menu_item ($args, $assoc_args) {
list($urn, $title) = $args;
$menu_location_slug = $assoc_args['menu-location-slug'];
if (!empty($menu_location_slug)) $menu_location_slug = "top";
# todo: check that params is format urn:epfl
WP_CLI::log(___('Add a new external menu item...'));
$external_menu_item = ExternalMenuItem::get_or_create($urn);
$external_menu_item->set_title($title);
$external_menu_item->meta()->set_remote_slug($menu_location_slug);
$external_menu_item->meta()->set_items_json('[]');
WP_CLI::log(sprintf(___('External menu item ID %d...'),$external_menu_item->ID));
}
}
EPFLMenusCLICommand::hook();
|
package compilerapi
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
)
const (
GoogleEndpointUrl = "http://closure-compiler.appspot.com/compile"
)
// See https://developers.google.com/closure/compiler/docs/api-ref for details about the options
type Client struct {
// Possible values: ECMASCRIPT3, ECMASCRIPT5, ECMASCRIPT5_STRICT, default to ECMASCRIPT5_STRICT
Language string
// Possible values: WHITESPACE_ONLY, SIMPLE_OPTIMIZATIONS, ADVANCED_OPTIMIZATIONS, default to WHITESPACE_ONLY
CompilationLevel string
}
type OutputError struct {
Charno int `json:"charno"`
Error string `json:"error"`
Lineno int `json:"lineno"`
File string `json:"file"`
Type string `json:"type"`
Line string `json:"line"`
}
func (e *OutputError) AsLogline() string {
return fmt.Sprintf("\033[36;1m[%d, %d]\033[31m error: \033[0m%s\n\t%s\n",
e.Lineno,
e.Charno,
e.Error,
e.Line,
)
}
type OutputWarning struct {
Charno int `json:"charno"`
Warning string `json:"warning"`
Lineno int `json:"lineno"`
File string `json:"file"`
Type string `json:"type"`
Line string `json:"line"`
}
func (w *OutputWarning) AsLogline() string {
return fmt.Sprintf("\033[36;1m[%d, %d]\033[33m warning: \033[0m%s\n\t%s\n",
w.Lineno,
w.Charno,
w.Warning,
w.Line,
)
}
type OutputServerError struct {
Code int `json:"code"`
Error string `json:"error"`
}
type OutputStatistics struct {
OriginalSize int `json:"originalSize"`
CompressedSize int `json:"compressedSize"`
CompileTime int `json:"compileTime"`
}
type Output struct {
CompiledCode string `json:"compiledCode"`
Errors []OutputError `json:"errors"`
Warnings []OutputWarning `json:"warnings"`
ServerErrors *OutputServerError `json:"serverErrors"`
Statistics OutputStatistics `json:"statistics"`
}
func (client *Client) buildRequest(jsCode []byte) *http.Request {
values := url.Values{}
values.Set("js_code", string(jsCode[:]))
values.Set("output_format", "json")
values.Add("output_info", "compiled_code")
values.Add("output_info", "statistics")
values.Add("output_info", "warnings")
values.Add("output_info", "errors")
if client.Language != "" {
values.Set("language", client.Language)
} else {
values.Set("language", "ECMASCRIPT5_STRICT")
}
if client.CompilationLevel != "" {
values.Set("compilation_level", client.CompilationLevel)
} else {
values.Set("compilation_level", "WHITESPACE_ONLY")
}
req, err := http.NewRequest(
"POST",
GoogleEndpointUrl,
strings.NewReader(values.Encode()),
)
if err != nil {
log.Fatalf(err.Error())
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return req
}
func (client *Client) Compile(jsCode []byte) *Output {
httpClient := http.Client{}
req := client.buildRequest(jsCode)
res, err := httpClient.Do(req)
if err != nil {
log.Fatalf(err.Error())
}
content, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatalf(err.Error())
}
output := Output{}
err = json.Unmarshal(content, &output)
if err != nil {
log.Fatalf(err.Error())
}
return &output
}
|
// The MIT License (MIT)
//
// Copyright (c) 2015-2016 Rasmus Mikkelsen
// Copyright (c) 2015-2016 eBay Software Foundation
// https://github.com/rasmus/EventFlow
//
// 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.
//
using System;
using EventFlow.Sql.ReadModels.Attributes;
namespace EventFlow.MsSql.ReadStores.Attributes
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class MsSqlReadModelIdentityColumnAttribute : SqlReadModelIdentityColumnAttribute
{
}
} |
# Quantum Computing for Computer Scientists Drills
DONE SO FAR:
- Chapter 2
- Chapter 3
- Chapter 4.1
TODO:
- All other chapters
Merge requests are welcome for anybody who can make more optimal solutions to the drills
|
interface ITableListBindings {
addButton: any;
config: any;
data: any;
extra: any;
filters: any;
onAction: Function;
onSort: Function;
openFiltersPanel: Function;
rowClickable: boolean;
sort: any;
title: string;
}
interface ITableListController extends ITableListBindings {
isFunction(field: any): boolean;
isString(field: any): boolean;
parseField(model: any, field: string): ng.ICompiledExpression;
}
export class TableListController implements ITableListController {
/**
* Bindings
*/
addButton: any;
config: any;
data: any;
extra: any;
filters: any;
onAction: Function;
onSort: Function;
openFiltersPanel: Function;
rowClickable: boolean;
sort: any;
title: string;
/**
* Properties
*/
constructor(
private $log: ng.ILogService,
private $parse: ng.IParseService
) { }
$onChange(changes) {
if (changes.config) {
this.config = angular.copy(this.config);
}
if (changes.data) {
this.data = angular.copy(this.data);
}
if (changes.extra) {
this.extra = angular.copy(this.extra);
}
if (changes.filters) {
this.filters = angular.copy(this.filters);
}
if (changes.rowClickable) {
this.rowClickable = angular.copy(this.rowClickable);
}
if (changes.sort) {
this.sort = angular.copy(this.sort);
}
}
handleTdClick(td, $event) {
if (td.disableRowClick) {
$event.stopPropagation();
}
}
isFunction(field) {
return angular.isFunction(field);
}
isString(field) {
return angular.isString(field);
}
parseField(model, field): ng.ICompiledExpression {
const getter = this.$parse(field);
return getter(model);
}
}
TableListController.$inject = [
'$log',
'$parse',
];
|
'use strict'
const MongoClient = require('mongodb').MongoClient
const muri = require('muri')
const chai = require('chai')
const expect = chai.expect
const assert = chai.assert
const chaiSubset = require('chai-subset')
chai.use(chaiSubset)
chai.should()
const stringConnection = 'mongodb://localhost:27017/lambda-mongo-crud-test'
const tableName = 'posts'
const Crud = require('./../lib/crud')
const PERMISSION = {
list: 'posts:list',
get: 'posts:get',
save: 'posts:save',
delete: 'posts:delete'
}
const ROLES = {
admin: {
can: [PERMISSION.save, PERMISSION.delete, PERMISSION.list, PERMISSION.get]
}
}
describe('MANY', () => {
before(async () => {
const { db: dbName } = muri(stringConnection)
const client = await MongoClient.connect(stringConnection, { useUnifiedTopology: true })
const collection = client.db(dbName).collection(tableName)
await collection.insertMany([{ title: "Title 1", code: 1 }, { title: "Title 2", code: 2 }, { title: "Title 3", code: 3 }])
await client.close()
})
after(async () => {
const { db: dbName } = muri(stringConnection)
const client = await MongoClient.connect(stringConnection, { useUnifiedTopology: true })
const collection = client.db(dbName).collection(tableName)
await collection.deleteMany()
await client.close()
})
const crud = new Crud(stringConnection, tableName, { role: 'admin', _id: 123 }, ROLES)
describe('list()', () => {
it('should return an array', (done) => {
crud.list({}, PERMISSION.list, {}, (err, docs) => {
expect(docs.length).to.be.equal(3)
done()
})
})
it('should return an array', (done) => {
const data = [
{ title: "Title 2", code: 2 },
{ title: "Title 3bis", code: 3 },
{ title: "Title 4", code: 4 },
{ title: "Title 5", code: 5 }
]
crud.upsertMany(data, "code", PERMISSION.save, {}, (err, result) => {
expect(result.nMatched).to.be.equal(2)
expect(result.nUpserted).to.be.equal(2)
crud.list({}, PERMISSION.list, {}, (err, docs) => {
expect(docs.length).to.be.equal(5)
done()
})
})
})
})
})
|
//= require ./src/module
//= require_tree ./src/services
//= require_tree ./src/controllers
//= require_tree ./src/directives |
class Thor
module ZshCompletion
module Command
def self.included(klass)
klass.class_eval do
desc "zsh-completion", "Print zsh completion script"
option :name, aliases: [:n]
def zsh_completion
name = options.name || File.basename($0)
puts ZshCompletion::Generator.new(self.class, name).generate
end
end
end
end
end
end
|
'''
Created on Jun 16, 2014
@author: lwoydziak
'''
import pexpect
import sys
from dynamic_machine.cli_commands import assertResultNotEquals, Command
class SshCli(object):
LOGGED_IN = 0
def __init__(self, host, loginUser, debug = False, trace = False, log=None, port=22, pexpectObject=None):
self.pexpect = pexpect if not pexpectObject else pexpectObject
self.debug = debug
self.trace = trace
self.host = host
self._port = port
self._connection = None
self.modeList = []
self._log = log
self._bufferedCommands = None
self._bufferedMode = None
self._loginUser = loginUser
self._resetExpect()
def __del__(self):
self.closeCliConnectionTo()
def showOutputOnScreen(self):
self.debug = True
self.trace = True
self._log = None
self._setupLog()
def connectWithSsh(self):
self._debugLog("Establishing connection to " + self.host)
self._connection = self.pexpect.spawn(
'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no %s@%s -p %d' %
(self._loginUser.username, self.host, self._port))
if self._connection is None:
raise Exception("Unable to connect via SSH perhaps wrong IP!")
self._secure = True
self._setupLog()
self._loginUser.commandLine(self)
self.modeList = [self._loginUser]
def resetLoggingTo(self, log):
self._connection.logfile = log
def _setupLog(self):
if self.trace:
class Python3BytesToStdOut:
def write(self, s):
sys.stdout.buffer.write(s)
def flush(self):
sys.stdout.flush()
self._connection.logfile = Python3BytesToStdOut()
if self._log is not None:
self._connection.logfile = self._log
def loginSsh(self):
self._setupLog()
self._debugLog("Login in as "+self._loginUser.username)
try:
self._loginUser.sendPassword()
return True
except Exception as e:
self.forceCloseCliConnectionTo()
raise Exception('Exception ('+str(e)+') '+'Expected CLI response: "Password:"' + "\n Got: \n" + self._lastExpect())
def _exit_modes_beyond(self, thisMode):
if not self.modeList: return
while len(self.modeList) > thisMode + 1:
self.modeList.pop().exit()
def exitMode(self, mode):
if mode in self.modeList:
self.modeList.remove(mode)
def check_prereq(self, prereqMode = 0):
self._exit_modes_beyond(prereqMode)
if len(self.modeList) <= prereqMode:
raise Exception("Attempted to enter menu when prerequist mode was not entered, expected: %d" % prereqMode)
def execute_as(self, user):
self.check_prereq(self.LOGGED_IN)
self._exit_modes_beyond(self.LOGGED_IN)
user.commandLine(self)
user.login()
self.modeList.append(user)
return user
def closeCliConnectionTo(self):
if self._connection == None:
return
self._exit_modes_beyond(-1)
self.modeList = []
self._debugLog("Exited all modes.")
self.forceCloseCliConnectionTo()
def forceCloseCliConnectionTo(self):
self.modeList = None
if self._connection:
self._debugLog("Closing connection.")
self._connection.close()
self._connection = None
def _debugLog(self, message):
if self.debug:
print(message)
def _resetExpect(self):
self.previousExpectLine = ""
if self._connection is not None and isinstance(self._connection.buffer, str):
self.previousExpectLine = self._connection.buffer
self._connection.buffer = ""
def _lastExpect(self):
constructLine = self.previousExpectLine
if self._connection is not None and isinstance(self._connection.before, str):
constructLine += self._connection.before
if self._connection is not None and isinstance(self._connection.after, str):
constructLine += self._connection.after
return constructLine
def send(self, command):
if self._bufferedCommands is None:
self._bufferedCommands = command
else:
self._bufferedCommands += "\n" + command
if self._bufferedMode is None:
self.flush()
else:
self._debugLog("Buffering command " + command)
def flush(self):
if self._bufferedCommands is None:
return
self._connection.sendline(str(self._bufferedCommands))
self._bufferedCommands = None
def buffering(self):
return self._bufferedMode
def bufferedMode(self, mode = True):
if mode is None:
self.flush()
self._bufferedMode = mode
def compareReceivedAgainst(self, pattern, timeout=-1, searchwindowsize=None, indexOfSuccessfulResult=0):
if self._bufferedMode is None:
index = self._connection.expect(pattern, timeout, searchwindowsize)
self._debugLog("\nLooking for " + str(pattern) + " Found ("+str(index)+")")
self._debugLog(self._lastExpect())
return index
else:
return indexOfSuccessfulResult |
<?php
namespace Common\DataBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class CommonDataBundle extends Bundle
{
}
|
[](http://travis-ci.org/pirxpilot/guard)
[](http://badge.fury.io/js/guard)
# guard
Trivial guard: triggers callback when internal counter reaches 0.
## API
Create ```guard``` passing callback function. Call ```on()``` and ```off()``` to increase and
decrease internal counter.
g = guard(function() {
console.log('Done...')
});
g.on();
g.on();
g.off();
g.off(); // prints 'Done...'
You can initialize the counter when creating a new guard.
g = guard(function() {
console.log('Done...')
}, 2);
g.on();
// call off 3 times
g.off();
g.off();
g.off(); // prints 'Done...'
In addition to `done` callback you can setup callbacks when counter reaches a certain value during
`on` or `off`
g = guard()
.onCallback(100, function() {
// called when internal counter is 100 after increment
})
.offCallback(10, function() {
// called when internal counter is 10 after decrement
});
## License
MIT
|
package com.revolut.sinap.payment;
import java.util.Objects;
import java.util.UUID;
public class Payment implements PaymentServiceOperation {
private final UUID transactionId;
private long sourceAccountId;
private Currency sourceCurrency;
/**
* minor units
*/
private long sourceAmount;
private long targetAccountId;
private Currency targetCurrency;
/**
* minor units
*/
private long targetAmount;
private String comment;
public Payment(UUID transactionId) {
this.transactionId = Objects.requireNonNull(transactionId, "transactionId");
}
public Payment setSourceAccountId(long sourceAccountId) {
this.sourceAccountId = sourceAccountId;
return this;
}
public Payment setSourceCurrency(Currency sourceCurrency) {
this.sourceCurrency = sourceCurrency;
return this;
}
public Payment setSourceAmount(long sourceAmount) {
this.sourceAmount = sourceAmount;
return this;
}
public Payment setTargetAccountId(long targetAccountid) {
this.targetAccountId = targetAccountid;
return this;
}
public Payment setTargetCurrency(Currency targetCurrency) {
this.targetCurrency = targetCurrency;
return this;
}
public Payment setTargetAmount(long targetAmount) {
this.targetAmount = targetAmount;
return this;
}
public Payment setComment(String comment) {
this.comment = comment;
return this;
}
@Override
public UUID transactionId() {
return transactionId;
}
@Override
public long getSourceAccountId() {
return sourceAccountId;
}
@Override
public Currency getSourceCurrency() {
return sourceCurrency;
}
@Override
public long getSourceAmount() {
return sourceAmount;
}
@Override
public long getTargetAccountId() {
return targetAccountId;
}
@Override
public Currency getTargetCurrency() {
return targetCurrency;
}
@Override
public long getTargetAmount() {
return targetAmount;
}
@Override
public String getComment() {
return comment;
}
@Override
public String toString() {
// todo mask account ids if it is card numbers
return "Payment{" +
"transactionId=" + transactionId +
", sourceAccountId=" + sourceAccountId +
", sourceCurrency='" + sourceCurrency + '\'' +
", sourceAmount=" + sourceAmount +
", targetAccountId=" + targetAccountId +
", targetCurrency='" + targetCurrency + '\'' +
", targetAmount=" + targetAmount +
", comment='" + comment + '\'' +
'}';
}
}
|
// Operational amplifier
extern struct {
// OPAMP1 control register
struct {
unsigned int OPAMP1_EN: 1; // OPAMP1 enable
unsigned int FORCE_VP: 1; // FORCE_VP
unsigned int VP_SEL: 2; // OPAMP1 Non inverting input selection
unsigned int : 1; // Reserved
unsigned int VM_SEL: 2; // OPAMP1 inverting input selection
unsigned int TCM_EN: 1; // Timer controlled Mux mode enable
unsigned int VMS_SEL: 1; // OPAMP1 inverting input secondary selection
unsigned int VPS_SEL: 2; // OPAMP1 Non inverting input secondary selection
unsigned int CALON: 1; // Calibration mode enable
unsigned int CALSEL: 2; // Calibration selection
unsigned int PGA_GAIN: 4; // Gain in PGA mode
unsigned int USER_TRIM: 1; // User trimming enable
unsigned int TRIMOFFSETP: 5; // Offset trimming value (PMOS)
unsigned int TRIMOFFSETN: 5; // Offset trimming value (NMOS)
unsigned int TSTREF: 1; // TSTREF
unsigned int OUTCAL: 1; // OPAMP 1 ouput status flag
unsigned int LOCK: 1; // OPAMP 1 lock
} OPAMP1_CR;
// OPAMP2 control register
struct {
unsigned int OPAMP2EN: 1; // OPAMP2 enable
unsigned int FORCE_VP: 1; // FORCE_VP
unsigned int VP_SEL: 2; // OPAMP2 Non inverting input selection
unsigned int : 1; // Reserved
unsigned int VM_SEL: 2; // OPAMP2 inverting input selection
unsigned int TCM_EN: 1; // Timer controlled Mux mode enable
unsigned int VMS_SEL: 1; // OPAMP2 inverting input secondary selection
unsigned int VPS_SEL: 2; // OPAMP2 Non inverting input secondary selection
unsigned int CALON: 1; // Calibration mode enable
unsigned int CAL_SEL: 2; // Calibration selection
unsigned int PGA_GAIN: 4; // Gain in PGA mode
unsigned int USER_TRIM: 1; // User trimming enable
unsigned int TRIMOFFSETP: 5; // Offset trimming value (PMOS)
unsigned int TRIMOFFSETN: 5; // Offset trimming value (NMOS)
unsigned int TSTREF: 1; // TSTREF
unsigned int OUTCAL: 1; // OPAMP 2 ouput status flag
unsigned int LOCK: 1; // OPAMP 2 lock
} OPAMP2_CR;
// OPAMP3 control register
struct {
unsigned int OPAMP3EN: 1; // OPAMP3 enable
unsigned int FORCE_VP: 1; // FORCE_VP
unsigned int VP_SEL: 2; // OPAMP3 Non inverting input selection
unsigned int : 1; // Reserved
unsigned int VM_SEL: 2; // OPAMP3 inverting input selection
unsigned int TCM_EN: 1; // Timer controlled Mux mode enable
unsigned int VMS_SEL: 1; // OPAMP3 inverting input secondary selection
unsigned int VPS_SEL: 2; // OPAMP3 Non inverting input secondary selection
unsigned int CALON: 1; // Calibration mode enable
unsigned int CALSEL: 2; // Calibration selection
unsigned int PGA_GAIN: 4; // Gain in PGA mode
unsigned int USER_TRIM: 1; // User trimming enable
unsigned int TRIMOFFSETP: 5; // Offset trimming value (PMOS)
unsigned int TRIMOFFSETN: 5; // Offset trimming value (NMOS)
unsigned int TSTREF: 1; // TSTREF
unsigned int OUTCAL: 1; // OPAMP 3 ouput status flag
unsigned int LOCK: 1; // OPAMP 3 lock
} OPAMP3_CR;
// OPAMP4 control register
struct {
unsigned int OPAMP4EN: 1; // OPAMP4 enable
unsigned int FORCE_VP: 1; // FORCE_VP
unsigned int VP_SEL: 2; // OPAMP4 Non inverting input selection
unsigned int : 1; // Reserved
unsigned int VM_SEL: 2; // OPAMP4 inverting input selection
unsigned int TCM_EN: 1; // Timer controlled Mux mode enable
unsigned int VMS_SEL: 1; // OPAMP4 inverting input secondary selection
unsigned int VPS_SEL: 2; // OPAMP4 Non inverting input secondary selection
unsigned int CALON: 1; // Calibration mode enable
unsigned int CALSEL: 2; // Calibration selection
unsigned int PGA_GAIN: 4; // Gain in PGA mode
unsigned int USER_TRIM: 1; // User trimming enable
unsigned int TRIMOFFSETP: 5; // Offset trimming value (PMOS)
unsigned int TRIMOFFSETN: 5; // Offset trimming value (NMOS)
unsigned int TSTREF: 1; // TSTREF
unsigned int OUTCAL: 1; // OPAMP 4 ouput status flag
unsigned int LOCK: 1; // OPAMP 4 lock
} OPAMP4_CR;
} SVD_OPAMP;
asm(".equ SVD_OPAMP, 0x40010038");
|
describe "Application 'conekta-motion'" do
# before do
# @app = UIApplication.sharedApplication
# end
#
# it "has one window" do
# @app.windows.size.should == 1
# end
end
|
(function($){
$.applyBulkSelectTable = function(obj, settings) {
var lastClickedElement = null,
lastClickedChecked = false,
lastClickedIndex = null;
var applyClass = function(obj, className, checked) {
if(checked)
obj.addClass(className);
else
obj.removeClass(className);
};
obj.on('click', '.'+settings.selectAllClass, function(e) {
var checked = $(this).is(':checked'),
items = obj.find('.'+settings.checkboxClass);
items.prop('checked', checked);
if(checked)
items.parents(settings.parentTag).addClass(settings.selectedClass);
else
items.parents(settings.parentTag).removeClass(settings.selectedClass);
});
obj.on('click', '.'+settings.checkboxClass, function(e) {
var o = $(e.target);
clickingElement = o;
clickingChecked = o.is(':checked');
clickingIndex = o.parents(settings.parentTag).index();
applyClass(clickingElement.parents(settings.parentTag), settings.selectedClass, clickingChecked);
if(e.shiftKey && lastClickedElement!==null) {
var list,
start,
end;
if(lastClickedIndex < clickingIndex) {
start = lastClickedElement.parents(settings.parentTag);
end = clickingElement.parents(settings.parentTag);
list = start.nextUntil(end);
}
else if(lastClickedIndex > clickingIndex) {
start = lastClickedElement.parents(settings.parentTag);
end = clickingElement.parents(settings.parentTag);
list = start.prevUntil(end);
}
lastClickedElement.prop('checked', clickingChecked);
applyClass(start, settings.selectedClass, clickingChecked);
list.find('.'+settings.checkboxClass).prop('checked', clickingChecked);
applyClass(list, settings.selectedClass, clickingChecked);
obj.trigger(clickingChecked ? 'bulk-select' : 'bulk-deselect', {
'start': start,
'end': end,
'list': list,
'applied': Math.abs(clickingIndex-lastClickedIndex+1)
});
}
lastClickedElement = clickingElement;
lastClickedChecked = clickingChecked;
lastClickedIndex = clickingIndex;
});
};
$.fn.bulkSelectTable = function(options) {
var settings = $.extend({
selectAllClass: 'selectall',
checkboxClass: 'selectable',
selectedClass: 'selected',
parentTag: 'tr'
}, options);
return this.each(function(){
$.applyBulkSelectTable($(this), settings);
});
};
}(jQuery)); |
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE_AFL.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category design
* @package default
* @copyright Copyright (c) 2014 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/
button, .form-button { filter:chroma(color=#000000); overflow:visible; width:auto; }
.main { height:400px; }
.nav, .form-btn-set, .header-top, .bar-head { zoom:1; }
.clear { clear:both; height:0; font-size:0; line-height:0; overflow:hidden; }
.connect-packages td .select { margin:0 0 2px; }
|
using Asteroids.Model;
using Asteroids.Utils;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using Xamarin.Forms;
namespace Asteroids.ViewModel
{
public class AsteroidsViewModel : INotifyPropertyChanged
{
#region Private fields
private AsteroidsModel _model;
private String _timer;
#endregion
public DelegateCommand NewGameCommand { get; private set; }
public DelegateCommand PauseResumeCommand { get; private set; }
public DelegateCommand TurnCommand { get; private set; }
public String PauseResumeLabel
{
get
{
if (_model.Paused)
{
return "Resume";
}
else
{
return "Pause";
}
}
}
public String TimerLabel
{
get { return _timer; }
set
{
_timer = "Time: " + value;
OnPropertyChanged();
}
}
public Int32 ColumnCount
{
get { return _model.GameBoard.Width; }
}
public ObservableCollection<Field> Fields { get; private set; }
#region Constructor
public AsteroidsViewModel(AsteroidsModel model)
{
_model = model;
_model.FieldsChanged += new EventHandler(Model_FieldsChanged);
_model.TimePassed += new EventHandler<int>(Model_TimePassed);
_model.GameOver += new EventHandler<int>(Model_GameOver);
NewGameCommand = new DelegateCommand(param => StartNewGame());
PauseResumeCommand = new DelegateCommand(param => PauseResume());
TurnCommand = new DelegateCommand(param => Turn(param.ToString()));
TimerLabel = "0";
Fields = new ObservableCollection<Field>();
}
#endregion
#region Model event handlers
private void Model_FieldsChanged(object sender, EventArgs e)
{
Device.BeginInvokeOnMainThread(() =>
{
FieldType[][] matrix = new FieldType[_model.GameBoard.Width][];
for (int i = 0; i < matrix.Length; i++)
{
matrix[i] = new FieldType[_model.GameBoard.Height];
for (int j = 0; j < matrix[i].Length; j++)
{
matrix[i][j] = FieldType.EMPTY;
}
}
foreach (Coordinate asteroid in _model.Asteroids)
{
matrix[asteroid.X][asteroid.Y] = FieldType.ASTEROID;
}
matrix[_model.Player.X][_model.Player.Y] = FieldType.PLAYER;
Fields.Clear();
for (int i = 0; i < matrix.Length; i++)
{
for (int j = 0; j < matrix[i].Length; j++)
{
Fields.Add(new Field(i, j, matrix[j][i]));
}
}
OnFieldsChanged?.Invoke(this, new FieldsChangedEventArgs(_model.Player, _model.Asteroids));
});
}
private void Model_TimePassed(object sender, int time)
{
TimerLabel = time.ToString();
}
private void Model_GameOver(object sender, int time)
{
string message = "You lived for " + time.ToString() + " seconds";
if (OnGameOver != null)
OnGameOver(this, message);
}
#endregion
#region Public Methods
public void StartNewGame()
{
_model.NewGame();
TimerLabel = "0";
OnPropertyChanged("PauseResumeLabel");
OnNewGame?.Invoke(this, EventArgs.Empty);
}
#endregion
#region Private Methods
private void PauseResume()
{
if (_model.Paused)
{
_model.Resume();
}
else
{
_model.Pause();
}
OnPropertyChanged("PauseResumeLabel");
}
private void Turn(String direction)
{
switch (direction)
{
case "left":
_model.TurnLeft();
break;
case "right":
_model.TurnRight();
break;
}
}
private void OnPropertyChanged([CallerMemberName] String property = null)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
#endregion
#region Public Events
public event PropertyChangedEventHandler PropertyChanged;
public event EventHandler OnNewGame;
public event EventHandler<String> OnGameOver;
public event EventHandler<FieldsChangedEventArgs> OnFieldsChanged;
#endregion
}
}
|
#include "DecisionTreeLearner.h"
#include "RowListUtil.h"
#include <stdexcept>
#include <vector>
#include <sstream>
using namespace std;
using namespace ml;
typedef vector<DecisionTree*>::iterator DTIterator;
typedef vector<DecisionTree*>::const_iterator DTCIterator;
typedef vector<DecisionTree*>::reverse_iterator DTRIterator;
void DecisionTreeLearner::copy(const DecisionTreeLearner & other)
{
trees = other.trees;
rand = other.rand;
}
void DecisionTreeLearner::free()
{
for (DTIterator i = trees.begin(); i != trees.end(); i++)
{
DecisionTree::RetireInstance(*i);
}
trees.clear();
}
DecisionTreeLearner::DecisionTreeLearner() :
trees(), rand()
{
}
DecisionTreeLearner::DecisionTreeLearner(const Rand & r) : trees(), rand(r)
{
}
DecisionTreeLearner::DecisionTreeLearner(const DecisionTreeLearner & other) : trees(other.trees), rand(other.rand)
{
}
DecisionTreeLearner & DecisionTreeLearner::operator = (const DecisionTreeLearner & other)
{
if (&other != this)
{
free();
copy(other);
}
return *this;
}
DecisionTreeLearner::~DecisionTreeLearner()
{
free();
}
void DecisionTreeLearner::train(Matrix & features, Matrix & labels,
Matrix *testSet, Matrix * testLabels)
{
free();
if (features.rows() != labels.rows())
{
stringstream ss;
ss << "Features and Labels must be equinumerous" << " at " << __LINE__
<< " in " << __FILE__;
throw std::runtime_error(ss.str());
}
std::vector<int> FeatureAttrs;
FeatureAttrs.resize(features.cols());
std::vector<int> FeatureCommonValues;
FeatureCommonValues.resize(features.cols());
for (int i = 0; i < FeatureAttrs.size(); i++)
{
FeatureCommonValues[i] = features.mostCommonValue(i);
FeatureAttrs[i] = features.valueCount(i);
}
trees.resize(labels.cols());
Matrix TurnedLabels;
TransposeMatrix(labels, TurnedLabels);
for (int i = 0; i < trees.size(); i++)
{
trees[i] = DecisionTree::CreateInstance(FeatureAttrs, FeatureCommonValues,
labels.valueCount(i), labels.mostCommonValue(i),
features, TurnedLabels[i]);
}
}
void DecisionTreeLearner::predict(const std::vector<double> & features, std::vector<double> & labels)
{
for (int i = 0; i < trees.size();
i++)
{
labels[i] = (trees[i])->Classify(features);
}
}
|
use nix::sys::socket::{InetAddr, UnixAddr, getsockname};
use std::{mem, net};
use std::path::Path;
use std::str::FromStr;
use std::os::unix::io::AsRawFd;
use ports::localhost;
#[test]
pub fn test_inetv4_addr_to_sock_addr() {
let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap();
let addr = InetAddr::from_std(&actual);
match addr {
InetAddr::V4(addr) => {
let ip: u32 = 0x7f000001;
let port: u16 = 3000;
assert_eq!(addr.sin_addr.s_addr, ip.to_be());
assert_eq!(addr.sin_port, port.to_be());
}
_ => panic!("nope"),
}
assert_eq!(addr.to_str(), "127.0.0.1:3000");
let inet = addr.to_std();
assert_eq!(actual, inet);
}
#[test]
pub fn test_path_to_sock_addr() {
let actual = Path::new("/foo/bar");
let addr = UnixAddr::new(actual).unwrap();
let expect: &'static [i8] = unsafe { mem::transmute(&b"/foo/bar"[..]) };
assert_eq!(&addr.0.sun_path[..8], expect);
assert_eq!(addr.path(), actual);
}
#[test]
pub fn test_getsockname() {
use std::net::TcpListener;
let addr = localhost();
let sock = TcpListener::bind(&*addr).unwrap();
let res = getsockname(sock.as_raw_fd()).unwrap();
assert_eq!(addr, res.to_str());
}
|
// Copyright (c) 2013 Richard Long & HexBeerium
//
// Released under the MIT license ( http://opensource.org/licenses/MIT )
//
#import <Foundation/Foundation.h>
#import "CABaseException.h"
#import "CAJob.h"
@protocol CAJobListener <NSObject>
-(void)jobCompleted:(id<CAJob>)job;
-(void)jobFailed:(id<CAJob>)job withException:(CABaseException*)exception;
@end
|
using AVDump3CL;
using AVDump3Lib.Processing.HashAlgorithms;
using AVDump3Lib.Settings;
using AVDump3Lib.Settings.CLArguments;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Xml.Linq;
using Xunit;
namespace AVDump3Tests;
public class CLTests {
[Fact]
public void WithoutArgs() {
var management = AVD3CLModule.Create(null);
var avd3CLModule = management.GetModule<AVD3CLModule>();
avd3CLModule.HandleArgs(Array.Empty<string>());
var settingsModule = management.GetModule<AVD3SettingsModule>();
CLSettingsHandler.PrintHelp(settingsModule.SettingProperties, null, true);
}
[Fact]
public void HashTests() {
var hashes = new Dictionary<string, IAVDHashAlgorithm[]> {
{ "ED2K", new IAVDHashAlgorithm[] { new Ed2kHashAlgorithm() , new Ed2kNativeHashAlgorithm() } },
{ "CRC32C", new IAVDHashAlgorithm[] { new Crc32CIntelHashAlgorithm() } },
{ "CRC32", new IAVDHashAlgorithm[] { new Crc32HashAlgorithm() , new Crc32NativeHashAlgorithm() } },
{ "KECCAK-224", new IAVDHashAlgorithm[] { new KeccakNativeHashAlgorithm(224) } },
{ "KECCAK-256", new IAVDHashAlgorithm[] { new KeccakNativeHashAlgorithm(256) } },
{ "KECCAK-384", new IAVDHashAlgorithm[] { new KeccakNativeHashAlgorithm(384) } },
{ "KECCAK-512", new IAVDHashAlgorithm[] { new KeccakNativeHashAlgorithm(512) } },
{ "SHA3-224", new IAVDHashAlgorithm[] { new SHA3NativeHashAlgorithm(224) } },
{ "SHA3-256", new IAVDHashAlgorithm[] { new SHA3NativeHashAlgorithm(256) } },
{ "SHA3-384", new IAVDHashAlgorithm[] { new SHA3NativeHashAlgorithm(384) } },
{ "SHA3-512", new IAVDHashAlgorithm[] { new SHA3NativeHashAlgorithm(512) } },
{ "MD4", new IAVDHashAlgorithm[] { new Md4HashAlgorithm(), new Md4NativeHashAlgorithm() } },
{ "SHA1", new IAVDHashAlgorithm[] { new SHA1NativeHashAlgorithm() } },
{ "SHA2-256", new IAVDHashAlgorithm[] { new SHA256NativeHashAlgorithm() } },
{ "Tiger", new IAVDHashAlgorithm[] { new TigerNativeHashAlgorithm() } },
{ "TTH", new IAVDHashAlgorithm[] { new TigerTreeHashAlgorithm(1), new TigerTreeHashAlgorithm(3) } },
};
var sourceDataCheckAlg = SHA256.Create();
var testVectors = XElement.Load("HashTestVectors.xml");
foreach(var hashElem in testVectors.Elements("Hash")) {
var hashName = (string)hashElem.Attribute("name");
var hashAlgs = hashes[hashName];
foreach(var testVectorElem in hashElem.Elements("TestVector")) {
Span<byte> b = new byte[(int)testVectorElem.Attribute("length")];
var patternName = (string)testVectorElem.Attribute("pattern");
switch(patternName) {
case "BinaryZeros": break;
case "BinaryOnes": for(int i = 0; i < b.Length; i++) b[i] = 0xFF; break;
case "ASCIIZeros": for(int i = 0; i < b.Length; i++) b[i] = (byte)'0'; break;
default: break;
}
var bHash = sourceDataCheckAlg.ComputeHash(b.ToArray());
foreach(var hashAlg in hashAlgs) {
Debug.Print($"{hashName} - {hashAlg.GetType().Name} - {patternName} - {b.Length}");
hashAlg.Initialize();
var bytesProcessed = 0L;
while(bytesProcessed + hashAlg.BlockSize <= b.Length) {
hashAlg.TransformFullBlocks(b[..hashAlg.BlockSize]);
bytesProcessed += hashAlg.BlockSize;
}
var hash = hashAlg.TransformFinalBlock(b[^(b.Length % hashAlg.BlockSize)..]);
Assert.True(!b.SequenceEqual(bHash), "Source Data has been corrupted");
var hashStr = BitConverter.ToString(hash.ToArray()).Replace("-", "").ToLower();
var expectedHashStr = ((string)testVectorElem.Attribute("hash"))?.ToLower();
Assert.True(hashStr.Equals(expectedHashStr), $"{hashName} - {hashAlg.GetType().Name} - {patternName} - {b.Length}: {hashStr} != {expectedHashStr}");
if(hashAlg.AdditionalHashes.IsEmpty) {
Assert.True(testVectorElem.Attribute("hash2") == null, $"{hashName} - {hashAlg.GetType().Name} - {patternName} - {b.Length}: Additional hashes expected");
} else {
hashStr = BitConverter.ToString(hashAlg.AdditionalHashes[0].ToArray()).Replace("-", "").ToLower();
expectedHashStr = ((string)testVectorElem.Attribute("hash2"))?.ToLower() ?? "<NoAdditionalHash>";
Assert.True(hashStr.Equals(expectedHashStr), $"{hashName} - {hashAlg.GetType().Name} - {patternName} - {b.Length}: {hashStr} != {expectedHashStr}");
}
}
}
}
}
}
|
{% extends "template.html" %}
{% block content %}
<h1>About</h1>
<p>This is all about us.</p>
{% endblock %}
|
@include ('theme.header')
@yield('content')
@include ('theme.footer') |
<?php
if ( ! class_exists( 'WP_Customize_Control' ) )
return NULL;
/**
* Customize Control for Heading
*/
class WEN_Customize_Heading_Control extends WP_Customize_Control {
public $type = 'heading';
public function render_content() {
?>
<h3 class="wen-customize-heading"><?php echo esc_html( $this->label ); ?></h3><!-- .wen-customize-heading -->
<?php
}
}
/**
* Customize Control for Message
*/
class WEN_Customize_Message_Control extends WP_Customize_Control {
public $type = 'message';
public function render_content() {
?>
<div class="wen-customize-message">
<?php echo $this->description; ?>
</div> <!-- .wen-customize-message -->
<?php
}
}
/**
* Customize Control for Radio Image
*/
class WEN_Customize_Radio_Image_Control extends WP_Customize_Control {
public $type = 'radio-image';
public function render_content() {
if ( empty( $this->choices ) )
return;
$name = '_customize-radio-' . $this->id;
?>
<label>
<span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
<?php
foreach ( $this->choices as $value => $label ) :
?>
<label>
<input type="radio" value="<?php echo esc_attr( $value ); ?>" <?php $this->link(); checked( $this->value(), $value ); ?> class="stylish-radio-image" name="<?php echo esc_attr( $name ); ?>"/>
<span><img src="<?php echo esc_url($label); ?>" alt="<?php echo esc_attr( $value ); ?>" /></span>
</label>
<?php
endforeach;
?>
</label>
<?php
}
}
/**
* Customize Control for Taxonomy Select
*/
class WEN_Customize_Dropdown_Taxonomies_Control extends WP_Customize_Control {
public $type = 'dropdown-taxonomies';
public $taxonomy = '';
public function __construct( $manager, $id, $args = array() ) {
$our_taxonomy = 'category';
if ( isset( $args['taxonomy'] ) ) {
$taxonomy_exist = taxonomy_exists( esc_attr( $args['taxonomy'] ) );
if ( true === $taxonomy_exist ) {
$our_taxonomy = esc_attr( $args['taxonomy'] );
}
}
$args['taxonomy'] = $our_taxonomy;
$this->taxonomy = esc_attr( $our_taxonomy );
parent::__construct( $manager, $id, $args );
}
public function render_content() {
$tax_args = array(
'hierarchical' => 0,
'taxonomy' => $this->taxonomy,
);
$all_taxonomies = get_categories( $tax_args );
?>
<label>
<span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
<select <?php echo $this->link(); ?>>
<?php
printf('<option value="%s" %s>%s</option>', '', selected($this->value(), '', false), __( 'Select', 'wen-associate' ) );
?>
<?php if ( ! empty( $all_taxonomies ) ): ?>
<?php foreach ( $all_taxonomies as $key => $tax ): ?>
<?php
printf('<option value="%s" %s>%s</option>', $tax->term_id, selected($this->value(), $tax->term_id, false), $tax->name );
?>
<?php endforeach ?>
<?php endif ?>
</select>
</label>
<?php
}
}
|
package myheadlessplugin;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
public class Perspective implements IPerspectiveFactory {
public void createInitialLayout(IPageLayout layout) {
}
}
|
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("16.ListsMoreEx04.UnunionList")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("16.ListsMoreEx04.UnunionList")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
[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("6c724ea1-5832-4f31-8bb5-5a3e51f72e25")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
package controller.tasks;
import static controller.NAMControllerCompilerMain.LOGGER;
import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutionException;
import javax.swing.SwingWorker;
import controller.CompileMode;
public abstract class CollectRULsTask implements ExecutableTask {
private static FileFilter fileFilter = new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory() ||
pathname.getName().endsWith(".txt") ||
pathname.getName().endsWith(".rul");
}
};
private final File[] rulDirs;
public static CollectRULsTask getInstance(CompileMode mode, File[] rulDirs) {
return mode.isInteractive() ? new GUITask(rulDirs) : new CommandLineTask(rulDirs);
}
private CollectRULsTask(File[] rulDirs) {
this.rulDirs = rulDirs;
}
public abstract Queue<File>[] get() throws InterruptedException, ExecutionException;
private Queue<File>[] mainProcess() {
LOGGER.info("Collecting input data.");
@SuppressWarnings("unchecked")
Queue<File>[] rulInputFiles = new Queue[3];
for (int i = 0; i < rulInputFiles.length; i++)
rulInputFiles[i] = collectRecursively(CollectRULsTask.this.rulDirs[i]);
return rulInputFiles;
}
/**
* Recursive collecting.
* @param parent parent file of the directory.
* @return Queue of subfiles.
*/
private Queue<File> collectRecursively(File parent) {
Queue<File> result = new LinkedList<File>();
File[] subFiles = parent.listFiles(fileFilter);
Arrays.sort(subFiles); // sort files alphabetically
for (int i = 0; i < subFiles.length; i++) {
if (subFiles[i].isDirectory())
result.addAll(collectRecursively(subFiles[i]));
else
result.add(subFiles[i]);
}
return result;
}
private static class GUITask extends CollectRULsTask {
private final SwingWorker<Queue<File>[], Void> worker;
private GUITask(File[] rulDirs) {
super(rulDirs);
this.worker = new SwingWorker<Queue<File>[], Void>() {
@Override
protected Queue<File>[] doInBackground() {
return GUITask.super.mainProcess();
}
};
}
@Override
public void execute() {
this.worker.execute();
}
@Override
public Queue<File>[] get() throws InterruptedException, ExecutionException {
return worker.get();
}
}
private static class CommandLineTask extends CollectRULsTask {
private Queue<File>[] result;
private CommandLineTask(File[] rulDirs) {
super(rulDirs);
}
@Override
public void execute() {
result = CommandLineTask.super.mainProcess();
}
@Override
public Queue<File>[] get() {
return result;
}
}
}
|
package seedu.task.commons.util;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
/**
* Writes and reads files
*/
public class FileUtil {
private static final String CHARSET = "UTF-8";
public static boolean isFileExists(File file) {
return file.exists() && file.isFile();
}
public static void createIfMissing(File file) throws IOException {
if (!isFileExists(file)) {
createFile(file);
}
}
/**
* Creates a file if it does not exist along with its missing parent directories
*
* @return true if file is created, false if file already exists
*/
public static boolean createFile(File file) throws IOException {
if (file.exists()) {
return false;
}
createParentDirsOfFile(file);
return file.createNewFile();
}
/**
* Creates the given directory along with its parent directories
*
* @param dir the directory to be created; assumed not null
* @throws IOException if the directory or a parent directory cannot be created
*/
public static void createDirs(File dir) throws IOException {
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Failed to make directories of " + dir.getName());
}
}
/**
* Creates parent directories of file if it has a parent directory
*/
public static void createParentDirsOfFile(File file) throws IOException {
File parentDir = file.getParentFile();
if (parentDir != null) {
createDirs(parentDir);
}
}
/**
* Assumes file exists
*/
public static String readFromFile(File file) throws IOException {
return new String(Files.readAllBytes(file.toPath()), CHARSET);
}
/**
* Writes given string to a file.
* Will create the file if it does not exist yet.
*/
public static void writeToFile(File file, String content) throws IOException {
Files.write(file.toPath(), content.getBytes(CHARSET));
}
/**
* Converts a string to a platform-specific file path
* @param pathWithForwardSlash A String representing a file path but using '/' as the separator
* @return {@code pathWithForwardSlash} but '/' replaced with {@code File.separator}
*/
public static String getPath(String pathWithForwardSlash) {
assert pathWithForwardSlash != null;
assert pathWithForwardSlash.contains("/");
return pathWithForwardSlash.replace("/", File.separator);
}
//@@author A0163848R
/**
* Creates a localized window to create a file for saving.
* @param Window title
* @param File extension filters
* @return Chosen file
*/
public static File promptSaveFileDialog(String title, Stage stage, ExtensionFilter ...extensionFilters) {
FileChooser prompt = getFileChooser(title, extensionFilters);
File saved = prompt.showSaveDialog(stage);
if (!saved.getName().contains(".")) {
saved = new File(saved.getAbsolutePath()
+ prompt.getSelectedExtensionFilter().getExtensions().get(0).substring(1));
}
return saved;
}
/**
* Creates a localized window to select a file for loading.
* @param Window title
* @param File extension filters
* @return Chosen file
*/
public static File promptOpenFileDialog(String title, Stage stage, ExtensionFilter ...extensionFilters) {
return getFileChooser(title, extensionFilters).showOpenDialog(stage);
}
/**
* Returns a new file chooser prompt
* @param Title of prompt
* @param Extension filters to allow for writing/reading
* @return New file chooser prompt
*/
private static FileChooser getFileChooser(String title, ExtensionFilter ...extensionFilters) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(title);
fileChooser.getExtensionFilters().addAll(extensionFilters);
return fileChooser;
}
}
|
/**
* IconElement is often mixed into other classes to generate an icon.
* Icons are graphics, about the size of normal text. They are used to aid the user
* in locating a control or to convey information in a space-efficient way. See the
* [OOUI documentation on MediaWiki] [1] for a list of icons
* included in the library.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
* the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
* the icon element be set to an existing icon instead of the one generated by this class, set a
* value using a jQuery selection. For example:
*
* // Use a <div> tag instead of a <span>
* $icon: $( '<div>' )
* // Use an existing icon element instead of the one generated by the class
* $icon: this.$element
* // Use an icon element from a child widget
* $icon: this.childwidget.$element
* @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a
* map of symbolic names. A map is used for i18n purposes and contains a `default` icon
* name and additional names keyed by language code. The `default` name is used when no icon is
* keyed by the user's language.
*
* Example of an i18n map:
*
* { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
* See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
* [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
*/
OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$icon = null;
this.icon = null;
// Initialization
this.setIcon( config.icon || this.constructor.static.icon );
this.setIconElement( config.$icon || $( '<span>' ) );
};
/* Setup */
OO.initClass( OO.ui.mixin.IconElement );
/* Static Properties */
/**
* The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map
* is used for i18n purposes and contains a `default` icon name and additional names keyed by
* language code. The `default` name is used when no icon is keyed by the user's language.
*
* Example of an i18n map:
*
* { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
*
* Note: the static property will be overridden if the #icon configuration is used.
*
* @static
* @inheritable
* @property {Object|string}
*/
OO.ui.mixin.IconElement.static.icon = null;
/**
* The icon title, displayed when users move the mouse over the icon. The value can be text, a
* function that returns title text, or `null` for no title.
*
* The static property will be overridden if the #iconTitle configuration is used.
*
* @static
* @inheritable
* @property {string|Function|null}
*/
OO.ui.mixin.IconElement.static.iconTitle = null;
/* Methods */
/**
* Set the icon element. This method is used to retarget an icon mixin so that its functionality
* applies to the specified icon element instead of the one created by the class. If an icon
* element is already set, the mixin’s effect on that element is removed. Generated CSS classes
* and mixin methods will no longer affect the element.
*
* @param {jQuery} $icon Element to use as icon
*/
OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
if ( this.$icon ) {
this.$icon
.removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
.removeAttr( 'title' );
}
this.$icon = $icon
.addClass( 'oo-ui-iconElement-icon' )
.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon )
.toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
if ( this.iconTitle !== null ) {
this.$icon.attr( 'title', this.iconTitle );
}
this.updateThemeClasses();
};
/**
* Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
* The icon parameter can also be set to a map of icon names. See the #icon config setting
* for an example.
*
* @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
* by language code, or `null` to remove the icon.
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
if ( icon && typeof icon !== 'string' ) {
icon = OO.ui.getLocalValue( icon, null, 'default' );
}
if ( this.icon === icon ) {
return this;
}
this.$element.toggleClass( 'oo-ui-iconElement', !!icon );
if ( this.$icon ) {
if ( this.icon ) {
this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
}
if ( icon ) {
this.$icon.addClass( 'oo-ui-icon-' + icon );
}
this.$icon.toggleClass( 'oo-ui-iconElement-noIcon', !icon );
}
this.icon = icon;
this.updateThemeClasses();
return this;
};
/**
* Get the symbolic name of the icon.
*
* @return {string} Icon name
*/
OO.ui.mixin.IconElement.prototype.getIcon = function () {
return this.icon;
};
|
//
// UIButton+SKClickInterval.h
// SKExtension
//
// Created by CFsyk on 2017/10/23.
// Copyright © 2017年 CFsyk. All rights reserved.
//
#import <UIKit/UIKit.h>
//设置按钮的点击间隔为"kDefaultClickInterval"
@interface UIButton (SKClickInterval)
@end
|
![In-game picture of Madagascar][1]
The country of Madagascar is only reachable through sea. This means that if the country closes its shipyard before I reach it there is no way I can possibly win… or is there?
How can I work around this?
http://www.crazymonkeygames.com/Pandemic-2.html
[1]: http://i.stack.imgur.com/0hCCA.png |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\IEntityCollectionRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
/// <summary>
/// The interface ISiteContentTypesCollectionRequestBuilder.
/// </summary>
public partial interface ISiteContentTypesCollectionRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
ISiteContentTypesCollectionRequest Request();
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
ISiteContentTypesCollectionRequest Request(IEnumerable<Option> options);
/// <summary>
/// Gets an <see cref="IContentTypeRequestBuilder"/> for the specified ContentType.
/// </summary>
/// <param name="id">The ID for the ContentType.</param>
/// <returns>The <see cref="IContentTypeRequestBuilder"/>.</returns>
IContentTypeRequestBuilder this[string id] { get; }
}
}
|
<?php
namespace Dafiti\Correios\Adapter;
use Dafiti\Correios\Entity;
class SapAdapterTest extends \PHPUnit_Framework_TestCase
{
private $adapter;
private $config;
public function setUp()
{
$this->adapter = $this->getMockBuilder(__NAMESPACE__.'\\SoapAdapter')
->disableOriginalConstructor()
->setMethods([
'__getLastRequest',
'__getLastResponse',
'getLogFile',
'solicitarPostagemReversa'
])->getMock();
$this->config = new Entity\Config([
'wsdl' => 'http://teste',
'usuario' => 'test',
'senha' => '123',
'codAdministrativo' => '123',
'contrato' => '123',
]);
$this->adapter->setConfig($this->config);
}
public function testGetConfig()
{
$this->assertEquals($this->config,$this->adapter->getConfig());
}
public function testSuccessfulCall()
{
$response = (object) ['cod_erro'=>0];
$response = (object) ['return'=>$response];
$this->adapter->expects($this->once())
->method('solicitarPostagemReversa')
->will($this->returnValue($response));
$expected = new Entity\ResponseObject($response);
$result = $this->adapter->call(
'solicitarPostagemReversa',
new Entity\RequestObject(['test'])
);
$this->assertEquals($expected,$result);
}
public function testSuccessfulCallWithLogs()
{
$this->config->setLogPath("php://memory");
$response = (object) ['cod_erro'=>0];
$response = (object) ['return'=>$response];
$this->adapter->expects($this->once())
->method('solicitarPostagemReversa')
->will($this->returnValue($response));
$file = $this->getMock(
'SplFileObject',
['fwrite'],
['php://memory']
);
$file->expects($this->atLeastOnce())
->method('fwrite')
->will($this->returnValue(1));
$this->adapter->expects($this->atLeastOnce())
->method('getLogFile')
->will($this->returnValue($file));
$this->adapter->call(
'solicitarPostagemReversa',
new Entity\RequestObject(['test'])
);
}
/**
* @expectedException \RuntimeException
*/
public function testSuccessfulCallWithLogsFailure()
{
$this->config->setLogPath("/tmp");
$response = (object) ['cod_erro'=>0];
$response = (object) ['return'=>$response];
$this->adapter->expects($this->once())
->method('solicitarPostagemReversa')
->will($this->returnValue($response));
$this->adapter->expects($this->once())
->method('getLogFile')
->will($this->throwException(
new \RuntimeException("Unable to write log files.")
)
);
$this->adapter->call(
'solicitarPostagemReversa',
new Entity\RequestObject(['test'])
);
}
/**
* @expectedException \SoapFault
*/
public function testUnsuccessfulCall()
{
$this->adapter->expects($this->any())
->method('solicitarPostagemReversa')
->will($this->throwException(new \SoapFault("test", "msg"))
);
$this->adapter->call(
'solicitarPostagemReversa',
new Entity\RequestObject(['test'])
);
}
}
|
#include "actiongroup.h"
#include "taskheader_p.h"
#include "taskgroup_p.h"
#include "actionlabel.h"
#include "actionpanelscheme.h"
#include <QtGui/QPainter>
namespace QSint
{
ActionGroup::ActionGroup(QWidget *parent)
: QWidget(parent)
{
myHeader = new TaskHeader(QPixmap(), "", false, this);
myHeader->setVisible(false);
init(false);
}
ActionGroup::ActionGroup(const QString &title, bool expandable, QWidget *parent)
: QWidget(parent)
{
myHeader = new TaskHeader(QPixmap(), title, expandable, this);
init(true);
}
ActionGroup::ActionGroup(const QPixmap &icon, const QString &title, bool expandable, QWidget *parent)
: QWidget(parent)
{
myHeader = new TaskHeader(icon, title, expandable, this);
init(true);
}
void ActionGroup::init(bool header)
{
m_foldStep = 0;
myScheme = ActionPanelScheme::defaultScheme();
QVBoxLayout *vbl = new QVBoxLayout();
vbl->setMargin(0);
vbl->setSpacing(0);
setLayout(vbl);
vbl->addWidget(myHeader);
myGroup = new TaskGroup(this, header);
vbl->addWidget(myGroup);
myDummy = new QWidget(this);
vbl->addWidget(myDummy);
myDummy->hide();
connect(myHeader, SIGNAL(activated()), this, SLOT(showHide()));
}
void ActionGroup::setScheme(ActionPanelScheme *pointer)
{
myScheme = pointer;
myHeader->setScheme(pointer);
myGroup->setScheme(pointer);
update();
}
QBoxLayout* ActionGroup::groupLayout()
{
return myGroup->groupLayout();
}
ActionLabel* ActionGroup::addAction(QAction *action, bool addToLayout, bool addStretch)
{
if (!action)
return 0;
ActionLabel* label = new ActionLabel(action, this);
myGroup->addActionLabel(label, addToLayout, addStretch);
return label;
}
ActionLabel* ActionGroup::addActionLabel(ActionLabel *label, bool addToLayout, bool addStretch)
{
if (!label)
return 0;
myGroup->addActionLabel(label, addToLayout, addStretch);
return label;
}
bool ActionGroup::addWidget(QWidget *widget, bool addToLayout, bool addStretch)
{
return myGroup->addWidget(widget, addToLayout, addStretch);
}
void ActionGroup::showHide()
{
if (m_foldStep)
return;
if (!myHeader->expandable())
return;
if (myGroup->isVisible())
{
m_foldPixmap = myGroup->transparentRender();
// m_foldPixmap = QPixmap::grabWidget(myGroup, myGroup->rect());
m_tempHeight = m_fullHeight = myGroup->height();
m_foldDelta = m_fullHeight / myScheme->groupFoldSteps;
m_foldStep = myScheme->groupFoldSteps;
m_foldDirection = -1;
myGroup->hide();
myDummy->setFixedSize(myGroup->size());
myDummy->show();
QTimer::singleShot(myScheme->groupFoldDelay, this, SLOT(processHide()));
}
else
{
m_foldStep = myScheme->groupFoldSteps;
m_foldDirection = 1;
m_tempHeight = 0;
QTimer::singleShot(myScheme->groupFoldDelay, this, SLOT(processShow()));
}
myDummy->show();
}
void ActionGroup::processHide()
{
if (!--m_foldStep) {
myDummy->setFixedHeight(0);
myDummy->hide();
setFixedHeight(myHeader->height());
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
return;
}
setUpdatesEnabled(false);
m_tempHeight -= m_foldDelta;
myDummy->setFixedHeight(m_tempHeight);
setFixedHeight(myDummy->height()+myHeader->height());
QTimer::singleShot(myScheme->groupFoldDelay, this, SLOT(processHide()));
setUpdatesEnabled(true);
}
void ActionGroup::processShow()
{
if (!--m_foldStep) {
myDummy->hide();
m_foldPixmap = QPixmap();
myGroup->show();
setFixedHeight(m_fullHeight+myHeader->height());
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
setMaximumHeight(9999);
setMinimumHeight(0);
return;
}
setUpdatesEnabled(false);
m_tempHeight += m_foldDelta;
myDummy->setFixedHeight(m_tempHeight);
setFixedHeight(myDummy->height()+myHeader->height());
QTimer::singleShot(myScheme->groupFoldDelay, this, SLOT(processShow()));
setUpdatesEnabled(true);
}
void ActionGroup::paintEvent ( QPaintEvent * event )
{
QPainter p(this);
if (myDummy->isVisible()) {
if (myScheme->groupFoldThaw) {
if (m_foldDirection < 0)
p.setOpacity((double)m_foldStep / myScheme->groupFoldSteps);
else
p.setOpacity((double)(myScheme->groupFoldSteps-m_foldStep) / myScheme->groupFoldSteps);
}
switch (myScheme->groupFoldEffect)
{
case ActionPanelScheme::ShrunkFolding:
p.drawPixmap(myDummy->pos(), m_foldPixmap.scaled(myDummy->size()) );
break;
case ActionPanelScheme::SlideFolding:
p.drawPixmap(myDummy->pos(), m_foldPixmap,
QRect(0, m_foldPixmap.height()-myDummy->height(),
m_foldPixmap.width(), myDummy->width()
) );
break;
default:
p.drawPixmap(myDummy->pos(), m_foldPixmap);
}
return;
}
}
bool ActionGroup::isExpandable() const
{
return myHeader->expandable();
}
void ActionGroup::setExpandable(bool expandable)
{
myHeader->setExpandable(expandable);
}
bool ActionGroup::hasHeader() const
{
return myHeader->isVisible();
}
void ActionGroup::setHeader(bool enable)
{
myHeader->setVisible(enable);
}
QString ActionGroup::headerText() const
{
return myHeader->myTitle->text();
}
void ActionGroup::setHeaderText(const QString & headerText)
{
myHeader->myTitle->setText(headerText);
}
QSize ActionGroup::minimumSizeHint() const
{
return QSize(200,100);
}
}
|
<?php
/*
* This file is part of the Liquid package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @package Liquid
*/
namespace Liquid\Tag;
use Liquid\TestCase;
use Liquid\Template;
class TagForTest extends TestCase
{
/**
*/
public function testForInvalidSyntax()
{
$this->expectException(\Liquid\Exception\ParseException::class);
$template = new Template();
$template->parse("{% for elem %}{% endfor %}");
}
public function testFor()
{
$this->assertTemplateResult('', '{%for item in array%} yo {%endfor%}', array('array' => array()));
$this->assertTemplateResult(' yo yo yo yo ', '{%for item in array%} yo {%endfor%}', array('array' => array(1, 2, 3, 4)));
$this->assertTemplateResult(' boo boo boo boo ', '{%for item in array%} boo {%endfor%}', array('array' => new \ArrayIterator(array(1, 2, 3, 4))));
$this->assertTemplateResult('yoyo', '{%for item in array%}yo{%endfor%}', array('array' => array(1, 2)));
$this->assertTemplateResult(' yo ', '{%for item in array%} yo {%endfor%}', array('array' => array(1)));
$this->assertTemplateResult('', '{%for item in array%}{%endfor%}', array('array' => array(1, 2)));
$expected = <<<HERE
yo
yo
yo
HERE;
$template = <<<HERE
{%for item in array%}
yo
{%endfor%}
HERE;
$this->assertTemplateResult($expected, $template, array('array' => array(1, 2, 3)));
}
public function testForWithVariable()
{
$this->assertTemplateResult(' 1 2 3 ', '{%for item in array%} {{item}} {%endfor%}', array('array' => array(1, 2, 3)));
$this->assertTemplateResult('123', '{%for item in array%}{{item}}{%endfor%}', array('array' => array(1, 2, 3)));
$this->assertTemplateResult('123', '{% for item in array %}{{item}}{% endfor %}', array('array' => array(1, 2, 3)));
$this->assertTemplateResult('abcd', '{%for item in array%}{{item}}{%endfor%}', array('array' => array('a', 'b', 'c', 'd')));
$this->assertTemplateResult('a b c', '{%for item in array%}{{item}}{%endfor%}', array('array' => array('a', ' ', 'b', ' ', 'c')));
$this->assertTemplateResult('abc', '{%for item in array%}{{item}}{%endfor%}', array('array' => array('a', '', 'b', '', 'c')));
}
public function testForWithHash()
{
$this->assertTemplateResult('a=b c=d e=f ', '{%for item in array%}{{item[0]}}={{item[1]}} {%endfor%}', array('array' => array('a' => 'b', 'c' => 'd', 'e' => 'f')));
}
public function testForHelpers()
{
$assigns = array('array' => array(1, 2, 3));
$this->assertTemplateResult(' 1/3 2/3 3/3 ', '{%for item in array%} {{forloop.index}}/{{forloop.length}} {%endfor%}', $assigns);
$this->assertTemplateResult(' 1 2 3 ', '{%for item in array%} {{forloop.index}} {%endfor%}', $assigns);
$this->assertTemplateResult(' 0 1 2 ', '{%for item in array%} {{forloop.index0}} {%endfor%}', $assigns);
$this->assertTemplateResult(' 2 1 0 ', '{%for item in array%} {{forloop.rindex0}} {%endfor%}', $assigns);
$this->assertTemplateResult(' 3 2 1 ', '{%for item in array%} {{forloop.rindex}} {%endfor%}', $assigns);
$this->assertTemplateResult(' 1 0 0 ', '{%for item in array%} {{forloop.first}} {%endfor%}', $assigns);
$this->assertTemplateResult(' 0 0 1 ', '{%for item in array%} {{forloop.last}} {%endfor%}', $assigns);
}
public function testForHelpersWithOffsetAndLimit()
{
$assigns = array('array' => array(0, 1, 2, 3, 4));
$this->assertTemplateResult(' 1/3 2/3 3/3 ', '{%for item in array offset:1 limit:3%} {{forloop.index}}/{{forloop.length}} {%endfor%}', $assigns);
$this->assertTemplateResult(' 1 2 3 ', '{%for item in array offset:1 limit:3%} {{forloop.index}} {%endfor%}', $assigns);
$this->assertTemplateResult(' 0 1 2 ', '{%for item in array offset:1 limit:3%} {{forloop.index0}} {%endfor%}', $assigns);
$this->assertTemplateResult(' 2 1 0 ', '{%for item in array offset:1 limit:3%} {{forloop.rindex0}} {%endfor%}', $assigns);
$this->assertTemplateResult(' 3 2 1 ', '{%for item in array offset:1 limit:3%} {{forloop.rindex}} {%endfor%}', $assigns);
$this->assertTemplateResult(' 1 0 0 ', '{%for item in array offset:1 limit:3%} {{forloop.first}} {%endfor%}', $assigns);
$this->assertTemplateResult(' 0 0 1 ', '{%for item in array offset:1 limit:3%} {{forloop.last}} {%endfor%}', $assigns);
}
public function testForAndIf()
{
$assigns = array('array' => array(1, 2, 3));
$this->assertTemplateResult(' yay ', '{%for item in array%} {% if forloop.first %}yay{% endif %} {%endfor%}', $assigns);
$this->assertTemplateResult(' yay boo boo ', '{%for item in array%} {% if forloop.first %}yay{% else %}boo{% endif %} {%endfor%}', $assigns);
$this->assertTemplateResult(' boo boo ', '{%for item in array%} {% if forloop.first %}{% else %}boo{% endif %} {%endfor%}', $assigns);
}
public function testLimiting()
{
$assigns = array('array' => array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0));
$this->assertTemplateResult('12', '{%for i in array limit:2 %}{{ i }}{%endfor%}', $assigns);
$this->assertTemplateResult('1234567890', '{%for i in array limit:20 %}{{ i }}{%endfor%}', $assigns);
$this->assertTemplateResult('1234', '{%for i in array limit:4 %}{{ i }}{%endfor%}', $assigns);
$this->assertTemplateResult('3456', '{%for i in array limit:4 offset:2 %}{{ i }}{%endfor%}', $assigns);
$this->assertTemplateResult('3456', '{%for i in array limit: 4 offset: 2 %}{{ i }}{%endfor%}', $assigns);
$assigns['limit'] = 2;
$assigns['offset'] = 2;
$this->assertTemplateResult('34', '{%for i in array limit: limit offset: offset %}{{ i }}{%endfor%}', $assigns);
}
public function testNestedFor()
{
$assigns = array('array' => array(array(1, 2), array(3, 4), array(5, 6)));
$this->assertTemplateResult('123456', '{%for item in array%}{%for i in item%}{{ i }}{%endfor%}{%endfor%}', $assigns);
}
public function testOffsetOnly()
{
$assigns = array('array' => array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0));
$this->assertTemplateResult('890', '{%for i in array offset:7 %}{{ i }}{%endfor%}', $assigns);
}
public function testPauseResume()
{
$assigns = array('array' => array('items' => array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)));
$markup = <<<MKUP
{%for i in array.items limit: 3 %}{{i}}{%endfor%}
next
{%for i in array.items offset:continue limit: 3 %}{{i}}{%endfor%}
next
{%for i in array.items offset:continue limit: 3 %}{{i}}{%endfor%}
MKUP;
$expected = <<<XPCTD
123
next
456
next
789
XPCTD;
$this->assertTemplateResult($expected, $markup, $assigns);
}
public function testPauseResumeLimit()
{
$assigns = array('array' => array('items' => array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)));
$markup = <<<MKUP
{%for i in array.items limit: 3 %}{{i}}{%endfor%}
next
{%for i in array.items offset:continue limit: 3 %}{{i}}{%endfor%}
next
{%for i in array.items offset:continue limit: 1 %}{{i}}{%endfor%}
MKUP;
$expected = <<<XPCTD
123
next
456
next
7
XPCTD;
$this->assertTemplateResult($expected, $markup, $assigns);
}
public function testPauseResumeBIGLimit()
{
$assigns = array('array' => array('items' => array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)));
$markup = <<<MKUP
{%for i in array.items limit: 3 %}{{i}}{%endfor%}
next
{%for i in array.items offset:continue limit: 3 %}{{i}}{%endfor%}
next
{%for i in array.items offset:continue limit: 1000 %}{{i}}{%endfor%}
MKUP;
$expected = <<<XPCTD
123
next
456
next
7890
XPCTD;
$this->assertTemplateResult($expected, $markup, $assigns);
}
public function testPauseResumeBIGOffset()
{
$assigns = array('array' => array('items' => array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)));
$markup = <<<MKUP
{%for i in array.items limit: 3 %}{{i}}{%endfor%}
next
{%for i in array.items offset:continue limit: 3 %}{{i}}{%endfor%}
next
{%for i in array.items offset:continue limit: 1000 offset:1000 %}{{i}}{%endfor%}
MKUP;
$expected = <<<XPCTD
123
next
456
next
XPCTD;
$this->assertTemplateResult($expected, $markup, $assigns);
}
public function testForWithRanges()
{
$this->assertTemplateResult('123456789', '{%for i in (1..9)%}{{i}}{%endfor%}');
$this->assertTemplateResult(' 9 10 11', '{%for i in (9..11)%} {{i}}{%endfor%}');
$this->assertTemplateResult('9991000', '{%for i in (999..1000)%}{{i}}{%endfor%}');
$assigns = array('variable' => 100);
$this->assertTemplateResult('9596979899100', '{%for i in (95..variable)%}{{i}}{%endfor%}', $assigns);
}
}
|
#ifndef MARKER_OBJECT_H
#define MARKER_OBJECT_H
class StateGraphicsObject;
class MarkerObject
{
public:
MarkerObject(int id, int color, StateGraphicsObject* parent = nullptr);
public:
void connectToState(StateGraphicsObject* state);
void disconnectFromState();
int getId();
int getColor();
private:
int m_id;
int m_color;
StateGraphicsObject* m_parentState;
};
#endif // MARKER_OBJECT_H
|
/**
* Created by Yang on 2/11/16.
*/
import { createSelector } from 'reselect';
const selectForgetPasswordPage = () => (state) => state.get('forgetpassword');
const selectEmail = () => createSelector(
selectForgetPasswordPage(),
(forgetPasswordState) => forgetPasswordState.get('email')
);
const selectError = () => createSelector(
selectForgetPasswordPage(),
(forgetPasswordState) => forgetPasswordState.get('error')
);
const selectResetEmailSent = () => createSelector(
selectForgetPasswordPage(),
(forgetPasswordState) => forgetPasswordState.get('resetEmailSent')
);
export {
selectForgetPasswordPage,
selectEmail,
selectError,
selectResetEmailSent,
};
|
### SpendFrom ###
Use the raw transactions API to send coins received on a particular
address (or addresses).
### Usage: ###
Depends on [jsonrpc](http://json-rpc.org/).
spendfrom.py --from=FROMADDRESS1[,FROMADDRESS2] --to=TOADDRESS --amount=amount \
--fee=fee --datadir=/path/to/.gvidoncore --testnet --dry_run
With no arguments, outputs a list of amounts associated with addresses.
With arguments, sends coins received by the `FROMADDRESS` addresses to the `TOADDRESS`.
### Notes ###
- You may explicitly specify how much fee to pay (a fee more than 1% of the amount
will fail, though, to prevent gvidon-losing accidents). Spendfrom may fail if
it thinks the transaction would never be confirmed (if the amount being sent is
too small, or if the transaction is too many bytes for the fee).
- If a change output needs to be created, the change will be sent to the last
`FROMADDRESS` (if you specify just one `FROMADDRESS`, change will go back to it).
- If `--datadir` is not specified, the default datadir is used.
- The `--dry_run` option will just create and sign the transaction and print
the transaction data (as hexadecimal), instead of broadcasting it.
- If the transaction is created and broadcast successfully, a transaction id
is printed.
- If this was a tool for end-users and not programmers, it would have much friendlier
error-handling.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: test.py
#
# Copyright 2018 Costas Tyfoxylos
#
# 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.
#
import argparse
import logging
import json
import os
from bootstrap import bootstrap
from library import execute_command, tempdir
# This is the main prefix used for logging
LOGGER_BASENAME = '''_CI.test'''
LOGGER = logging.getLogger(LOGGER_BASENAME)
LOGGER.addHandler(logging.NullHandler())
def get_arguments():
parser = argparse.ArgumentParser(description='Accepts stages for testing')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--lint', help='Test the lint stage of the template', action='store_true')
group.add_argument('--test', help='Test the test stage of the template', action='store_true')
group.add_argument('--build', help='Test the build stage of the template', action='store_true')
group.add_argument('--document', help='Test the document stage of the template', action='store_true')
args = parser.parse_args()
return args
def _test(stage):
from cookiecutter.main import cookiecutter
template = os.path.abspath('.')
context = os.path.abspath('cookiecutter.json')
with tempdir():
cookiecutter(template,
extra_context=json.loads(open(context).read()),
no_input=True)
os.chdir(os.listdir('.')[0])
del os.environ['PIPENV_PIPFILE']
return execute_command(os.path.join('_CI', 'scripts', f'{stage}.py'))
def test(stage):
emojize = bootstrap()
exit_code = _test(stage)
success = not exit_code
if success:
LOGGER.info('%s Tested stage "%s" successfully! %s',
emojize(':white_heavy_check_mark:'),
stage,
emojize(':thumbs_up:'))
else:
LOGGER.error('%s Errors found testing stage "%s"! %s',
emojize(':cross_mark:'),
stage,
emojize(':crying_face:'))
raise SystemExit(exit_code)
if __name__ == '__main__':
args = get_arguments()
stage = next((argument for argument in ('lint', 'test', 'build', 'document')
if getattr(args, argument)), None)
test(stage)
|
import { createPool } from '../index';
const pool = createPool(
{
create: function () {
return Promise.resolve('test');
},
destroy: function (resource) {
}
},
{
max: 10,
idleTimeoutMillis: 30000,
priorityRange: 3
}
);
pool.acquire().then(function (client) {
pool.release(client);
});
pool.acquire(0).then(function (client) {
pool.release(client);
});
pool.acquire(1).then(function (client) {
pool.release(client);
});
|
import {assert} from 'chai'
import {toConsole} from '../src/destinations'
import {Message} from '../src/message'
import {addDestination} from '../src/output'
import {assertContainsFields} from '../src/testing'
describe('toConsole', function() {
/** @test {toConsole} */
it('performs a noop if no suitable method is found', function() {
const messages = [],
remove = addDestination(toConsole({}))
Message.create({x: 123}).write()
remove()
assert.deepEqual(messages, [])
})
/** @test {toConsole} */
it('falls back to `console.log`', function() {
const messages = [],
console = {log: x => messages.push(x)},
remove = addDestination(toConsole(console))
Message.create({x: 123}).write()
remove()
assertContainsFields(
messages[0],
{x: 123})
})
/** @test {toConsole} */
it('logs to `console.info`', function() {
const messages = [],
console = {info: x => messages.push(x)},
remove = addDestination(toConsole(console))
Message.create({x: 123}).write()
remove()
assertContainsFields(
messages[0],
{x: 123})
})
})
|
import isNil from "lodash/isNil";
import isArray from "lodash/isArray";
import isFunction from "lodash/isFunction";
import isObject from "lodash/isObject";
import mergeWith from "lodash/mergeWith";
import Fakerator from "lib/fakerator";
module.exports = function() {
let locale = require("lib/locales/sv-SE");
let fbLocale = require("lib/locales/default");
// Merge locale and fallback
locale = mergeWith(locale, fbLocale, (objValue) => {
// DON'T MERGE ARRAYS
if (isArray(objValue) || isFunction(objValue))
return objValue;
if (!isNil(objValue) && !isObject(objValue))
return objValue;
});
return new Fakerator(locale);
}; |
module.exports = {
'tokens': [
{
'type': 'category',
'name': 'Colors',
'tokens': [
{
'variable': '--app-accent-color',
'name': 'App Accent Color',
'type': 'color',
'themes': {
'plain': {
'value': 'black',
'variable': '--plain-black-color'
},
'funky': {
'value': 'orange',
'variable': '--funky-orange-color'
}
},
'description': 'Accent color'
},
{
'variable': '--app-call-to-action-color',
'name': 'App Call To Action Color',
'type': 'color',
'themes': {
'plain': {
'value': 'red',
'variable': '--plain-red-color'
},
'funky': {
'value': 'orange',
'variable': '--funky-orange-color'
}
},
'description': 'Primary interaction color'
}
]
},
{
'type': 'category',
'name': 'Shadows',
'tokens': [
{
'variable': '--app-box-shadow',
'name': 'App Box Shadow',
'type': 'shadow',
'themes': {
'plain': {
'value': '0 0 8px 2px rgba(92,43,54,0.2)'
},
'funky': {
'value': '0 0 8px 2px rgba(0,0,0,0.2)'
}
}
}
]
},
{
'type': 'category',
'name': 'Borders',
'tokens': [
{
'variable': '--app-border-radius',
'name': 'App Border Radius',
'type': 'border-radius',
'themes': {
'plain': {
'value': '20rem'
},
'funky': {
'value': '3px'
}
}
},
{
'variable': '--app-border-width',
'name': 'App Border Width',
'type': 'border-width',
'themes': {
'plain': {
'value': '2px'
},
'funky': {
'value': '7px'
}
}
},
{
'variable': '--app-border-style',
'name': 'App Border Style',
'type': 'border-style',
'themes': {
'plain': {
'value': 'dashed'
},
'funky': {
'value': 'dotted'
}
}
}
]
},
{
'type': 'category',
'name': 'Opacity',
'tokens': [
{
'variable': '--app-opacity-30',
'name': 'Opacity 30%',
'type': 'opacity',
'themes': {
'plain': {
'value': '0.3'
},
'funky': {
'value': '0.3'
}
}
},
{
'variable': '--app-opacity-60',
'name': 'Opacity 60%',
'type': 'opacity',
'themes': {
'plain': {
'value': '0.6'
},
'funky': {
'value': '0.6'
}
}
},
{
'variable': '--app-opacity-90',
'name': 'Opacity 90%',
'type': 'opacity',
'themes': {
'plain': {
'value': '0.9'
},
'funky': {
'value': '0.9'
}
}
}
]
},
{
'type': 'category',
'name': 'Spaces',
'tokens': [
{
'variable': '--app-space-xs',
'name': 'App Space XS',
'type': 'size',
'themes': {
'plain': {
'value': '0.25rem'
},
'funky': {
'value': '0.25rem'
}
}
},
{
'variable': '--app-space-s',
'name': 'App Space S',
'type': 'size',
'themes': {
'plain': {
'value': '0.5rem'
},
'funky': {
'value': '0.5rem'
}
}
},
{
'variable': '--app-space-m',
'name': 'App Space M',
'type': 'size',
'themes': {
'plain': {
'value': '1rem'
},
'funky': {
'value': '1rem'
}
}
},
{
'variable': '--app-space-l',
'name': 'App Space L',
'type': 'size',
'themes': {
'plain': {
'value': '1.5rem'
},
'funky': {
'value': '1.5rem'
}
}
},
{
'variable': '--app-space-xl',
'name': 'App Space XL',
'type': 'size',
'themes': {
'plain': {
'value': '2rem'
},
'funky': {
'value': '2rem'
}
}
},
{
'variable': '--app-space-xxl',
'name': 'App Space XXL',
'type': 'size',
'themes': {
'plain': {
'value': '4rem'
},
'funky': {
'value': '4rem'
}
}
}
]
}
]
}
|
using System.Linq.Expressions;
using System.Reflection;
namespace GraphExec
{
internal sealed class ExpressionProcessResult<T>
{
internal MemberExpression Member { get; set; }
internal ConstantExpression Constant { get; set; }
internal FieldInfo Field { get; set; }
internal string Description { get; set; }
internal T Value { get; set; }
}
}
|
require 'spec_helper'
describe MongoProfiler do
end
|
#ifndef _LIBP_VPX_H_
#define _LIBP_VPX_H_
#ifdef __cplusplus
extern "C" {
#endif
void* vpx_init(const char* filename);
const unsigned char* vpx_read(void *input, unsigned int *length);
void vpx_destroy(void *input);
#ifdef __cplusplus
}
#endif
#endif |
/*
* Copyright (C) 2014 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration. All Rights Reserved.
*/
/**
* @exports BMNGRestLayer
*/
define([
'../error/ArgumentError',
'../layer/Layer',
'../util/Logger',
'../util/PeriodicTimeSequence',
'../layer/RestTiledImageLayer'
],
function (ArgumentError,
Layer,
Logger,
PeriodicTimeSequence,
RestTiledImageLayer) {
"use strict";
/**
* Constructs a Blue Marble layer.
* @alias BMNGRestLayer
* @constructor
* @augments Layer
* @classdesc Represents the 12 month collection of Blue Marble Next Generation imagery for the year 2004.
* By default the month of January is displayed, but this can be changed by setting this class' time
* property to indicate the month to display.
* @param {String} serverAddress The server address of the tile service. May be null, in which case the
* current origin is used (see window.location).
* @param {String} pathToData The path to the data directory relative to the specified server address.
* May be null, in which case the server address is assumed to be the full path to the data directory.
* @param {String} displayName The display name to assign this layer. Defaults to "Blue Marble" if null or
* undefined.
* @param {Date} initialTime A date value indicating the month to display. The nearest month to the specified
* time is displayed. January is displayed if this argument is null or undefined, i.e., new Date("2004-01");
* See {@link RestTiledImageLayer} for a description of its contents. May be null, in which case default
* values are used.
*/
var BMNGRestLayer = function (serverAddress, pathToData, displayName, initialTime) {
Layer.call(this, displayName || "Blue Marble time series");
/**
* A value indicating the month to display. The nearest month to the specified time is displayed.
* @type {Date}
* @default January 2004 (new Date("2004-01"));
*/
this.time = initialTime || new Date("2004-01");
this.pickEnabled = false;
// Intentionally not documented.
this.layers = {}; // holds the layers as they're created.
// Intentionally not documented.
this.layerNames = [
{month: "BlueMarble-200401", time: BMNGRestLayer.availableTimes[0]},
{month: "BlueMarble-200402", time: BMNGRestLayer.availableTimes[1]},
{month: "BlueMarble-200403", time: BMNGRestLayer.availableTimes[2]},
{month: "BlueMarble-200404", time: BMNGRestLayer.availableTimes[3]},
{month: "BlueMarble-200405", time: BMNGRestLayer.availableTimes[4]},
{month: "BlueMarble-200406", time: BMNGRestLayer.availableTimes[5]},
{month: "BlueMarble-200407", time: BMNGRestLayer.availableTimes[6]},
{month: "BlueMarble-200408", time: BMNGRestLayer.availableTimes[7]},
{month: "BlueMarble-200409", time: BMNGRestLayer.availableTimes[8]},
{month: "BlueMarble-200410", time: BMNGRestLayer.availableTimes[9]},
{month: "BlueMarble-200411", time: BMNGRestLayer.availableTimes[10]},
{month: "BlueMarble-200412", time: BMNGRestLayer.availableTimes[11]}
];
this.timeSequence = new PeriodicTimeSequence("2004-01-01/2004-12-01/P1M");
// By default if no server address and path are sent as parameters in the constructor,
// the layer's data is retrieved from http://worldwindserver.net
this.serverAddress = serverAddress || "http://worldwindserver.net/webworldwind/";
this.pathToData = pathToData || "/standalonedata/Earth/BlueMarble256/";
// Alternatively, the data can be retrieved from a local folder as follows.
// - Download the file located in:
// http://worldwindserver.net/webworldwind/WebWorldWindStandaloneData.zip
// - Unzip it into the Web World Wind top-level directory so that the "standalonedata" directory is a peer
// of examples, src, apps and worldwind.js.
// - Uncomment the following lines or call BMNGRestLayer from the application with these parameters:
//this.serverAddress = serverAddress || null;
//this.pathToData = pathToData || "../standalonedata/Earth/BlueMarble256/";
};
BMNGRestLayer.prototype = Object.create(Layer.prototype);
/**
* Indicates the available times for this layer.
* @type {Date[]}
* @readonly
*/
BMNGRestLayer.availableTimes = [
new Date("2004-01"),
new Date("2004-02"),
new Date("2004-03"),
new Date("2004-04"),
new Date("2004-05"),
new Date("2004-06"),
new Date("2004-07"),
new Date("2004-08"),
new Date("2004-09"),
new Date("2004-10"),
new Date("2004-11"),
new Date("2004-12")
];
/**
* Initiates retrieval of this layer's level 0 images for all sub-layers. Use
* [isPrePopulated]{@link TiledImageLayer#isPrePopulated} to determine when the images have been retrieved
* and associated with the level 0 tiles.
* Pre-populating is not required. It is used to eliminate the visual effect of loading tiles incrementally,
* but only for level 0 tiles. An application might pre-populate a layer in order to delay displaying it
* within a time series until all the level 0 images have been retrieved and added to memory.
* @param {WorldWindow} wwd The world window for which to pre-populate this layer.
* @throws {ArgumentError} If the specified world window is null or undefined.
*/
BMNGRestLayer.prototype.prePopulate = function (wwd) {
if (!wwd) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "BMNGRestLayer", "prePopulate", "missingWorldWindow"));
}
for (var i = 0; i < this.layerNames.length; i++) {
var layerName = this.layerNames[i].month;
if (!this.layers[layerName]) {
this.createSubLayer(layerName);
}
this.layers[layerName].prePopulate(wwd);
}
};
/**
* Indicates whether this layer's level 0 tile images for all sub-layers have been retrieved and associated
* with the tiles.
* Use [prePopulate]{@link TiledImageLayer#prePopulate} to initiate retrieval of level 0 images.
* @param {WorldWindow} wwd The world window associated with this layer.
* @returns {Boolean} true if all level 0 images have been retrieved, otherwise false.
* @throws {ArgumentError} If the specified world window is null or undefined.
*/
BMNGRestLayer.prototype.isPrePopulated = function (wwd) {
for (var i = 0; i < this.layerNames.length; i++) {
var layer = this.layers[this.layerNames[i].month];
if (!layer || !layer.isPrePopulated(wwd)) {
return false;
}
}
return true;
};
BMNGRestLayer.prototype.doRender = function (dc) {
var layer = this.nearestLayer(this.time);
layer.opacity = this.opacity;
if (this.detailControl) {
layer.detailControl = this.detailControl;
}
layer.doRender(dc);
this.inCurrentFrame = layer.inCurrentFrame;
};
// Intentionally not documented.
BMNGRestLayer.prototype.nearestLayer = function (time) {
var nearestName = this.nearestLayerName(time);
if (!this.layers[nearestName]) {
this.createSubLayer(nearestName);
}
return this.layers[nearestName];
};
BMNGRestLayer.prototype.createSubLayer = function (layerName) {
var dataPath = this.pathToData + layerName;
this.layers[layerName] = new RestTiledImageLayer(this.serverAddress, dataPath, this.displayName);
};
// Intentionally not documented.
BMNGRestLayer.prototype.nearestLayerName = function (time) {
var milliseconds = time.getTime();
if (milliseconds <= this.layerNames[0].time.getTime()) {
return this.layerNames[0].month;
}
if (milliseconds >= this.layerNames[11].time.getTime()) {
return this.layerNames[11].month;
}
for (var i = 0; i < this.layerNames.length - 1; i++) {
var leftTime = this.layerNames[i].time.getTime(),
rightTime = this.layerNames[i + 1].time.getTime();
if (milliseconds >= leftTime && milliseconds <= rightTime) {
var dLeft = milliseconds - leftTime,
dRight = rightTime - milliseconds;
return dLeft < dRight ? this.layerNames[i].month : this.layerNames[i + 1].month;
}
}
};
return BMNGRestLayer;
}); |
console.log('Hello!');
var thermostat = new Thermostat();
var updateTemperature = function() {
$('#temperature_display').text(thermostat.temperature);
$('#temperature_display').css('color', thermostat.colour);
};
$(document).ready(function() {
updateTemperature();
$('#increase-button').on('click', function() {
thermostat.increaseTemp();
updateTemperature();
});
$('#decrease-button').on('click', function() {
thermostat.decreaseTemp();
updateTemperature();
});
$('#reset-button').on('click', function() {
thermostat.reset();
updateTemperature();
});
$('#power-saving-mode').on('change', function() {
if (this.checked) {
thermostat.powerSavingOn();
} else {
thermostat.powerSavingOff();
}
updateTemperature();
});
$('#weather-status-form').submit(function(event){
event.preventDefault();
captureCity = $('#weather-city').val();
console.log(captureCity);
processForm();
updateTemperature();
});
});
function processForm() {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + captureCity,
jsonp: 'callback',
dataType: 'jsonp',
cache: false,
data: {
q: $('#weather-city').val(),
},
success: function (response) {
$('#current-city').text(response.name);
$('#weather-description').text(response.weather[0].description);
$('#weather-temp').text((response.main.temp -273.15).toFixed(1));
$('#weather-wind').text(response.wind.speed);
},
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.