code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
'use strict'
const { describe, it, beforeEach, afterEach } = require('mocha')
const Helper = require('hubot-test-helper')
const { expect } = require('chai')
const mock = require('mock-require')
const http = require('http')
const sleep = m => new Promise(resolve => setTimeout(() => resolve(), m))
const request = uri => {
return new Promise((resolve, reject) => {
http
.get(uri, res => {
const result = { statusCode: res.statusCode }
if (res.statusCode !== 200) {
resolve(result)
} else {
res.setEncoding('utf8')
let rawData = ''
res.on('data', chunk => {
rawData += chunk
})
res.on('end', () => {
result.body = rawData
resolve(result)
})
}
})
.on('error', err => reject(err))
})
}
const infoRutStub = {
getPersonByRut (rut) {
return new Promise((resolve, reject) => {
if (rut === '11111111-1') {
return resolve({ name: 'Anonymous', rut })
} else if (rut === '77777777-7') {
return resolve({ name: 'Sushi', rut })
} else if (rut === '22222222-2') {
return resolve(null)
}
reject(new Error('Not found'))
})
},
getEnterpriseByRut (rut) {
return new Promise((resolve, reject) => {
if (rut === '11111111-1') {
return resolve({ name: 'Anonymous', rut })
} else if (rut === '77777777-7') {
return resolve({ name: 'Sushi', rut })
} else if (rut === '22222222-2') {
return resolve(null)
}
reject(new Error('Not found'))
})
},
getPersonByName (name) {
return new Promise((resolve, reject) => {
if (name === 'juan perez perez') {
return resolve([
{ rut: '11.111.111-1', name: 'Anonymous' },
{ rut: '11.111.111-1', name: 'Anonymous' },
{ rut: '11.111.111-1', name: 'Anonymous' },
{ rut: '11.111.111-1', name: 'Anonymous' },
{ rut: '11.111.111-1', name: 'Anonymous' },
{ rut: '11.111.111-1', name: 'Anonymous' }
])
} else if (name === 'soto') {
return resolve([
{ rut: '11.111.111-1', name: 'Anonymous' },
{ rut: '11.111.111-1', name: 'Anonymous' },
{ rut: '11.111.111-1', name: 'Anonymous' },
{ rut: '11.111.111-1', name: 'Anonymous' },
{ rut: '11.111.111-1', name: 'Anonymous' }
])
} else if (name === 'info-rut') {
return resolve([])
}
reject(new Error('Not found'))
})
},
getEnterpriseByName (name) {
return new Promise((resolve, reject) => {
if (name === 'perez') {
return resolve([{ rut: '11.111.111-1', name: 'Anonymous' }])
} else if (name === 'info-rut') {
return resolve([])
}
reject(new Error('Not found'))
})
}
}
mock('info-rut', infoRutStub)
const helper = new Helper('./../src/index.js')
describe('info rut', function () {
beforeEach(() => {
this.room = helper.createRoom()
})
afterEach(() => this.room.destroy())
describe('person rut valid', () => {
const rut = '11111111-1'
beforeEach(async () => {
this.room.user.say('user', `hubot info-rut rut ${rut}`)
await sleep(1000)
})
it('should return a full name', () => {
expect(this.room.messages).to.eql([
['user', `hubot info-rut rut ${rut}`],
['hubot', `Anonymous (${rut})`]
])
})
})
describe('enterprise rut valid', () => {
const rut = '77777777-7'
beforeEach(async () => {
this.room.user.say('user', `hubot info-rut rut ${rut}`)
await sleep(1000)
})
it('should return a full name', () => {
expect(this.room.messages).to.eql([
['user', `hubot info-rut rut ${rut}`],
['hubot', `Sushi (${rut})`]
])
})
})
describe('rut invalid', () => {
const rut = '22222222-2'
beforeEach(async () => {
this.room.user.say('user', `hubot info-rut rut ${rut}`)
await sleep(1000)
})
it('should return a error', () => {
expect(this.room.messages).to.eql([
['user', `hubot info-rut rut ${rut}`],
['hubot', '@user rut sin resultados']
])
})
})
describe('rut error', () => {
const rut = '1'
beforeEach(async () => {
this.room.user.say('user', `hubot info-rut rut ${rut}`)
await sleep(1000)
})
it('should return a error', () => {
expect(this.room.messages).to.eql([
['user', `hubot info-rut rut ${rut}`],
['hubot', '@user ocurrio un error al consultar el rut']
])
})
})
describe('name valid', () => {
const name = 'juan perez perez'
beforeEach(async () => {
this.room.user.say('user', `hubot info-rut persona ${name}`)
await sleep(1000)
})
it('should return a array of results with link', () => {
expect(this.room.messages).to.eql([
['user', `hubot info-rut persona ${name}`],
[
'hubot',
'Anonymous (11.111.111-1)\n' +
'Anonymous (11.111.111-1)\n' +
'Anonymous (11.111.111-1)\n' +
'Anonymous (11.111.111-1)\n' +
'Anonymous (11.111.111-1)\n' +
'Más resultados en ' +
'http://localhost:8080/info-rut?name=juan%20perez%20perez&' +
'type=persona'
]
])
})
})
describe('name valid', () => {
const name = 'soto'
beforeEach(async () => {
this.room.user.say('user', `hubot info-rut persona ${name}`)
await sleep(500)
})
it('should return a array of results', () => {
expect(this.room.messages).to.eql([
['user', `hubot info-rut persona ${name}`],
[
'hubot',
'Anonymous (11.111.111-1)\n' +
'Anonymous (11.111.111-1)\n' +
'Anonymous (11.111.111-1)\n' +
'Anonymous (11.111.111-1)\n' +
'Anonymous (11.111.111-1)'
]
])
})
})
describe('name without results', () => {
const name = 'info-rut'
beforeEach(async () => {
this.room.user.say('user', `hubot info-rut empresa ${name}`)
await sleep(500)
})
it('should return a empty results', () => {
expect(this.room.messages).to.eql([
['user', `hubot info-rut empresa ${name}`],
['hubot', `@user no hay resultados para ${name}`]
])
})
})
describe('name invalid', () => {
const name = 'asdf'
beforeEach(async () => {
this.room.user.say('user', `hubot info-rut persona ${name}`)
await sleep(500)
})
it('should return a empty results', () => {
expect(this.room.messages).to.eql([
['user', `hubot info-rut persona ${name}`],
['hubot', '@user ocurrio un error al consultar el nombre']
])
})
})
describe('GET /info-rut?name=perez&type=persona', () => {
beforeEach(async () => {
this.response = await request(
'http://localhost:8080/info-rut?name=juan%20perez%20perez&type=persona'
)
})
it('responds with status 200 and results', () => {
expect(this.response.statusCode).to.equal(200)
expect(this.response.body).to.equal(
'Anonymous (11.111.111-1)<br/>' +
'Anonymous (11.111.111-1)<br/>' +
'Anonymous (11.111.111-1)<br/>' +
'Anonymous (11.111.111-1)<br/>' +
'Anonymous (11.111.111-1)<br/>' +
'Anonymous (11.111.111-1)'
)
})
})
describe('GET /info-rut?name=perez&type=empresa', () => {
beforeEach(async () => {
this.response = await request(
'http://localhost:8080/info-rut?name=perez&type=empresa'
)
})
it('responds with status 200 and results', () => {
expect(this.response.statusCode).to.equal(200)
expect(this.response.body).to.equal('Anonymous (11.111.111-1)')
})
})
describe('GET /info-rut?name=info-rut&type=persona', () => {
beforeEach(async () => {
this.response = await request(
'http://localhost:8080/info-rut?name=info-rut&type=persona'
)
})
it('responds with status 200 and not results', () => {
expect(this.response.statusCode).to.equal(200)
expect(this.response.body).to.equal('no hay resultados para info-rut')
})
})
describe('GET /info-rut', () => {
beforeEach(async () => {
this.response = await request('http://localhost:8080/info-rut')
})
it('responds with status 200 and not results', () => {
expect(this.response.statusCode).to.equal(200)
expect(this.response.body).to.equal('faltan los parametros type y name')
})
})
describe('GET /info-rut?name=asdf&type=persona', () => {
beforeEach(async () => {
this.response = await request(
'http://localhost:8080/info-rut?name=asdf&type=persona'
)
})
it('responds with status 200 and not results', () => {
expect(this.response.statusCode).to.equal(200)
expect(this.response.body).to.equal(
'Ocurrio un error al consultar el nombre'
)
})
})
})
| Java |
module Modernizr
module Rails
class Engine < ::Rails::Engine
end
end
end
| Java |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Fungus
{
// <summary>
/// Add force to a Rigidbody2D
/// </summary>
[CommandInfo("Rigidbody2D",
"AddForce2D",
"Add force to a Rigidbody2D")]
[AddComponentMenu("")]
public class AddForce2D : Command
{
[SerializeField]
protected Rigidbody2DData rb;
[SerializeField]
protected ForceMode2D forceMode = ForceMode2D.Force;
public enum ForceFunction
{
AddForce,
AddForceAtPosition,
AddRelativeForce
}
[SerializeField]
protected ForceFunction forceFunction = ForceFunction.AddForce;
[Tooltip("Vector of force to be added")]
[SerializeField]
protected Vector2Data force;
[Tooltip("Scale factor to be applied to force as it is used.")]
[SerializeField]
protected FloatData forceScaleFactor = new FloatData(1);
[Tooltip("World position the force is being applied from. Used only in AddForceAtPosition")]
[SerializeField]
protected Vector2Data atPosition;
public override void OnEnter()
{
switch (forceFunction)
{
case ForceFunction.AddForce:
rb.Value.AddForce(force.Value * forceScaleFactor.Value, forceMode);
break;
case ForceFunction.AddForceAtPosition:
rb.Value.AddForceAtPosition(force.Value * forceScaleFactor.Value, atPosition.Value, forceMode);
break;
case ForceFunction.AddRelativeForce:
rb.Value.AddRelativeForce(force.Value * forceScaleFactor.Value, forceMode);
break;
default:
break;
}
Continue();
}
public override string GetSummary()
{
return forceMode.ToString() + ": " + force.ToString();
}
public override Color GetButtonColor()
{
return new Color32(235, 191, 217, 255);
}
public override bool HasReference(Variable variable)
{
if (rb.rigidbody2DRef == variable || force.vector2Ref == variable || forceScaleFactor.floatRef == variable ||
atPosition.vector2Ref == variable)
return true;
return false;
}
}
} | Java |
// package metadata file for Meteor.js
Package.describe({
name: 'startup-cafe',
"author": "Dragos Mateescu <dmateescu@tremend.ro>",
"licenses": [
{
"type": "MIT",
"url": "http://opensource.org/licenses/MIT"
}
],
"scripts": {
},
"engines": {
"node": ">= 0.10.0"
},
"devDependencies": {
"grunt": "~0.4.5",
"grunt-autoprefixer": "~0.8.1",
"grunt-contrib-concat": "~0.4.0",
"grunt-contrib-jshint": "~0.10.0",
"grunt-contrib-less": "~0.11.3",
"grunt-contrib-uglify": "~0.5.0",
"grunt-contrib-watch": "~0.6.1",
"grunt-contrib-clean": "~ v0.6.0",
"grunt-modernizr": "~0.5.2",
"grunt-stripmq": "0.0.6",
"grunt-wp-assets": "~0.2.6",
"load-grunt-tasks": "~0.6.0",
"time-grunt": "~0.3.2",
"grunt-bless": "^0.1.1"
}
});
Package.onUse(function (api) {
api.versionsFrom('METEOR@1.0');
api.use('jquery', 'client');
api.addFiles([
'dist/fonts/glyphicons-halflings-regular.eot',
'dist/fonts/glyphicons-halflings-regular.svg',
'dist/fonts/glyphicons-halflings-regular.ttf',
'dist/fonts/glyphicons-halflings-regular.woff',
'dist/fonts/glyphicons-halflings-regular.woff2',
'dist/css/bootstrap.css',
'dist/js/bootstrap.js',
], 'client');
});
| Java |
exports.engine = function(version){
version = version || null;
switch (version){
case null:
case '0.8.2':
return require('./0.8.2').engine;
default:
return null;
}
};
| Java |
/* This is a managed file. Do not delete this comment. */
#include <include/lifecycle.h>
static void echo(lifecycle_Foo this, char* hook) {
corto_state s = corto_stateof(this);
char *stateStr = corto_ptr_str(&s, corto_state_o, 0);
corto_info("callback: %s [%s]",
hook,
stateStr);
free(stateStr);
}
int16_t lifecycle_Foo_construct(
lifecycle_Foo this)
{
echo(this, "construct");
return 0;
}
void lifecycle_Foo_define(
lifecycle_Foo this)
{
echo(this, "define");
}
void lifecycle_Foo_deinit(
lifecycle_Foo this)
{
echo(this, "deinit");
}
void lifecycle_Foo_delete(
lifecycle_Foo this)
{
echo(this, "delete");
}
void lifecycle_Foo_destruct(
lifecycle_Foo this)
{
echo(this, "destruct");
}
int16_t lifecycle_Foo_init(
lifecycle_Foo this)
{
echo(this, "init");
return 0;
}
void lifecycle_Foo_update(
lifecycle_Foo this)
{
echo(this, "update");
}
int16_t lifecycle_Foo_validate(
lifecycle_Foo this)
{
echo(this, "validate");
return 0;
}
| Java |
"""
http://community.topcoder.com/stat?c=problem_statement&pm=1667
Single Round Match 147 Round 1 - Division II, Level One
"""
class CCipher:
def decode(self, cipherText, shift):
a = ord('A')
decoder = [a + (c - shift if c >= shift else c - shift + 26) for c in range(26)]
plain = [chr(decoder[ord(c) - a]) for c in cipherText]
return ''.join(plain)
| Java |
'use strict';
var Killable = artifacts.require('../contracts/lifecycle/Killable.sol');
require('./helpers/transactionMined.js');
contract('Killable', function(accounts) {
it('should send balance to owner after death', async function() {
let killable = await Killable.new({from: accounts[0], value: web3.toWei('10','ether')});
let owner = await killable.owner();
let initBalance = web3.eth.getBalance(owner);
await killable.kill({from: owner});
let newBalance = web3.eth.getBalance(owner);
assert.isTrue(newBalance > initBalance);
});
});
| Java |
//
// PCMenuPopView.h
// PCMenuPopDemo
//
// Created by peichuang on 16/6/30.
// Copyright © 2016年 peichuang. All rights reserved.
//
#import <UIKit/UIKit.h>
@class PCMenuPopView;
@protocol PCMenuPopViewDelegate <NSObject>
//返回需要多少个菜单项
- (NSInteger)numberOfitemsInMenuPopView:(PCMenuPopView *)menuPopView;
//配置对应菜单button
- (void)menuPopView:(PCMenuPopView *)menuPopView configureWithMenuItem:(UIButton *)menuButton index:(NSInteger)index;
//配置对应的button的位置
- (CGRect)menuPopView:(PCMenuPopView *)menuPopView rectForMenuItemWithIndex:(NSInteger)index;
@end
@interface PCMenuPopView : UIView
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, weak) id<PCMenuPopViewDelegate>delegate;
- (void)showInView:(UIView *)view withPopButton:(UIButton *)popButton;
- (void)hide;
//根据index可以设置默认位置,从右到左的顺序
- (CGRect)defaultItemRectWithSize:(CGSize)size index:(NSInteger)index;
@end
| Java |
---
layout: post
title: Word Embedding
category: NLP
---
## 基于矩阵的分布表示
* 选取上下文,确定矩阵类型
1. “词-文档”矩阵,非常稀疏
2. “词-词”矩阵,选取词附近上下文中的各个词(如上下文窗口中的5个词),相对稠密
3. “词-n gram词组”,选取词附近上下文各词组成的n元词组,更加精准,但是更加稀疏
* 确定矩阵中各元素的值,包括TF-IDF,PMI,log
* 矩阵分解,包括 SVD,NMF,CCA,HPCA
## 基于神经网络的语言模型
* NNLM basic Language model

* LBL 双线性结构
和nnlm基本类似,只是输出的目标函数稍有不同。
* RNNLM 利用所有的上下文信息,不进行简化(每个词都用上之前看过的所有单词,而不是n个)
一个语言模型的描述

当m很大的时候没法算,因此做了n-gram的估算

在计算右边的公式的时候,一般直接采用频率计数的方法进行计算

由此带来的问题是数据稀疏问题和平滑问题,由此,神经网络语言模型产生。
Bengio Neural Probabilistic Language Model

x是一个分布式向量

### word2vec
前面的模型相对而言都很复杂,然后出了一个CBOW和Skip-gram模型。

没有很多的计算过程,就是根据上下文关系的softmax
| Java |
from hwt.synthesizer.rtlLevel.extract_part_drivers import extract_part_drivers
from hwt.synthesizer.rtlLevel.remove_unconnected_signals import removeUnconnectedSignals
from hwt.synthesizer.rtlLevel.mark_visibility_of_signals_and_check_drivers import markVisibilityOfSignalsAndCheckDrivers
class DummyPlatform():
"""
:note: all processors has to be callable with only one parameter
which is actual Unit/RtlNetlist instance
"""
def __init__(self):
self.beforeToRtl = []
self.beforeToRtlImpl = []
self.afterToRtlImpl = []
self.beforeHdlArchGeneration = [
extract_part_drivers,
removeUnconnectedSignals,
markVisibilityOfSignalsAndCheckDrivers,
]
self.afterToRtl = []
| Java |
using Microsoft.Diagnostics.Tracing;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Management.Automation;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Threading;
namespace EtwStream.PowerShell
{
[Cmdlet(VerbsCommon.Get, "TraceEventStream", DefaultParameterSetName = "nameOrGuid")]
public class GetTraceEvent : PSCmdlet
{
private CompositeDisposable disposable = new CompositeDisposable();
[Parameter(Position = 0, ParameterSetName = "nameOrGuid", Mandatory = true, ValueFromPipeline = true)]
public string[] NameOrGuid { get; set; }
[ValidateSet(
nameof(WellKnownEventSources.AspNetEventSource),
nameof(WellKnownEventSources.ConcurrentCollectionsEventSource),
nameof(WellKnownEventSources.FrameworkEventSource),
nameof(WellKnownEventSources.PinnableBufferCacheEventSource),
nameof(WellKnownEventSources.PlinqEventSource),
nameof(WellKnownEventSources.SqlEventSource),
nameof(WellKnownEventSources.SynchronizationEventSource),
nameof(WellKnownEventSources.TplEventSource))]
[Parameter(Position = 0, ParameterSetName = "wellKnown", Mandatory = true, ValueFromPipeline = true)]
public string[] WellKnownEventSource { get; set; }
[ValidateSet(
nameof(IISEventSources.AspDotNetEvents),
nameof(IISEventSources.HttpEvent),
nameof(IISEventSources.HttpLog),
nameof(IISEventSources.HttpService),
nameof(IISEventSources.IISAppHostSvc),
nameof(IISEventSources.IISLogging),
nameof(IISEventSources.IISW3Svc),
nameof(IISEventSources.RuntimeWebApi),
nameof(IISEventSources.RuntimeWebHttp))]
[Parameter(Position = 0, ParameterSetName = "IIS", Mandatory = true, ValueFromPipeline = true)]
public string[] IISEventSource { get; set; }
[Parameter]
public SwitchParameter DumpWithColor { get; set; }
[Parameter]
public TraceEventLevel TraceLevel { get; set; } = TraceEventLevel.Verbose;
private IObservable<TraceEvent> listener = Observable.Empty<TraceEvent>();
protected override void ProcessRecord()
{
switch (ParameterSetName)
{
case "wellKnown":
listener = listener.Merge(WellKnownEventSource.Select(x => GetWellKnownEventListener(x)).Merge());
break;
case "IIS":
listener = listener.Merge(IISEventSource.Select(x => GetIISEventListener(x)).Merge());
break;
default:
listener = listener.Merge(NameOrGuid.Select(x => ObservableEventListener.FromTraceEvent(x)).Merge());
break;
}
}
protected override void EndProcessing()
{
var q = new BlockingCollection<Action>();
Exception exception = null;
var d = listener
.Where(x => Process.GetCurrentProcess().Id != x.ProcessID)
.Where(x => x.Level <= TraceLevel)
.Subscribe(
x =>
{
q.Add(() =>
{
var item = new PSTraceEvent(x, Host.UI);
if (DumpWithColor.IsPresent)
{
item.DumpWithColor();
}
else
{
WriteObject(item);
}
WriteVerbose(item.DumpPayloadOrMessage());
});
},
e =>
{
exception = e;
q.CompleteAdding();
}, q.CompleteAdding);
disposable.Add(d);
var cts = new CancellationTokenSource();
disposable.Add(new CancellationDisposable(cts));
foreach (var act in q.GetConsumingEnumerable(cts.Token))
{
act();
}
if (exception != null)
{
ThrowTerminatingError(new ErrorRecord(exception, "1", ErrorCategory.OperationStopped, null));
}
}
protected override void StopProcessing()
{
disposable.Dispose();
}
private IObservable<TraceEvent> GetWellKnownEventListener(string wellKnownEventSource)
{
switch (wellKnownEventSource)
{
case nameof(WellKnownEventSources.AspNetEventSource):
return ObservableEventListener.FromTraceEvent(WellKnownEventSources.AspNetEventSource);
case nameof(WellKnownEventSources.ConcurrentCollectionsEventSource):
return ObservableEventListener.FromTraceEvent(WellKnownEventSources.ConcurrentCollectionsEventSource);
case nameof(WellKnownEventSources.FrameworkEventSource):
return ObservableEventListener.FromTraceEvent(WellKnownEventSources.FrameworkEventSource);
case nameof(WellKnownEventSources.PinnableBufferCacheEventSource):
return ObservableEventListener.FromTraceEvent(WellKnownEventSources.PinnableBufferCacheEventSource);
case nameof(WellKnownEventSources.PlinqEventSource):
return ObservableEventListener.FromTraceEvent(WellKnownEventSources.PlinqEventSource);
case nameof(WellKnownEventSources.SqlEventSource):
return ObservableEventListener.FromTraceEvent(WellKnownEventSources.SqlEventSource);
case nameof(WellKnownEventSources.SynchronizationEventSource):
return ObservableEventListener.FromTraceEvent(WellKnownEventSources.SynchronizationEventSource);
case nameof(WellKnownEventSources.TplEventSource):
return ObservableEventListener.FromTraceEvent(WellKnownEventSources.TplEventSource);
default:
return Observable.Empty<TraceEvent>();
}
}
private IObservable<TraceEvent> GetIISEventListener(string iisEventSource)
{
switch (iisEventSource)
{
case nameof(IISEventSources.AspDotNetEvents):
return ObservableEventListener.FromTraceEvent(IISEventSources.AspDotNetEvents);
case nameof(IISEventSources.HttpEvent):
return ObservableEventListener.FromTraceEvent(IISEventSources.HttpEvent);
case nameof(IISEventSources.HttpLog):
return ObservableEventListener.FromTraceEvent(IISEventSources.HttpLog);
case nameof(IISEventSources.HttpService):
return ObservableEventListener.FromTraceEvent(IISEventSources.HttpService);
case nameof(IISEventSources.IISAppHostSvc):
return ObservableEventListener.FromTraceEvent(IISEventSources.IISAppHostSvc);
case nameof(IISEventSources.IISLogging):
return ObservableEventListener.FromTraceEvent(IISEventSources.IISLogging);
case nameof(IISEventSources.IISW3Svc):
return ObservableEventListener.FromTraceEvent(IISEventSources.IISW3Svc);
case nameof(IISEventSources.RuntimeWebApi):
return ObservableEventListener.FromTraceEvent(IISEventSources.RuntimeWebApi);
case nameof(IISEventSources.RuntimeWebHttp):
return ObservableEventListener.FromTraceEvent(IISEventSources.RuntimeWebHttp);
default:
return Observable.Empty<TraceEvent>();
}
}
}
}
| Java |
package com.yunpian.sdk.model;
/**
* Created by bingone on 15/11/8.
*/
public class VoiceSend extends BaseInfo {
}
| Java |
package com.ipvans.flickrgallery.ui.main;
import android.util.Log;
import com.ipvans.flickrgallery.data.SchedulerProvider;
import com.ipvans.flickrgallery.di.PerActivity;
import com.ipvans.flickrgallery.domain.FeedInteractor;
import com.ipvans.flickrgallery.domain.UpdateEvent;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.subjects.BehaviorSubject;
import io.reactivex.subjects.PublishSubject;
import static com.ipvans.flickrgallery.ui.main.MainViewState.*;
@PerActivity
public class MainPresenterImpl implements MainPresenter<MainViewState> {
private final FeedInteractor interactor;
private final SchedulerProvider schedulers;
private BehaviorSubject<MainViewState> stateSubject = BehaviorSubject.createDefault(empty());
private PublishSubject<UpdateEvent> searchSubject = PublishSubject.create();
private Disposable disposable = new CompositeDisposable();
@Inject
public MainPresenterImpl(FeedInteractor interactor, SchedulerProvider schedulers) {
this.interactor = interactor;
this.schedulers = schedulers;
}
@Override
public void onAttach() {
Observable.combineLatest(searchSubject
.debounce(150, TimeUnit.MILLISECONDS, schedulers.io())
.doOnNext(interactor::getFeed),
interactor.observe(),
(tags, feed) -> new MainViewState(feed.isLoading(),
feed.getError(), feed.getData(), tags.getTags()))
.withLatestFrom(stateSubject,
(newState, oldState) -> new MainViewState(
newState.isLoading(), newState.getError(),
newState.getData() != null ? newState.getData() : oldState.getData(),
newState.getTags()
))
.observeOn(schedulers.io())
.subscribeWith(stateSubject)
.onSubscribe(disposable);
}
@Override
public void onDetach() {
disposable.dispose();
}
@Override
public void restoreState(MainViewState data) {
stateSubject.onNext(data);
}
@Override
public Observable<MainViewState> observe() {
return stateSubject;
}
@Override
public MainViewState getLatestState() {
return stateSubject.getValue();
}
@Override
public void search(String tags, boolean force) {
searchSubject.onNext(new UpdateEvent(tags, force));
}
}
| Java |
package aaron.org.anote.viewbinder;
import android.app.Activity;
import android.os.Bundle;
public class DynamicActivity extends Activity {
@Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
Layout.start(this);
}
}
| Java |
'use strict';
describe('Directive: resize', function () {
// load the directive's module
beforeEach(module('orderDisplayApp'));
var element,
scope;
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new();
}));
//TODO: Add unit tests
/*it('should change height', inject(function ($compile, $window) {
element = angular.element('<resize></resize>');
element = $compile(element)(scope);
expect(scope.screenHeight).toBe($window.outerHeight);
}));*/
});
| Java |
/*
* Copyright (c) 2005 Dizan Vasquez.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.jenet;
import java.nio.ByteBuffer;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
/**
* Wraps information to be sent through JeNet.
* @author Dizan Vasquez
*/
public class Packet implements IBufferable {
/**
* Indicates that this packet is reliable
*/
public static final int FLAG_RELIABLE = 1;
/**
* Indicates that the packet should be processed no
* matter its order relative to other packets.
*/
public static final int FLAG_UNSEQUENCED = 2;
protected int referenceCount;
protected int flags;
protected ByteBuffer data;
protected int dataLength;
private Packet() {
super();
}
/**
* Creates a new Packet.
* The constructor allocates a new packet and allocates a
* buffer of <code>dataLength</code> bytes for it.
*
* @param dataLength
* The size in bytes of this packet.
* @param flags
* An byte inidicating the how to handle this packet.
*/
public Packet( int dataLength, int flags ) {
data = ByteBuffer.allocateDirect( dataLength );
this.dataLength = dataLength;
this.flags = flags;
}
/**
* Copies this packet's data into the given buffer.
* @param buffer
* Destination buffer
*/
public void toBuffer( ByteBuffer buffer ) {
data.flip();
for ( int i = 0; i < dataLength; i++ ) {
buffer.put( data.get() );
}
}
/**
* Copies part of this packet's data into the given buffer.
* @param buffer
* Destination buffer
* @param offset
* Initial position of the destination buffer
* @param length
* Total number of bytes to copy
*/
public void toBuffer( ByteBuffer buffer, int offset, int length ) {
int position = data.position();
int limit = data.limit();
data.flip();
data.position( offset );
for ( int i = 0; i < length; i++ ) {
buffer.put( data.get() );
}
data.position( position );
data.limit( limit );
}
/**
* Copies the given buffer into this packet's data.
* @ param buffer
* Buffer to copy from
*/
public void fromBuffer( ByteBuffer buffer ) {
data.clear();
for ( int i = 0; i < dataLength; i++ ) {
data.put( buffer.get() );
}
}
/**
* Copies part of the given buffer into this packet's data.
* @param buffer
* Buffer to copy from
* @param fragmentOffset
* Position of the first byte to copy
* @param length
* Total number of bytes to copy
*/
public void fromBuffer( ByteBuffer buffer, int fragmentOffset, int length ) {
data.position( fragmentOffset );
for ( int i = 0; i < length; i++ ) {
data.put( buffer.get() );
}
data.position( dataLength );
data.limit( dataLength );
}
/**
* Returs size of this packet.
* @return Size in bytes of this packet
*/
public int byteSize() {
return dataLength;
}
/**
* Returns the data contained in this packet
* @return Returns the data.
*/
public ByteBuffer getData() {
return data;
}
/**
* Returns the size in bytes of this packet's data
* @return Returns the dataLength.
*/
public int getDataLength() {
return dataLength;
}
/**
* Returns this packet's flags.
* @return Returns the flags.
*/
public int getFlags() {
return flags;
}
/**
* @return Returns the referenceCount.
*/
int getReferenceCount() {
return referenceCount;
}
/**
* Sets the flags for this packet.
* The parameter is an or of the flags <code>FLAG_RELIABLE</code> and <code>FLAG_UNSEQUENCED</code>
* a value of zero indicates an unreliable, sequenced (last one is kept) packet.
* @param flags
* The flags to set.
*/
public void setFlags( int flags ) {
this.flags = flags;
}
/**
* @param referenceCount
* The referenceCount to set.
*/
void setReferenceCount( int referenceCount ) {
this.referenceCount = referenceCount;
}
public String toString() {
return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE );
}
} | Java |
'use strict';
angular.module('core').controller('HomeController', ['$scope', 'Authentication', '$http', '$modal','$rootScope',
function($scope, Authentication, $http, $modal, $rootScope) {
// This provides Authentication context.
$scope.authentication = Authentication;
$scope.card = {};
$scope.columnWidth = function() {
return Math.floor((100 / $scope.columns.length) * 100) / 100;
};
$scope.updateCard = function(column, card) {
var modalInstance = $modal.open({
templateUrl: '/modules/core/views/card-details.client.view.html',
controller: modalController,
size: 'lg',
resolve: {
items: function() {
return angular.copy({
title: card.title,
Details: card.details,
release: card.release,
cardColor: card.ragStatus,
column: column,
architect: card.architect,
analyst: card.Analyst,
designer: card.designer,
buildCell: card.buildCell
});
}
}
});
modalInstance.result.then(function(result) {
console.log(result.title);
angular.forEach($scope.columns, function(col) {
if(col.name === column.name) {
angular.forEach(col.cards, function(cd) {
if (cd.title === card.title) {
if (col.name === 'Backlog') {
cd.details = result.Details;
} else {
cd.details = result.Details;
if (result.cardColor) {
cd.ragStatus = '#' + result.cardColor;
} else {
cd.ragStatus = '#5CB85C';
}
cd.release = result.release;
cd.architect = result.architect;
cd.designer = result.designer;
cd.Analyst = result.analyst;
cd.buildCell = result.buildCell
}
}
});
}
});
console.log('modal closed');
}, function() {
console.log('modal dismissed');
});
//setTimeout(function() {
// $scope.$apply(function(){
// console.log('broadcasting event');
// $rootScope.$broadcast('OpenCardDetails', column, card);
// });
//}, 500);
};
var modalController = function($scope, $modalInstance, items) {
$scope.colorOptions = ['5CB85C','FFEB13','FF0000'];
console.log(items.column.name);
$scope.card = items;
$scope.ok = function () {
//events();
$modalInstance.close($scope.card);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
$scope.$on('OpenCardDetails', function(e, column,card) {
console.log('in broadcast event');
console.log(column.name);
$scope.card = card;
});
$scope.columns = [
{'name': 'Backlog',cards: [{'id': '1', 'title': 'item1', 'drag':true, 'release':"",'ragStatus':'#5cb85c', 'details':"",'architect':"", 'Analyst':"",'designer':"",'buildCell':""},
{'id': '2','title': 'item2', 'drag':true, 'release':"",'ragStatus':'#5cb85c', 'details':"",'architect':"", 'Analyst':"",'designer':"",'buildCell':""},
{'id': '3','title': 'item3', 'drag':true, 'release':"",'ragStatus':'#ffeb13', 'details':"",'architect':"", 'Analyst':"",'designer':"",'buildCell':""},
{'id': '4','title': 'item4', 'drag':true, 'release':"",'ragStatus':'#5cb85c', 'details':"",'architect':"", 'Analyst':"",'designer':"",'buildCell':""},
{'id': '5','title': 'item5', 'drag':true, 'release':"",'ragStatus':'#ff0000', 'details':"",'architect':"", 'Analyst':"",'designer':"",'buildCell':""},
{'id': '6','title': 'item6', 'drag':true, 'release':"",'ragStatus':'#5cb85c', 'details':"",'architect':"", 'Analyst':"",'designer':"",'buildCell':""}], 'hideCol':false},
{'name': 'Discovery',cards: [], 'hideCol':false},
{'name': 'Design',cards: [], 'hideCol':false},
{'name': 'Build',cards: [], 'hideCol':false},
{'name': 'Pilot',cards: [], 'hideCol':false}
];
$scope.hiddenCol = function(column) {
angular.forEach($scope.columns, function(col) {
if(col.name === column.name) {
if(column.hideCol === true) {
column.hideCol = false;
} else {
column.hideCol = true;
}
}
});
};
$scope.addCard = function(column) {
angular.forEach($scope.columns, function(col){
if(col.name === column.name) {
column.cards.push({'title': 'item8','drag':true});
}
});
};
$scope.list1 = [
{'title': 'item1', 'drag':true},
{'title': 'item2', 'drag':true},
{'title': 'item3', 'drag':true},
{'title': 'item4', 'drag':true},
{'title': 'item5', 'drag':true},
{'title': 'item6', 'drag':true}
];
$scope.list2 = [];
$scope.sortableOptions = {
//containment: '#sortable-container1'
};
$scope.sortableOptions1 = {
//containment: '#sortable-container2'
};
$scope.removeCard = function(column, card) {
angular.forEach($scope.columns, function(col) {
if (col.name === column.name) {
col.cards.splice(col.cards.indexOf(card), 1);
}
});
};
$scope.dragControlListeners = {
itemMoved: function (event) {
var releaseVar = '';
var columnName = event.dest.sortableScope.$parent.column.name;
if (columnName === 'Backlog') {
releaseVar = '';
} else {
//releaseVar = prompt('Enter Release Info !');
}
angular.forEach($scope.columns, function(col) {
if (col.name === columnName) {
angular.forEach(col.cards, function(card) {
if (card.title === event.source.itemScope.modelValue.title) {
if (releaseVar === ' ' || releaseVar.length === 0) {
releaseVar = 'Rel';
}
card.release = releaseVar;
}
});
}
});
}
};
}
]);
| Java |
/*eslint-disable */
var webpack = require( "webpack" );
var sml = require( "source-map-loader" );
/*eslint-enable */
var path = require( "path" );
module.exports = {
module: {
preLoaders: [
{
test: /\.js$/,
loader: "source-map-loader"
}
],
loaders: [
{ test: /sinon.*\.js/, loader: "imports?define=>false" },
{ test: /\.spec\.js$/, exclude: /node_modules/, loader: "babel-loader" }
],
postLoaders: [ {
test: /\.js$/,
exclude: /(spec|node_modules)\//,
loader: "istanbul-instrumenter"
} ]
},
resolve: {
alias: {
"when.parallel": "when/parallel",
"when.pipeline": "when/pipeline",
react: "react/dist/react-with-addons.js",
lux: path.join( __dirname, "./lib/lux.js" )
}
}
};
| Java |
import {Component, OnInit} from '@angular/core';
import {ActivityService} from '../../services/activity.service';
import {Activity} from "../../models/activity";
import {BarChartComponent} from "../bar-chart/bar-chart.component";
@Component({
selector: 'records-view',
moduleId: module.id,
templateUrl: 'records-view.component.html',
styleUrls: ['records-view.component.css'],
directives: [BarChartComponent]
})
export class RecordsViewComponent implements OnInit {
calBurnActs:Activity[];
longestActs:Activity[];
constructor(private activityService:ActivityService) {
}
getData() {
this.activityService.getActivities('totalCalories','desc',6).then(
data => this.calBurnActs = data
);
this.activityService.getActivities('totalDistance','desc',6).then(
data => this.longestActs = data
);
}
ngOnInit() {
this.getData();
}
} | Java |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
RJUST = 12
def format_fans(fans):
return format_line(prefix='fans'.rjust(RJUST), values=fans)
def format_rpms(rpms):
return format_line(prefix='rpms'.rjust(RJUST), values=rpms)
def format_pwms(pwms):
return format_line(prefix='pwms'.rjust(RJUST), values=pwms)
def format_tmps(tmps):
return format_line(prefix='temps'.rjust(RJUST), values=tmps)
def format_names(names):
return format_line(prefix='names'.rjust(RJUST), values=names)
def format_ports(ports):
return format_line(prefix='ports'.rjust(RJUST), values=ports)
def format_temps(temps):
return format_line(prefix='temps'.rjust(RJUST), values=temps)
def format_ambients(ambients):
return format_line(prefix='ambients'.rjust(RJUST), values=ambients)
def format_limits(limits):
return format_line(prefix='limits'.rjust(RJUST), values=limits)
def format_buffers(buffers):
return format_line(prefix='buffers'.rjust(RJUST), values=buffers)
def format_headrooms(headrooms):
return format_line(prefix='headrooms'.rjust(RJUST), values=headrooms)
def format_directions(directions):
return format_line(prefix='directions'.rjust(RJUST), values=directions)
def format_differences(differences):
return format_line(prefix='differences'.rjust(RJUST), values=differences)
def format_pwms_new(pwms_new):
return format_line(prefix='new pwms'.rjust(RJUST), values=pwms_new)
def format_line(prefix, values):
line = ''
line += prefix
line += ': '
line += '['
for value in values:
try:
if value >= 1:
value = int(round(value, 0))
if 1 > value != 0:
value = str(value)[1:4].ljust(3, '0')
except TypeError:
# value is None
pass
value = str(value) if value is not None else ''
line += value.rjust(6)
line += ', '
line = line[:-len(', ')]
line += ']'
return line
| Java |
/* /////////////////////////////////////////////////////////////////////////
* File: stlsoft/conversion/internal/explicit_cast_specialisations.hpp
*
* Purpose: Specialisations of explicit_cast
*
* Created: 13th August 2003
* Updated: 10th August 2009
*
* Home: http://stlsoft.org/
*
* Copyright (c) 2003-2009, Matthew Wilson and Synesis Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name(s) of Matthew Wilson and Synesis Software nor the names of
* any contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* ////////////////////////////////////////////////////////////////////// */
/** \file stlsoft/conversion/internal/explicit_cast_specialisations.hpp
*
* \brief [C++ only] Explicit specialisations of stlsoft::explicit_cast
* (\ref group__library__conversion "Conversion" Library).
*/
#ifndef STLSOFT_INCL_STLSOFT_CONVERSION_HPP_EXPLICIT_CAST
# error This file is included from within stlsoft/conversion/explicit_cast.hpp, and cannot be included directly
#else
#ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION
# define STLSOFT_VER_STLSOFT_CONVERSION_INTERNAL_HPP_EXPLICIT_CAST_SPECIALISATIONS_MAJOR 4
# define STLSOFT_VER_STLSOFT_CONVERSION_INTERNAL_HPP_EXPLICIT_CAST_SPECIALISATIONS_MINOR 0
# define STLSOFT_VER_STLSOFT_CONVERSION_INTERNAL_HPP_EXPLICIT_CAST_SPECIALISATIONS_REVISION 1
# define STLSOFT_VER_STLSOFT_CONVERSION_INTERNAL_HPP_EXPLICIT_CAST_SPECIALISATIONS_EDIT 21
#endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */
/* /////////////////////////////////////////////////////////////////////////
* Auto-generation and compatibility
*/
/*
[<[STLSOFT-AUTO:NO-UNITTEST]>]
[<[STLSOFT-AUTO:NO-DOCFILELABEL]>]
*/
/* /////////////////////////////////////////////////////////////////////////
* Specialisations
*/
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<char const&>
{
public:
typedef char value_type;
typedef explicit_cast<char> class_type;
// Construction
public:
explicit_cast(char const& t)
: m_t(t)
{}
// Conversions
public:
operator char const& () const
{
return m_t;
}
// Members
private:
char const& m_t;
};
#ifdef STLSOFT_CF_NATIVE_WCHAR_T_SUPPORT
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<wchar_t const&>
{
public:
typedef wchar_t value_type;
typedef explicit_cast<wchar_t> class_type;
// Construction
public:
explicit_cast(wchar_t const& t)
: m_t(t)
{}
// Conversions
public:
operator wchar_t const& () const
{
return m_t;
}
// Members
private:
wchar_t const& m_t;
};
#endif /* STLSOFT_CF_NATIVE_WCHAR_T_SUPPORT */
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<unsigned char const&>
{
public:
typedef unsigned char value_type;
typedef explicit_cast<unsigned char> class_type;
// Construction
public:
explicit_cast(unsigned char const& t)
: m_t(t)
{}
// Conversions
public:
operator unsigned char const& () const
{
return m_t;
}
// Members
private:
unsigned char const& m_t;
};
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<signed char const&>
{
public:
typedef signed char value_type;
typedef explicit_cast<signed char> class_type;
// Construction
public:
explicit_cast(signed char const& t)
: m_t(t)
{}
// Conversions
public:
operator signed char const& () const
{
return m_t;
}
// Members
private:
signed char const& m_t;
};
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<signed short const&>
{
public:
typedef signed short value_type;
typedef explicit_cast<signed short> class_type;
// Construction
public:
explicit_cast(signed short const& t)
: m_t(t)
{}
// Conversions
public:
operator signed short const& () const
{
return m_t;
}
// Members
private:
signed short const& m_t;
};
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<unsigned short const&>
{
public:
typedef unsigned short value_type;
typedef explicit_cast<unsigned short> class_type;
// Construction
public:
explicit_cast(unsigned short const& t)
: m_t(t)
{}
// Conversions
public:
operator unsigned short const& () const
{
return m_t;
}
// Members
private:
unsigned short const& m_t;
};
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<signed int const&>
{
public:
typedef signed int value_type;
typedef explicit_cast<signed int> class_type;
// Construction
public:
explicit_cast(signed int const& t)
: m_t(t)
{}
// Conversions
public:
operator signed int const& () const
{
return m_t;
}
// Members
private:
signed int const& m_t;
};
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<unsigned int const&>
{
public:
typedef unsigned int value_type;
typedef explicit_cast<unsigned int> class_type;
// Construction
public:
explicit_cast(unsigned int const& t)
: m_t(t)
{}
// Conversions
public:
operator unsigned int const& () const
{
return m_t;
}
// Members
private:
unsigned int const& m_t;
};
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<signed long const&>
{
public:
typedef signed long value_type;
typedef explicit_cast<signed long> class_type;
// Construction
public:
explicit_cast(signed long const& t)
: m_t(t)
{}
// Conversions
public:
operator signed long const& () const
{
return m_t;
}
// Members
private:
signed long const& m_t;
};
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<unsigned long const&>
{
public:
typedef unsigned long value_type;
typedef explicit_cast<unsigned long> class_type;
// Construction
public:
explicit_cast(unsigned long const& t)
: m_t(t)
{}
// Conversions
public:
operator unsigned long const& () const
{
return m_t;
}
// Members
private:
unsigned long const& m_t;
};
#ifdef STLSOFT_CF_64BIT_INT_IS_long_long
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<signed long long const&>
{
public:
typedef signed long long value_type;
typedef explicit_cast<signed long long> class_type;
// Construction
public:
explicit_cast(signed long long const& t)
: m_t(t)
{}
// Conversions
public:
operator signed long long const& () const
{
return m_t;
}
// Members
private:
signed long long const& m_t;
};
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<unsigned long long const&>
{
public:
typedef unsigned long long value_type;
typedef explicit_cast<unsigned long long> class_type;
// Construction
public:
explicit_cast(unsigned long long const& t)
: m_t(t)
{}
// Conversions
public:
operator unsigned long long const& () const
{
return m_t;
}
// Members
private:
unsigned long long const& m_t;
};
#elif defined(STLSOFT_CF_64BIT_INT_IS___int64)
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<signed __int64 const&>
{
public:
typedef signed __int64 value_type;
typedef explicit_cast<signed __int64> class_type;
// Construction
public:
explicit_cast(signed __int64 const& t)
: m_t(t)
{}
// Conversions
public:
operator signed __int64 const& () const
{
return m_t;
}
// Members
private:
signed __int64 const& m_t;
};
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<unsigned __int64 const&>
{
public:
typedef unsigned __int64 value_type;
typedef explicit_cast<unsigned __int64> class_type;
// Construction
public:
explicit_cast(unsigned __int64 const& t)
: m_t(t)
{}
// Conversions
public:
operator unsigned __int64 const& () const
{
return m_t;
}
// Members
private:
unsigned __int64 const& m_t;
};
#else
# error 64-bit discrimination not handled correctly
#endif /* 64-bit */
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<float const&>
{
public:
typedef float value_type;
typedef explicit_cast<float> class_type;
// Construction
public:
explicit_cast(float const& t)
: m_t(t)
{}
// Conversions
public:
operator float const& () const
{
return m_t;
}
// Members
private:
float const& m_t;
};
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<double const&>
{
public:
typedef double value_type;
typedef explicit_cast<double> class_type;
// Construction
public:
explicit_cast(double const& t)
: m_t(t)
{}
// Conversions
public:
operator double const& () const
{
return m_t;
}
// Members
private:
double const& m_t;
};
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<long double const&>
{
public:
typedef long double value_type;
typedef explicit_cast<long double> class_type;
// Construction
public:
explicit_cast(long double const& t)
: m_t(t)
{}
// Conversions
public:
operator long double const& () const
{
return m_t;
}
// Members
private:
long double const& m_t;
};
#ifdef STLSOFT_CF_NATIVE_BOOL_SUPPORT
STLSOFT_TEMPLATE_SPECIALISATION
class explicit_cast<bool const&>
{
public:
typedef bool value_type;
typedef explicit_cast<bool> class_type;
// Construction
public:
explicit_cast(bool const& t)
: m_t(t)
{}
// Conversions
public:
operator bool const& () const
{
return m_t;
}
// Members
private:
bool const& m_t;
};
#endif /* STLSOFT_CF_NATIVE_BOOL_SUPPORT */
/* ////////////////////////////////////////////////////////////////////// */
#endif /* !STLSOFT_INCL_STLSOFT_CONVERSION_HPP_EXPLICIT_CAST */
/* ///////////////////////////// end of file //////////////////////////// */
| Java |
<!-- 説明、ファイル操作・読み込み -->
# ファイル操作(読み込み)
ではファイルの内容を読み込めるようにしましょう。
ファイル操作は
- ファイルを開く(fopen)
- ファイルの中身を読み込む(fgets)
- ファイルを閉じる(fclose)
という手順になります。
それぞれを説明します
## fopen
ファイルを開き、ファイルハンドルを返します。
ファイルハンドルとはファイルを特定するIDのようなもので、この後読み込むときやファイルを閉じるときに必要になります。
```
fopen(ファイル名, モード);
```
の形式で使われます。
モードには大きく3つあり,
- r:読み込み(ファイルポインタはファイルの先頭)
- w:書き込み(ファイルポインタはファイルの先頭)
- a:書き込み(ファイルポインタはファイルの最後)
のようになります。
たとえば、file01.txtを読み込みモードで開く時は
```
$fp = fopen('file01.txt', 'r');
```
のようになります。
## fclose
fopenで開いたファイルを閉じます。必ずfopenで開いたファイルは閉じるようにしましょう。
```
fclose($fp);
```
## fgets
fopenで開いたファイルを1行ずつ読み込みます。
先のfopen,fcloseと組み合わせると例えば以下のように使われます。
```
if (($fp = fopen($filename, 'r')) !== FALSE) {
while (($tmp = fgets($fp)) !== FALSE) {
$data[] = htmlspecialchars($tmp, ENT_QUOTES, 'UTF-8');
}
fclose($fp);
}
```
このように書くことで、1行ずつ最後まで読み込まれ、1行ずつのデータが$dataという配列の1行ずつに格納されます。
| Java |
<!DOCTYPE html>
<html>
<head>
<title>JAVASCRIPT BASICS</title>
<meta charset="UTF-8">
<link href="../styles/main.css" rel="stylesheet" type="text/css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css">
<link rel="stylesheet" href="styles/main.css">
<link href="https://fonts.googleapis.com/css?family=Amatic+SC|Fredericka+the+Great" rel="stylesheet">
</head>
<body>
<h1>JAVASCRIPT BASICS</h1>
<div class="container">
<h4>Technical Blog Part Four</h4>
<h5>Terminology: "Learning the Lingo"</h5>
<strong>How does JavaScript compare to HTML and CSS?</strong>
<p>
<strong><em>JavaScript</em></strong> compares differently to HTML and CSS as it is used for website functionality, this means it is able to process data and tells a page how to behave, where as HTML dictates structure, i.e. how the contents is divided, and CSS dictates style, i.e. how the page looks.
</p>
<strong> Explain control flow and loops using an example process from everyday life.</strong>
<p>
<strong><em>Control flow</em></strong> is the order in which the computer executes statements. <em>Loops</em> offer a quick and easy way to do something repeatedly, changing the control flow of the code. An example of this in daily life would be the process of waking up. The control flow when you wake up is that your alarm goes off, you turn alarm off, you wake up and you take a shower. However as we all know we like to snooze so sometimes when our alarm goes off we will snooze and go back to bed. A loop would then check that we haven't woken up and so the code to take a shower will not run until the condition of us waking up is met. If we are already awake when the alarm goes off the loop will not run at all as the condition has been met.
</p>
<strong>Explain the difference between accessing data from arrays and objects</strong>
<p>
The difference between accessing data from arrays and objects is that data from an array can only be accessed through bracket notation where as data from an object can be accessed with bracket and dot notation. Also I think arrays are ordered so that you can only add/remove the first and last element where as you can add/remove or modify any property within an object as long as you know the property name.
</p>
<strong>Explain what functions are and why they are useful</strong>
<p>
<strong><em>Functions</em></strong> are a way for us to give instructions to the computer more efficiently. Imagine us doing a daily task such as cooking. Our Ingredients(inputs) and meal(output) would differ but our method i.e. cook will be the same. Functions let us tell the computer to perform a set of instructions, without typing it over and over again, we just give it different inputs to get the corresponding output.
</p>
</div>
</body>
<footer>
<p>
<a href="../tblog.html">Back</a>
</p>
</footer>
</html>
| Java |
<h1>Full Sail Landing Page</h1>
<h2>README</h2>
<h3>Objective:</h3>
<p>Recreate a PSD landing page using HTML/CSS/JavaScript for Full Sail University</p>
<h3>Dependencies</h3>
<ul>
<li>Rails</li>
<li>Boostrap</li>
</ul>
<h3>How to run through terminal</h3>
<ul>
<li>Fork project</li>
<li>Clone forked repo/install locally</li>
<li>Bundle install</li>
<li>run "rails s" in the terminal from the root directory of the forked project</li>
<li>Type "localhost:3000" into your browsers search bar to view the project</li>
</ul>
<h3>Designers</h3>
<ul>
<li>Full Sail University</li>
</ul>
<h3>Developers</h3>
<ul>
<li>Christopher Pelnar</li>
</ul>
| Java |
package com.aspose.cloud.sdk.cells.model;
public enum ValidFormatsForDocumentEnum {
csv,
xlsx,
xlsm,
xltx,
xltm,
text,
html,
pdf,
ods,
xls,
spreadsheetml,
xlsb,
xps,
tiff,
jpeg,
png,
emf,
bmp,
gif
}
| Java |
# Haml Changelog
## 5.0.1
Released on May 3, 2017
([diff](https://github.com/haml/haml/compare/v5.0.0...v5.0.1)).
* Fix parsing attributes including string interpolation. [#917](https://github.com/haml/haml/pull/917) [#921](https://github.com/haml/haml/issues/921)
* Stop distributing test files in gem package and allow installing on Windows.
* Use ActionView's Erubi/Erubis handler for erb filter only on ActionView. [#914](https://github.com/haml/haml/pull/914)
## 5.0.0
Released on April 26, 2017
([diff](https://github.com/haml/haml/compare/4.0.7...v5.0.0)).
Breaking Changes
* Haml now requires Ruby 2.0.0 or above.
* Rails 3 is no longer supported, matching the official
[Maintenance Policy for Ruby on Rails](http://weblog.rubyonrails.org/2013/2/24/maintenance-policy-for-ruby-on-rails/).
(Tee Parham)
* The `haml` command's debug option (`-d`) no longer executes the Haml code, but
rather checks the generated Ruby syntax for errors.
* Drop parser/compiler accessor from `Haml::Engine`. Modify `Haml::Engine#initialize` options
or `Haml::Template.options` instead. (Takashi Kokubun)
* Drop dynamic quotes support and always escape `'` for `escape_html`/`escape_attrs` instead.
Also, escaped results are slightly changed and always unified to the same characters. (Takashi Kokubun)
* Don't preserve newlines in attributes. (Takashi Kokubun)
* HTML escape interpolated code in filters.
[#770](https://github.com/haml/haml/pull/770)
(Matt Wildig)
:javascript
#{JSON.generate(foo: "bar")}
Haml 4 output: {"foo":"bar"}
Haml 5 output: {"foo":"bar"}
Added
* Add a tracing option. When enabled, Haml will output a data-trace attribute on each tag showing the path
to the source Haml file from which it was generated. Thanks [Alex Babkin](https://github.com/ababkin).
* Add `haml_tag_if` to render a block, conditionally wrapped in another element (Matt Wildig)
* Support Rails 5.1 Erubi template handler.
* Support Sprockets 3. Thanks [Sam Davies](https://github.com/samphilipd) and [Jeremy Venezia](https://github.com/jvenezia).
* General performance and memory usage improvements. (Akira Matsuda)
* Analyze attribute values by Ripper and render static attributes beforehand. (Takashi Kokubun)
* Optimize attribute rendering about 3x faster. (Takashi Kokubun)
* Add temple gem as dependency and create `Haml::TempleEngine` class.
Some methods in `Haml::Compiler` are migrated to `Haml::TempleEngine`. (Takashi Kokubun)
Fixed
* Fix for attribute merging. When an attribute method (or literal nested hash)
was used in an old style attribute hash and there is also a (non-static) new
style hash there is an error. The fix can result in different behavior in
some circumstances. See the [commit message](https://github.com/haml/haml/tree/e475b015d3171fb4c4f140db304f7970c787d6e3)
for detailed info. (Matt Wildig)
* Make escape_once respect hexadecimal references. (Matt Wildig)
* Don't treat the 'data' attribute specially when merging attribute hashes. (Matt Wildig and Norman Clarke)
* Fix #@foo and #$foo style interpolation that was not working in html_safe mode. (Akira Matsuda)
* Allow `@` as tag's class name. Thanks [Joe Bartlett](https://github.com/redoPop).
* Raise `Haml::InvalidAttributeNameError` when attribute name includes invalid characters. (Takashi Kokubun)
* Don't ignore unexpected exceptions on initializing `ActionView::OutputBuffer`. (Takashi Kokubun)
## 4.0.7
Released on August 10, 2015
([diff](https://github.com/haml/haml/compare/4.0.6...4.0.7)).
* Significantly improve performance of regexp used to fix whitespace handling in textareas (thanks [Stan Hu](https://github.com/stanhu)).
## 4.0.6
Released on Dec 1, 2014 ([diff](https://github.com/haml/haml/compare/4.0.5...4.0.6)).
* Fix warning on Ruby 1.8.7 "regexp has invalid interval" (thanks [Elia Schito](https://github.com/elia)).
## 4.0.5
Released on Jan 7, 2014 ([diff](https://github.com/haml/haml/compare/4.0.4...4.0.5)).
* Fix haml_concat appending unescaped HTML after a call to haml_tag.
* Fix for bug whereby when HAML :ugly option is "true",
ActionView::Helpers::CaptureHelper::capture returns the whole view buffer
when passed a block that returns nothing (thanks [Mircea
Moise](https://github.com/mmircea16)).
## 4.0.4
Released on November 5, 2013 ([diff](https://github.com/haml/haml/compare/4.0.3...4.0.4)).
* Check for Rails::Railtie rather than Rails (thanks [Konstantin Shabanov](https://github.com/etehtsea)).
* Parser fix to allow literal '#' with suppress_eval (Matt Wildig).
* Helpers#escape_once works on frozen strings (as does
ERB::Util.html_escape_once for which it acts as a replacement in
Rails (thanks [Patrik Metzmacher](https://github.com/patrik)).
* Minor test fix (thanks [Mircea Moise](https://github.com/mmircea16)).
## 4.0.3
Released May 21, 2013 ([diff](https://github.com/haml/haml/compare/4.0.2...4.0.3)).
* Compatibility with newer versions of Rails's Erubis handler.
* Fix Erubis handler for compatibility with Tilt 1.4.x, too.
* Small performance optimization for html_escape.
(thanks [Lachlan Sylvester](https://github.com/lsylvester))
* Documentation fixes.
* Documented some helper methods that were left out of the reference.
(thanks [Shane Riley](https://github.com/shaneriley))
## 4.0.2
Released April 5, 2013 ([diff](https://github.com/haml/haml/compare/4.0.1...4.0.2)).
* Explicitly require Erubis to work around bug in older versions of Tilt.
* Fix :erb filter printing duplicate content in Rails views.
(thanks [Jori Hardman](https://github.com/jorihardman))
* Replace range with slice to reduce objects created by `capture_haml`.
(thanks [Tieg Zaharia](https://github.com/tiegz))
* Correct/improve some documentation.
## 4.0.1
Released March 21, 2013 ([diff](https://github.com/haml/haml/compare/4.0.0...4.0.1)).
* Remove Rails 3.2.3+ textarea hack in favor of a more general solution.
* Fix some performance regressions.
* Fix support for Rails 4 `text_area` helper method.
* Fix data attribute flattening with singleton objects.
(thanks [Alisdair McDiarmid](https://github.com/alisdair))
* Fix support for sass-rails 4.0 beta.
(thanks [Ryunosuke SATO](https://github.com/tricknotes))
* Load "haml/template" in Railtie in order to prevent user options set in a
Rails initializer from being overwritten
* Don't depend on Rails in haml/template to allow using Haml with ActionView
but without Rails itself. (thanks [Hunter Haydel](https://github.com/wedgex))
## 4.0.0
* The Haml executable now accepts an `--autoclose` option. You can now
specify a list of tags that should be autoclosed
* The `:ruby` filter no longer redirects $stdout to the Haml document, as this
is not thread safe. Instead it provides a `haml_io` local variable, which is
an IO object that writes to the document.
* HTML5 is now the default output format rather than XHTML. This was already
the default on Rails 3+, so many users will notice no difference.
* The :sass filter now wraps its output in a style tag, as do the new :less and
:scss filters. The :coffee filter wraps its output in a script tag.
* Haml now supports only Rails 3 and above, and Ruby 1.8.7 and above. If you
still need support for Rails 2 and Ruby 1.8.6, please use Haml 3.1.x which
will continue to be maintained for bug fixes.
* The :javascript and :css filters no longer add CDATA tags when the format is
html4 or html5. This can be overridden by setting the `cdata` option to
`true`. CDATA tags are always added when the format is xhtml.
* HTML2Haml has been extracted to a separate gem, creatively named "html2haml".
* The `:erb` filter now uses Rails's safe output buffer to provide XSS safety.
* Haml's internals have been refactored to move the parser, compiler and options
handling into independent classes, rather than including them all in the
Engine module. You can also specify your own custom Haml parser or compiler
class in Haml::Options in order to extend or modify Haml reasonably easily.
* Add an {file:REFERENCE.md#hyphenate_data_attrs-option `:hyphenate_data_attrs`
option} that converts underscores to hyphens in your HTML5 data keys. This is
a language change from 3.1 and is enabled by default.
(thanks to [Andrew Smith](https://github.com/fullsailor))
* All Hash attribute values are now treated as HTML5 data, regardless of key.
Previously only the "data" key was treated this way. Allowing arbitrary keys
means you can now easily use this feature for Aria attributes, among other
uses.
(thanks to [Elvin Efendi](https://github.com/ElvinEfendi))
* Added `remove_whitespace` option to always remove all whitespace around Haml
tags. (thanks to [Tim van der Horst](https://github.com/vdh))
* Haml now flattens deeply nested data attribute hashes. For example:
`.foo{:data => {:a => "b", :c => {:d => "e", :f => "g"}}}`
would render to:
`<div class='foo' data-a='b' data-c-d='e' data-c-f='g'></div>`
(thanks to [Péter Pál Koszta](https://github.com/koszta))
* Filters that rely on third-party template engines are now implemented using
[Tilt](http://github.com/rtomayko/tilt). Several new filters have been added, namely
SCSS (:scss), LessCSS, (:less), and Coffeescript (:coffee/:coffeescript).
Though the list of "official" filters is kept intentionally small, Haml comes
with a helper method that makes adding support for other Tilt-based template
engines trivial.
As of 4.0, Haml will also ship with a "haml-contrib" gem that includes useful
but less-frequently used filters and helpers. This includes several additional
filters such as Nokogiri, Yajl, Markaby, and others.
* Generate object references based on `#to_key` if it exists in preference to
`#id`.
* Performance improvements.
(thanks to [Chris Heald](https://github.com/cheald))
* Helper `list_of` takes an extra argument that is rendered into list item
attributes.
(thanks [Iain Barnett](http://iainbarnett.me.uk/))
* Fix parser to allow lines ending with `some_method?` to be a Ruby multinline.
(thanks to [Brad Ediger](https://github.com/bradediger))
* Always use :xhtml format when the mime_type of the rendered template is
'text/xml'.
(thanks to [Stephen Bannasch](https://github.com/stepheneb))
* html2haml now includes an `--html-attributes` option.
(thanks [Stefan Natchev](https://github.com/snatchev))
* Fix for inner whitespace removal in loops.
(thanks [Richard Michael](https://github.com/richardkmichael))
* Use numeric character references rather than HTML entities when escaping
double quotes and apostrophes in attributes. This works around some bugs in
Internet Explorer earlier than version 9.
(thanks [Doug Mayer](https://github.com/doxavore))
* Fix multiline silent comments: Haml previously did not allow free indentation
inside multline silent comments.
* Fix ordering bug with partial layouts on Rails.
(thanks [Sam Pohlenz](https://github.com/spohlenz))
* Add command-line option to suppress script evaluation.
* It's now possible to use Rails's asset helpers inside the Sass and SCSS
filters. Note that to do so, you must make sure sass-rails is loaded in
production, usually by moving it out of the assets gem group.
* The Haml project now uses [semantic versioning](http://semver.org/).
## 3.2.0
The Haml 3.2 series was released only as far as 3.2.0.rc.4, but then was
renamed to Haml 4.0 when the project adopted semantic versioning.
## 3.1.8
* Fix for line numbers reported from exceptions in nested blocks
(thanks to Grant Hutchins & Sabrina Staedt).
## 3.1.7
* Fix for compatibility with Sass 3.2.x.
(thanks [Michael Westbom](https://github.com/totallymike)).
## 3.1.6
* In indented mode, don't reindent buffers that contain preserved tags, and
provide a better workaround for Rails 3.2.3's textarea helpers.
## 3.1.5
* Respect Rails' `html_safe` flag when escaping attribute values
(thanks to [Gerad Suyderhoud](https://github.com/gerad)).
* Fix for Rails 3.2.3 textarea helpers
(thanks to [James Coleman](https://github.com/jcoleman) and others).
## 3.1.4
* Fix the use of `FormBuilder#block` with a label in Haml.
* Fix indentation after a self-closing tag with dynamic attributes.
## 3.1.3
* Stop partial layouts from being displayed twice.
## 3.1.2
* If the ActionView `#capture` helper is used in a Haml template but without any Haml being run in the block,
return the value of the block rather than the captured buffer.
* Don't throw errors when text is nested within comments.
* Fix html2haml.
* Fix an issue where destructive modification was sometimes performed on Rails SafeBuffers.
* Use character code entities for attribute value replacements instead of named/keyword entities.
## 3.1.1
* Update the vendored Sass to version 3.1.0.
## 3.1.0
* Don't add a `type` attribute to `<script>` and `<style>` tags generated by filters
when `:format` is set to `:html5`.
* Add an {file:HAML_REFERENCE.md#escape_attrs-option `:escape_attrs` option}
that allows attributes to either remain unescaped
(for things like embedding PHP directives in Haml)
or to be always escaped rather than `#escape_once`d.
This can also be used from the command line via `--no-escape-attrs`.
* Allow custom filters to be loaded from the command line.
### Backwards Incompatibilities -- Must Read!
* Get rid of the `--rails` flag for the `haml` executable.
This flag hasn't been necessary since Rails 2.0.
Existing Rails 2.0 installations will continue to work.
* Drop support for Hpricot 0.7. 0.8 has been out for nearly two years.
## 3.0.25
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.25).
* HTML-to-Haml conversion now works within Ruby even if Hpricot is loaded before `haml/html`.
## 3.0.24
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.24).
* `html2haml` now properly generates Haml for silent script expressions
nested within blocks.
* IronRuby compatibility. This is sort of a hack: IronRuby reports its version as 1.9,
but it doesn't support the encoding APIs, so we treat it as 1.8 instead.
## 3.0.23
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.23).
* Fix the error message for unloadable modules when running the executables under Ruby 1.9.2.
* Fix an error when combining old-style and new-style attributes.
## 3.0.22
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.22).
* Allow an empty line after `case` but before `when`.
* Remove `vendor/sass`, which snuck into the gem by mistake
and was causing trouble for Heroku users (thanks to [Jacques Crocker](http://railsjedi.com/)).
* Support the Rails 3.1 template handler API.
## 3.0.21
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.21).
* Fix the permissions errors for good.
## 3.0.20
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.20).
* Fix some permissions errors.
## 3.0.19
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.19).
* Fix the `:encoding` option under Ruby 1.9.2.
* Fix interpolated if statement when HTML escaping is enabled.
* Allow the `--unix-newlines` flag to work on Unix, where it's a no-op.
## 3.0.18
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.18).
* Don't require `rake` in the gemspec, for bundler compatibility under
JRuby. Thanks to [Gordon McCreight](http://www.gmccreight.com/blog).
* Get rid of the annoying RDoc errors on install.
* Disambiguate references to the `Rails` module when `haml-rails` is installed.
* Fix a bug in `haml_tag` that would allow duplicate attributes to be added
and make `data-` attributes not work.
* Compatibility with Rails 3 final.
## 3.0.17
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.17).
* Understand that mingw counts as Windows.
## 3.0.16
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.16).
* Fix an html2haml ERB-parsing bug where ERB blocks were occasionally
left without indentation in Haml.
* Fix parsing of `if` and `case` statements whose values were assigned to variables.
This is still bad style, though.
* Fix `form_for` and `form_tag` when they're passed a block that
returns a string in a helper.
## 3.0.15
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.15).
There were no changes made to Haml between versions 3.0.14 and 3.0.15.
## 3.0.14
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.14).
* Allow CSS-style classes and ids to contain colons.
* Fix an obscure bug with if statements.
### Rails 3 Support
* Don't use the `#returning` method, which Rails 3 no longer provides.
## 3.0.13
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.13).
## Rails 3 Support
Support for Rails 3 versions prior to beta 4 has been removed.
Upgrade to Rails 3.0.0.beta4 if you haven't already.
### Minor Improvements
* Properly process frozen strings with encoding declarations.
## 3.0.12
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.12).
## Rails 3 Support
Apparently the last version broke in new and exciting ways under Rails 3,
due to the inconsistent load order caused by certain combinations of gems.
3.0.12 hacks around that inconsistency, and *should* be fully Rails 3-compatible.
### Deprecated: Rails 3 Beta 3
Haml's support for Rails 3.0.0.beta.3 has been deprecated.
Haml 3.0.13 will only support 3.0.0.beta.4.
## 3.0.11
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.11).
## 3.0.10
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.10).
### Appengine-JRuby Support
The way we determine the location of the Haml installation
no longer breaks the version of JRuby
used by [`appengine-jruby`](http://code.google.com/p/appengine-jruby/).
### Bug Fixes
* Single-line comments are now handled properly by `html2haml`.
## 3.0.9
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.9).
There were no changes made to Haml between versions 3.0.8 and 3.0.9.
A bug in Gemcutter caused the gem to be uploaded improperly.
## 3.0.8
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.8).
* Fix a bug with Rails versions prior to Rails 3.
## 3.0.7
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.7).
### Encoding Support
Haml 3.0.7 adds support for Ruby-style `-# coding:` comments
for declaring the encoding of a template.
For details see {file:HAML_REFERENCE.md#encodings the reference}.
This also slightly changes the behavior of Haml when the
{file:HAML_REFERENCE.md#encoding-option `:encoding` option} is not set.
Rather than defaulting to `"utf-8"`,
it defaults to the encoding of the source document,
and only falls back to `"utf-8"` if this encoding is `"us-ascii"`.
The `haml` executable also now takes an `-E` option for specifying encoding,
which works the same way as Ruby's `-E` option.
### Other Changes
* Default to the {file:HAML_REFERENCE.md#format-option `:html5` format}
when running under Rails 3,
since it defaults to HTML5 as well.
### Bug Fixes
* When generating Haml for something like `<span>foo</span>,`,
use `= succeed` rather than `- succeed` (which doesn't work).
## 3.0.6
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.6).
### Rails 2.3.7 Support
This release fully supports Rails 2.3.7.
### Rails 2.3.6 Support Removed
Rails 2.3.6 was released with various bugs related to XSS-protection
and interfacing with Haml.
Rails 2.3.7 was released shortly after with fixes for these bugs.
Thus, Haml no longer supports Rails 2.3.6,
and anyone using it should upgrade to 2.3.7.
Attempting to use Haml with Rails 2.3.6 will cause an error.
## 3.0.5
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.5).
### Rails 2.3.6 Support
This release hacks around various bugs in Rails 2.3.6,
bringing Haml up to full compatibility.
### Rails 3 Support
Make sure the `#capture` helper in Rails 3
doesn't print its value directly to the template.
## 3.0.4
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.4).
There were no changes made to Haml between versions 3.0.3 and 3.0.4.
## 3.0.3
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.3).
### Rails 3 Support
In order to make some Rails loading errors easier to debug,
Sass will now raise an error if `Rails.root` is `nil` when Sass is loading.
Previously, this would just cause the paths to be mis-set.
## 3.0.2
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.2).
There were no changes made to Haml between versions 3.0.1 and 3.0.2.
## 3.0.1
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.1).
### Installation in Rails
`haml --rails` is no longer necessary for installing Haml in Rails.
Now all you need to do is add `gem "haml"` to the Gemfile for Rails 3,
or add `config.gem "haml"` to `config/environment.rb` for previous versions.
`haml --rails` will still work,
but it has been deprecated and will print an error message.
It will not work in the next version of Haml.
### Rails Test Speed
The {file:HAML_REFERENCE.md#ugly-option `:ugly` option} is now on by default
in the testing environment in Rails to help tests run faster.
## 3.0.0
[Tagged on GitHub](http://github.com/nex3/haml/commit/3.0.0).
### Backwards Incompatibilities: Must Read!
* The `puts` helper has been removed.
Use {Haml::Helpers#haml\_concat} instead.
### More Useful Multiline
Ruby code can now be wrapped across multiple lines
as long as each line but the last ends in a comma.
For example:
= link_to_remote "Add to cart",
:url => { :action => "add", :id => product.id },
:update => { :success => "cart", :failure => "error" }
### `haml_tag` and `haml_concat` Improvements
#### `haml_tag` with CSS Selectors
The {Haml::Helpers#haml_tag haml\_tag} helper can now take a string
using the same class/id shorthand as in standard Haml code.
Manually-specified class and id attributes are merged,
again as in standard Haml code.
For example:
haml_tag('#foo') #=> <div id='foo' />
haml_tag('.bar') #=> <div class='bar' />
haml_tag('span#foo.bar') #=> <span class='bar' id='foo' />
haml_tag('span#foo.bar', :class => 'abc') #=> <span class='abc bar' id='foo' />
haml_tag('span#foo.bar', :id => 'abc') #=> <span class='bar' id='abc_foo' />
Cheers, [S. Burkhard](http://github.com/hasclass/).
#### `haml_tag` with Multiple Lines of Content
The {Haml::Helpers#haml_tag haml\_tag} helper also does a better job
of formatting tags with multiple lines of content.
If a tag has multiple levels of content,
that content is indented beneath the tag.
For example:
haml_tag(:p, "foo\nbar") #=>
# <p>
# foo
# bar
# </p>
#### `haml_tag` with Multiple Lines of Content
Similarly, the {Haml::Helpers#haml_concat haml\_concat} helper
will properly indent multiple lines of content.
For example:
haml_tag(:p) {haml_concat "foo\nbar"} #=>
# <p>
# foo
# bar
# </p>
#### `haml_tag` and `haml_concat` with `:ugly`
When the {file:HAML_REFERENCE.md#ugly-option `:ugly` option} is enabled,
{Haml::Helpers#haml_tag haml\_tag} and {Haml::Helpers#haml_concat haml\_concat}
won't do any indentation of their arguments.
### Basic Tag Improvements
* It's now possible to customize the name used for {file:HAML_REFERENCE.md#object_reference_ object reference}
for a given object by implementing the `haml_object_ref` method on that object.
This method should return a string that will be used in place of the class name of the object
in the generated class and id.
Thanks to [Tim Carey-Smith](http://twitter.com/halorgium).
* All attribute values may be non-String types.
Their `#to_s` method will be called to convert them to strings.
Previously, this only worked for attributes other than `class`.
### `:class` and `:id` Attributes Accept Ruby Arrays
In an attribute hash, the `:class` attribute now accepts an Array
whose elements will be converted to strings and joined with <nobr>`" "`</nobr>.
Likewise, the `:id` attribute now accepts an Array
whose elements will be converted to strings and joined with `"_"`.
The array will first be flattened and any elements that do not test as true
will be stripped out. For example:
.column{:class => [@item.type, @item == @sortcol && [:sort, @sortdir]] }
could render as any of:
class="column numeric sort ascending"
class="column numeric"
class="column sort descending"
class="column"
depending on whether `@item.type` is `"numeric"` or `nil`,
whether `@item == @sortcol`,
and whether `@sortdir` is `"ascending"` or `"descending"`.
A single value can still be specified.
If that value evaluates to false it is ignored;
otherwise it gets converted to a string.
For example:
.item{:class => @item.is_empty? && "empty"}
could render as either of:
class="item"
class="item empty"
Thanks to [Ronen Barzel](http://www.ronenbarzel.org/).
### HTML5 Custom Data Attributes
Creating an attribute named `:data` with a Hash value
will generate [HTML5 custom data attributes](http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#embedding-custom-non-visible-data).
For example:
%div{:data => {:author_id => 123, :post_id => 234}}
Will compile to:
<div data-author_id='123' data-post_id='234'></div>
Thanks to [John Reilly](http://twitter.com/johnreilly).
### More Powerful `:autoclose` Option
The {file:HAML_REFERENCE.md#attributes_option `:attributes`} option
can now take regular expressions that specify which tags to make self-closing.
### `--double-quote-attributes` Option
The Haml executable now has a `--double-quote-attributes` option (short form: `-q`)
that causes attributes to use a double-quote mark rather than single-quote.
Thanks to [Charles Roper](http://charlesroper.com/).
### `:css` Filter
Haml now supports a {file:HAML_REFERENCE.md#css-filter `:css` filter}
that surrounds the filtered text with `<style>` and CDATA tags.
### `haml-spec` Integration
We've added the cross-implementation tests from the [haml-spec](http://github.com/norman/haml-spec) project
to the standard Haml test suite, to be sure we remain compatible with the base functionality
of the many and varied [Haml implementations](http://en.wikipedia.org/wiki/Haml#Implementations).
### Ruby 1.9 Support
* Haml and `html2haml` now produce more descriptive errors
when given a template with invalid byte sequences for that template's encoding,
including the line number and the offending character.
* Haml and `html2haml` now accept Unicode documents with a
[byte-order-mark](http://en.wikipedia.org/wiki/Byte_order_mark).
### Rails Support
* When `form_for` is used with `=`, or `form_tag` is used with `=` and a block,
they will now raise errors explaining that they should be used with `-`.
This is similar to how {Haml::Helpers#haml\_concat} behaves,
and will hopefully clear up some difficult bugs for some users.
### Rip Support
Haml is now compatible with the [Rip](http://hellorip.com/) package management system.
Thanks to [Josh Peek](http://joshpeek.com/).
### `html2haml` Improvements
* Ruby blocks within ERB are now supported.
The Haml code is properly indented and the `end`s are removed.
This includes methods with blocks and all language constructs
such as `if`, `begin`, and `case`.
For example:
<% content_for :footer do %>
<p>Hi there!</p>
<% end %>
is now transformed into:
- content_for :footer do
%p Hi there!
Thanks to [Jack Chen](http://chendo.net) and [Dr. Nic Williams](http://drnicwilliams)
for inspiring this and creating the first draft of the code.
* Inline HTML text nodes are now transformed into inline Haml text.
For example, `<p>foo</p>` now becomes `%p foo`, whereas before it became:
%p
foo
The same is true for inline comments,
and inline ERB when running in ERB mode:
`<p><%= foo %></p>` will now become `%p= foo`.
* ERB included within text is now transformed into Ruby interpolation.
For example:
<p>
Foo <%= bar %> baz!
Flip <%= bang %>.
</p>
is now transformed into:
%p
Foo #{bar} baz!
Flip #{bang}.
* `<script>` tags are now transformed into `:javascript` filters,
and `<style>` tags into `:css` filters.
and indentation is preserved.
For example:
<script type="text/javascript">
function foo() {
return 12;
}
</script>
is now transformed into:
:javascript
function foo() {
return 12;
}
* `<pre>` and `<textarea>` tags are now transformed into the `:preserve` filter.
For example:
<pre>Foo
bar
baz</pre>
is now transformed into:
%pre
:preserve
Foo
bar
baz
* Self-closing tags (such as `<br />`) are now transformed into
self-closing Haml tags (like `%br/`).
* IE conditional comments are now properly parsed.
* Attributes are now output in a more-standard format,
without spaces within the curly braces
(e.g. `%p{:foo => "bar"}` as opposed to `%p{ :foo => "bar" }`).
* IDs and classes containing `#` and `.` are now output as string attributes
(e.g. `%p{:class => "foo.bar"}`).
* Attributes are now sorted, to maintain a deterministic order.
* `>` or {Haml::Helpers#succeed #succeed} are inserted where necessary
when inline formatting is used.
* Multi-line ERB statements are now properly indented,
and those without any content are removed.
### Minor Improvements
* {Haml::Helpers#capture_haml capture\_haml} is now faster when using `:ugly`.
Thanks to [Alf Mikula](http://alfmikula.blogspot.com/).
* Add an `RDFa` doctype shortcut.
## 2.2.24
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.24).
* Don't prevent ActiveModel form elements from having error formatting applied.
* Make sure `form_for` blocks are properly indented under Rails 3.0.0.beta.3.
* Don't activate a bug in the `dynamic_form` plugin under Rails 3.0.0.beta.3
that would cause its methods not to be loaded.
## 2.2.23
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.23).
* Don't crash when `rake gems` is run in Rails with Haml installed.
Thanks to [Florian Frank](http://github.com/flori).
* Don't remove `\n` in filters with interpolation.
* Silence those annoying `"regexp match /.../n against to UTF-8 string"` warnings.
## 2.2.22
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.22).
* Add a railtie so Haml and Sass will be automatically loaded in Rails 3.
Thanks to [Daniel Neighman](http://pancakestacks.wordpress.com/).
* Add a deprecation message for using `-` with methods like `form_for`
that return strings in Rails 3.
This is [the same deprecation that exists in Rails 3](http://github.com/rails/rails/commit/9de83050d3a4b260d4aeb5d09ec4eb64f913ba64).
* Make sure line numbers are reported correctly when filters are being used.
* Make loading the gemspec not crash on read-only filesystems like Heroku's.
* Don't crash when methods like `form_for` return `nil` in, for example, Rails 3 beta.
* Compatibility with Rails 3 beta's RJS facilities.
## 2.2.21
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.21).
* Fix a few bugs in the git-revision-reporting in Haml::Version.
In particular, it will still work if `git gc` has been called recently,
or if various files are missing.
* Always use `__FILE__` when reading files within the Haml repo in the `Rakefile`.
According to [this bug report](http://github.com/carlhuda/bundler/issues/issue/44),
this should make Haml work better with Bundler.
* Make the error message for `- end` a little more intuitive based on user feedback.
* Compatibility with methods like `form_for`
that return strings rather than concatenate to the template in Rails 3.
* Add a {Haml::Helpers#with_tabs with_tabs} helper,
which sets the indentation level for the duration of a block.
## 2.2.20
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.20).
* The `form_tag` Rails helper is now properly marked as HTML-safe
when using Rails' XSS protection with Rails 2.3.5.
* Calls to `defined?` shouldn't interfere with Rails' autoloading
in very old versions (1.2.x).
* Fix a bug where calls to ActionView's `render` method
with blocks and layouts wouldn't work under the Rails 3.0 beta.
* Fix a bug where the closing tags of nested calls to \{Haml::Helpers#haml\_concat}
were improperly escaped under the Rails 3.0 beta.
## 2.2.19
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.19).
* Fix a bug with the integration with Rails' XSS support.
In particular, correctly override `safe_concat`.
## 2.2.18
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.18).
* Support [the new XSS-protection API](http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/)
used in Rails 3.
* Use `Rails.env` rather than `RAILS_ENV` when running under Rails 3.0.
Thanks to [Duncan Grazier](http://duncangrazier.com/).
* Add a `--unix-newlines` flag to all executables
for outputting Unix-style newlines on Windows.
* Fix a couple bugs with the `:erb` filter:
make sure error reporting uses the correct line numbers,
and allow multi-line expressions.
* Fix a parsing bug for HTML-style attributes including `#`.
## 2.2.17
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.17).
* Fix compilation of HTML5 doctypes when using `html2haml`.
* `nil` values for Sass options are now ignored,
rather than raising errors.
## 2.2.16
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.16).
* Abstract out references to `ActionView::TemplateError`,
`ActionView::TemplateHandler`, etc.
These have all been renamed to `ActionView::Template::*`
in Rails 3.0.
## 2.2.15
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.15).
* Allow `if` statements with no content followed by `else` clauses.
For example:
- if foo
- else
bar
## 2.2.14
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.14).
* Don't print warnings when escaping attributes containing non-ASCII characters
in Ruby 1.9.
* Don't crash when parsing an XHTML Strict doctype in `html2haml`.
* Support the HTML5 doctype in an XHTML document
by using `!!! 5` as the doctype declaration.
## 2.2.13
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.13).
* Allow users to specify {file:HAML_REFERENCE.md#encoding_option `:encoding => "ascii-8bit"`}
even for templates that include non-ASCII byte sequences.
This makes Haml templates not crash when given non-ASCII input
that's marked as having an ASCII encoding.
* Fixed an incompatibility with Hpricot 0.8.2, which is used for `html2haml`.
## 2.2.12
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.12).
There were no changes made to Haml between versions 2.2.11 and 2.2.12.
## 2.2.11
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.11).
* Fixed a bug with XSS protection where HTML escaping would raise an error
if passed a non-string value.
Note that this doesn't affect any HTML escaping when XSS protection is disabled.
* Fixed a bug in outer-whitespace nuking where whitespace-only Ruby strings
blocked whitespace nuking beyond them.
* Use `ensure` to protect the resetting of the Haml output buffer
against exceptions that are raised within the compiled Haml code.
* Fix an error line-numbering bug that appeared if an error was thrown
within loud script (`=`).
This is not the best solution, as it disables a few optimizations,
but it shouldn't have too much effect and the optimizations
will hopefully be re-enabled in version 2.4.
* Don't crash if the plugin skeleton is installed and `rake gems:install` is run.
* Don't use `RAILS_ROOT` directly.
This no longer exists in Rails 3.0.
Instead abstract this out as `Haml::Util.rails_root`.
This changes makes Haml fully compatible with edge Rails as of this writing.
## 2.2.10
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.10).
* Fixed a bug where elements with dynamic attributes and no content
would have too much whitespace between the opening and closing tag.
* Changed `rails/init.rb` away from loading `init.rb` and instead
have it basically copy the content.
This allows us to transfer the proper binding to `Haml.init_rails`.
* Make sure Haml only tries to enable XSS protection integration
once all other plugins are loaded.
This allows it to work properly when Haml is a gem
and the `rails_xss` plugin is being used.
* Mark the return value of Haml templates as HTML safe.
This makes Haml partials work with Rails' XSS protection.
## 2.2.9
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.9).
* Fixed a bug where Haml's text was concatenated to the wrong buffer
under certain circumstances.
This was mostly an issue under Rails when using methods like `capture`.
* Fixed a bug where template text was escaped when there was interpolation in a line
and the `:escape_html` option was enabled. For example:
Foo < Bar #{"<"} Baz
with `:escape_html` used to render as
Foo &lt; Bar < Baz
but now renders as
Foo < Bar < Baz
### Rails XSS Protection
Haml 2.2.9 supports the XSS protection in Rails versions 2.3.5+.
There are several components to this:
* If XSS protection is enabled, Haml's {file:HAML_REFERENCE.md#escape_html-option `:escape_html`}
option is set to `true` by default.
* Strings declared as HTML safe won't be escaped by Haml,
including the {file:Haml/Helpers.html#html_escape-instance_method `#html_escape`} helper
and `&=` if `:escape_html` has been disabled.
* Haml helpers that generate HTML are marked as HTML safe,
and will escape their input if it's not HTML safe.
## 2.2.8
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.8).
* Fixed a potential XSS issue with HTML escaping and wacky Unicode nonsense.
This is the same as [the issue fixed in Rails](http://groups.google.com/group/rubyonrails-security/browse_thread/thread/48ab3f4a2c16190f) a bit ago.
## 2.2.7
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.7).
* Fixed an `html2haml` issue where ERB attribute values
weren't HTML-unescaped before being transformed into Haml.
* Fixed an `html2haml` issue where `#{}` wasn't escaped
before being transformed into Haml.
* Add `<code>` to the list of tags that's
{file:HAML_REFERENCE.md#preserve-option automatically whitespace-preserved}.
* Fixed a bug with `end` being followed by code in silent scripts -
it no longer throws an error when it's nested beneath tags.
* Fixed a bug with inner whitespace-nuking and conditionals.
The `else` et al. clauses of conditionals are now properly
whitespace-nuked.
## 2.2.6
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.6).
* Made the error message when unable to load a dependency for html2haml
respect the `--trace` option.
* Don't crash when the `__FILE__` constant of a Ruby file is a relative path,
as apparently happens sometimes in TextMate
(thanks to [Karl Varga](http://github.com/kjvarga)).
* Add "Sass" to the `--version` string for the executables.
* Raise an exception when commas are omitted in static attributes
(e.g. `%p{:foo => "bar" :baz => "bang"}`).
## 2.2.5
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.5).
* Got rid of trailing whitespace produced when opening a conditional comment
(thanks to [Norman Clarke](http://blog.njclarke.com/)).
* Fixed CSS id concatenation when a numeric id is given as an attribute.
(thanks to [Norman Clarke](http://blog.njclarke.com/)).
* Fixed a couple bugs with using "-end" in strings.
## 2.2.4
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.4).
* Allow `end` to be used for silent script when it's followed by code.
For example:
- form_for do
...
- end if @show_form
This isn't very good style, but we're supporting it for consistency's sake.
* Don't add `require 'rubygems'` to the top of init.rb when installed
via `haml --rails`. This isn't necessary, and actually gets
clobbered as soon as haml/template is loaded.
## 2.2.3
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.3).
Haml 2.2.3 adds support for the JRuby bundling tools
for Google AppEngine, thanks to [Jan Ulbrich](http://github.com/ulbrich).
## 2.2.2
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.2).
Haml 2.2.2 is a minor bugfix release, with several notable changes.
First, {file:Haml/Helpers.html#haml_concat-instance_method `haml_concat`}
will now raise an error when used with `=`.
This has always been incorrect behavior,
and in fact has never actually worked.
The only difference is that now it will fail loudly.
Second, Ruby 1.9 is now more fully supported,
especially with the {file:HAML_REFERENCE.md#htmlstyle_attributes_ new attribute syntax}.
Third, filters are no longer escaped when the {file:HAML_REFERENCE.md#escape_html-option `:escape_html` option}
is enabled and `#{}` interpolation is used.
## 2.2.1
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.1).
Haml 2.2.1 is a minor bug-fix release.
## 2.2.0
[Tagged on GitHub](http://github.com/nex3/haml/commit/2.2.0).
Haml 2.2 adds several new features to the language,
fixes several bugs, and dramatically improves performance
(particularly when running with {file:HAML_REFERENCE.md#ugly-option `:ugly`} enabled).
### Syntax Changes
#### HTML-Style Attribute Syntax
Haml 2.2 introduces a new syntax for attributes
based on the HTML syntax.
For example:
%a(href="http://haml.info" title="Haml's so cool!")
%img(src="/images/haml.png" alt="Haml")
There are two main reasons for this.
First, the hash-style syntax is very Ruby-specific.
There are now [Haml implementations](http://en.wikipedia.org/wiki/Haml#Implementations)
in many languages, each of which has its own syntax for hashes
(or dicts or associative arrays or whatever they're called).
The HTML syntax will be adopted by all of them,
so you can feel comfortable using Haml in whichever language you need.
Second, the hash-style syntax is quite verbose.
`%img{:src => "/images/haml.png", :alt => "Haml"}`
is eight characters longer than `%img(src="/images/haml.png" alt="Haml")`.
Haml's supposed to be about writing templates quickly and easily;
HTML-style attributes should help out a lot with that.
Ruby variables can be used as attribute values by omitting quotes.
Local variables or instance variables can be used.
For example:
%a(title=@title href=href) Stuff
This is the same as:
%a{:title => @title, :href => href} Stuff
Because there are no commas separating attributes,
more complicated expressions aren't allowed.
You can use `#{}` interpolation to insert complicated expressions
in a HTML-style attribute, though:
%span(class="widget_#{@widget.number}")
#### Multiline Attributes
In general, Haml tries to keep individual elements on a single line.
There is a [multiline syntax](#multiline) for overflowing onto further lines,
but it's intentionally awkward to use to encourage shorter lines.
However, there is one case where overflow is reasonable: attributes.
Often a tag will simply have a lot of attributes, and in this case
it makes sense to allow overflow.
You can now stretch an attribute hash across multiple lines:
%script{:type => "text/javascript",
:src => "javascripts/script_#{2 + 7}"}
This also works for HTML-style attributes:
%script(type="text/javascript"
src="javascripts/script_#{2 + 7}")
Note that for hash-style attributes, the newlines must come after commas.
#### Universal interpolation
In Haml 2.0, you could use `==` to interpolate Ruby code
within a line of text using `#{}`.
In Haml 2.2, the `==` is unnecessary;
`#{}` can be used in any text.
For example:
%p This is a really cool #{h what_is_this}!
But is it a #{h what_isnt_this}?
In addition, to {file:HAML_REFERENCE.md#escaping_html escape} or {file:HAML_REFERENCE.md#unescaping_html unescape}
the interpolated code, you can just add `&` or `!`, respectively,
to the beginning of the line:
%p& This is a really cool #{what_is_this}!
& But is it a #{what_isnt_this}?
#### Flexible indentation
Haml has traditionally required its users to use two spaces of indentation.
This is the universal Ruby style, and still highly recommended.
However, Haml now allows any number of spaces or even tabs for indentation,
provided:
* Tabs and spaces are not mixed
* The indentation is consistent within a given document
### New Options
#### `:ugly`
The `:ugly` option is not technically new;
it was introduced in Haml 2.0 to make rendering deeply nested templates less painful.
However, it's been greatly empowered in Haml 2.2.
It now does all sorts of performance optimizations
that couldn't be done before,
and its use increases Haml's performance dramatically.
It's enabled by default in production in Rails,
and it's highly recommended for production environments
in other frameworks.
#### `:encoding` {#encoding-option}
This option specifies the encoding of the Haml template
when running under Ruby 1.9. It defaults to `Encoding.default_internal` or `"utf-8"`.
This is useful for making sure that you don't get weird
encoding errors when dealing with non-ASCII input data.
### Deprecations
#### `Haml::Helpers#puts`
This helper is being deprecated for the obvious reason
that it conflicts with the `Kernel#puts` method.
I'm ashamed I ever chose this name.
Use `haml_concat` instead and spare me the embarrassment.
#### `= haml_tag`
A lot of people accidentally use "`= haml_tag`".
This has always been wrong; `haml_tag` outputs directly to the template,
and so should be used as "`- haml_tag`".
Now it raises an error when you use `=`.
### Compatibility
#### Rails
Haml 2.2 is fully compatible with Rails,
from 2.0.6 to the latest revision of edge, 783db25.
#### Ruby 1.9
Haml 2.2 is also fully compatible with Ruby 1.9.
It supports Ruby 1.9-style attribute hashes,
and handles encoding-related issues
(see [the `:encoding` option](#encoding-option)).
### Filters
#### `:markdown`
There are numerous improvements to the Markdown filter.
No longer will Haml attempt to use RedCloth's inferior Markdown implementation.
Instead, it will look for all major Markdown implementations:
[RDiscount](https://github.com/rtomayko/rdiscount),
[RPeg-Markdown](https://github.com/rtomayko/rpeg-markdown),
[Maruku](http://maruku.rubyforge.org),
and [BlueCloth](http://www.deveiate.org/projects/BlueCloth).
#### `:cdata`
There is now a `:cdata` filter for wrapping text in CDATA tags.
#### `:sass`
The `:sass` filter now uses options set in `Sass::Plugin`,
if they're available.
### Executables
#### `haml`
The `haml` executable now takes `-r` and `-I` flags
that act just like the same flags for the `ruby` executable.
This allows users to load helper files when using Haml
from the command line.
It also takes a `--debug` flag that causes it to spit out
the Ruby code that Haml generates from the template.
This is more for my benefit than anything,
but you may find it interesting.
#### `html2haml`
The `html2haml` executable has undergone significant improvements.
Many of these are bugfixes, but there are also a few features.
For one, it now understands CDATA tags and autodetects ERB files.
In addition, a line containing just "`- end`" is now a Haml error;
since it's not possible for `html2haml` to properly parse all Ruby blocks,
this acts as a signal for the author that there are blocks
to be dealt with.
### Miscellaneous
#### XHTML Mobile DTD
Haml 2.2 supports a DTD for XHTML Mobile: `!!! Mobile`.
#### YARD
All the documentation for Haml 2.2, including this changelog,
has been moved to [YARD](http://yard.soen.ca).
YARD is an excellent documentation system,
and allows us to write our documentation in [Maruku](http://maruku.rubyforge.org),
which is also excellent.
>>>>>>> External Changes
| Java |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Package'
db.create_table(u'api_package', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(unique=True, max_length=500, db_index=True)),
('url', self.gf('django.db.models.fields.CharField')(unique=True, max_length=500)),
('created_at', self.gf('django.db.models.fields.DateField')(auto_now_add=True, blank=True)),
))
db.send_create_signal(u'api', ['Package'])
# Adding unique constraint on 'Package', fields ['name', 'url']
db.create_unique(u'api_package', ['name', 'url'])
def backwards(self, orm):
# Removing unique constraint on 'Package', fields ['name', 'url']
db.delete_unique(u'api_package', ['name', 'url'])
# Deleting model 'Package'
db.delete_table(u'api_package')
models = {
u'api.package': {
'Meta': {'unique_together': "(('name', 'url'),)", 'object_name': 'Package'},
'created_at': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '500', 'db_index': 'True'}),
'url': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '500'})
}
}
complete_apps = ['api'] | Java |
from __future__ import absolute_import
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from plotly.tests.utils import compare_dict
from plotly.tests.test_optional.optional_utils import run_fig
from plotly.tests.test_optional.test_matplotlylib.data.annotations import *
def test_annotations():
fig, ax = plt.subplots()
ax.plot([1, 2, 3], 'b-')
ax.plot([3, 2, 1], 'b-')
ax.text(0.001, 0.999,
'top-left', transform=ax.transAxes, va='top', ha='left')
ax.text(0.001, 0.001,
'bottom-left', transform=ax.transAxes, va='baseline', ha='left')
ax.text(0.999, 0.999,
'top-right', transform=ax.transAxes, va='top', ha='right')
ax.text(0.999, 0.001,
'bottom-right', transform=ax.transAxes, va='baseline', ha='right')
renderer = run_fig(fig)
for data_no, data_dict in enumerate(renderer.plotly_fig['data']):
equivalent, msg = compare_dict(data_dict,
ANNOTATIONS['data'][data_no])
assert equivalent, msg
for no, note in enumerate(renderer.plotly_fig['layout']['annotations']):
equivalent, msg = compare_dict(note,
ANNOTATIONS['layout']['annotations'][no])
assert equivalent, msg
| Java |
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
// excluding node_modules from being transpiled by babel-loader.
environment.loaders.delete("nodeModules");
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
jquery: "jquery",
Popper: ['popper.js', 'default']
}))
// const aliasConfig = {
// 'jquery': 'jquery-ui-dist/external/jquery/jquery.js',
// 'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
// };
// environment.config.set('resolve.alias', aliasConfig);
// resolve-url-loader must be used before sass-loader
// https://github.com/rails/webpacker/blob/master/docs/css.md#resolve-url-loader
environment.loaders.get("sass").use.splice(-1, 0, {
loader: "resolve-url-loader"
});
module.exports = environment
| Java |
from distutils.core import setup
setup(
# Application name:
name="streaker",
# Version number (initial):
version="0.0.1",
# Application author details:
author="Aldi Alimucaj",
author_email="aldi.alimucaj@gmail.com",
# Packages
packages=["streaker"],
scripts=['bin/streaker'],
# Include additional files into the package
include_package_data=True,
# Details
url="http://pypi.python.org/pypi/Streaker_v001/",
#
license="MIT",
description="GitHub streak manipulator",
# long_description=open("README.txt").read(),
# Dependent packages (distributions)
install_requires=[
# "",
],
)
| Java |
const ResponseMessage = require('../../messages').Response;
const through2 = require('through2');
const xtend = require('xtend');
var defaults = {
ignore_invalid: false
};
function encoder(Message, options) {
options = xtend(defaults, options || {});
return through2.obj(function(message, enc, callback) {
if (Message.verify(message)) {
if (options.ignore_invalid) {
return this.queue(message);
}
throw new Error('unhandled request');
}
return callback(null, Message.encodeDelimited(message).finish());
});
}
module.exports = function () {
return encoder(ResponseMessage);
};
| Java |
<?php
namespace CoreBundle\Model\map;
use \RelationMap;
use \TableMap;
/**
* This class defines the structure of the 'list_holidays' table.
*
*
*
* This map class is used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
* @package propel.generator.src.CoreBundle.Model.map
*/
class ListHolidaysTableMap extends TableMap
{
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'src.CoreBundle.Model.map.ListHolidaysTableMap';
/**
* Initialize the table attributes, columns and validators
* Relations are not initialized by this method since they are lazy loaded
*
* @return void
* @throws PropelException
*/
public function initialize()
{
// attributes
$this->setName('list_holidays');
$this->setPhpName('ListHolidays');
$this->setClassname('CoreBundle\\Model\\ListHolidays');
$this->setPackage('src.CoreBundle.Model');
$this->setUseIdGenerator(true);
// columns
$this->addPrimaryKey('id', 'Id', 'INTEGER', true, null, null);
$this->addColumn('date', 'Date', 'TIMESTAMP', true, null, null);
$this->addColumn('name', 'Name', 'VARCHAR', true, 45, null);
$this->addColumn('type', 'Type', 'VARCHAR', true, 45, null);
// validators
} // initialize()
/**
* Build the RelationMap objects for this table relationships
*/
public function buildRelations()
{
} // buildRelations()
} // ListHolidaysTableMap
| Java |
// Modified from https://github.com/dburrows/draft-js-basic-html-editor/blob/master/src/utils/draftRawToHtml.js
'use strict';
import { List } from 'immutable';
import * as InlineStylesProcessor from './inline-styles-processor';
import ApiDataInstance from './api-data-instance';
import AtomicBlockProcessor from './atomic-block-processor';
import ENTITY from './entities';
import merge from 'lodash/merge';
const _ = {
merge,
}
const annotationIndicatorPrefix = '__ANNOTATION__=';
let defaultBlockTagMap = {
'atomic': `<div>%content%</div>`,
'blockquote': `<blockquote>%content%</blockquote>`,
'code-block': `<code>%content%</code>`,
'default': `<p>%content%</p>`,
'header-one': `<h1>%content%</h1>`,
'header-two': `<h2>%content%</h2>`,
'header-three': `<h3>%content%</h3>`,
'header-four': `<h4>%content%</h4>`,
'header-five': `<h5>%content%</h5>`,
'header-six': `<h6>%content%</h6>`,
'ordered-list-item': `<li>%content%</li>`,
'paragraph': `<p>%content%</p>`,
'unordered-list-item': `<li>%content%</li>`,
'unstyled': `<p>%content%</p>`,
};
let inlineTagMap = {
BOLD: ['<strong>', '</strong>'],
CODE: ['<code>', '</code>'],
default: ['<span>', '</span>'],
ITALIC: ['<em>', '</em>'],
UNDERLINE: ['<u>', '</u>'],
};
let defaultEntityTagMap = {
[ENTITY.ANNOTATION.type]: ['<abbr title="<%= data.pureAnnotationText %>"><%= data.text %>', '</abbr>'],
[ENTITY.AUDIO.type]: ['<div class="audio-container"><div class="audio-title"><%= data.title %></div><div class="audio-desc"><%= data.description %></div><audio src="<%= data.url %>" />', '</div>'],
[ENTITY.BLOCKQUOTE.type]: ['<blockquote><div><%= data.quote %></div><div><%= data.quoteBy %></div>', '<blockquote>'],
[ENTITY.EMBEDDEDCODE.type]: ['<div><%= data.embeddedCode%>', '</div>'],
[ENTITY.INFOBOX.type]: ['<div class="info-box-container"><div class="info-box-title"><%= data.title %></div><div class="info-box-body"><%= data.body %></div>', '</div>'],
[ENTITY.LINK.type]: ['<a target="_blank" href="<%= data.url %>">', '</a>'],
[ENTITY.IMAGE.type]: ['<img alt="<%= data.description %>" src="<%= data.url %>">', '</img>'],
[ENTITY.IMAGELINK.type]: ['<img alt="<%= data.description %>" src="<%= data.url %>">', '</img>'],
[ENTITY.SLIDESHOW.type]: ['<!-- slideshow component start --> <ol class="slideshow-container"> <% if(!data) { data = []; } data.forEach(function(image) { %><li class="slideshow-slide"><img src="<%- image.url %>" /></li><% }); %>', '</ol><!-- slideshow component end -->'],
[ENTITY.IMAGEDIFF.type]: ['<!-- imageDiff component start --> <ol class="image-diff-container"> <% if(!data) { data = []; } data.forEach(function(image, index) { if (index > 1) { return; } %><li class="image-diff-item"><img src="<%- image.url %>" /></li><% }); %>', '</ol><!-- imageDiff component end-->'],
[ENTITY.YOUTUBE.type]: ['<iframe width="560" height="315" src="https://www.youtube.com/embed/<%= data.youtubeId %>" frameborder="0" allowfullscreen>', '</iframe>'],
};
let nestedTagMap = {
'ordered-list-item': ['<ol>', '</ol>'],
'unordered-list-item': ['<ul>', '</ul>'],
};
function _convertInlineStyle (block, entityMap, blockTagMap, entityTagMap) {
return blockTagMap[block.type] ? blockTagMap[block.type].replace(
'%content%',
InlineStylesProcessor.convertToHtml(inlineTagMap, entityTagMap, entityMap, block)
) : blockTagMap.default.replace(
'%content%',
InlineStylesProcessor.convertToHtml(inlineTagMap, block)
);
}
function _convertBlocksToHtml (blocks, entityMap, blockTagMap, entityTagMap) {
let html = '';
let nestLevel = []; // store the list type of the previous item: null/ol/ul
blocks.forEach((block) => {
// create tag for <ol> or <ul>: deal with ordered/unordered list item
// if the block is a list-item && the previous block is not a list-item
if (nestedTagMap[block.type] && nestLevel[0] !== block.type) {
html += nestedTagMap[block.type][0]; // start with <ol> or <ul>
nestLevel.unshift(block.type);
}
// end tag with </ol> or </ul>: deal with ordered/unordered list item
if (nestLevel.length > 0 && nestLevel[0] !== block.type) {
html += nestedTagMap[nestLevel.shift()][1]; // close with </ol> or </ul>
}
html += _convertInlineStyle(block, entityMap, blockTagMap, entityTagMap);
});
// end tag with </ol> or </ul>: or if it is the last block
if (blocks.length > 0 && nestedTagMap[blocks[blocks.length - 1].type]) {
html += nestedTagMap[nestLevel.shift()][1]; // close with </ol> or </ul>
}
return html;
}
function convertBlocksToApiData (blocks, entityMap, entityTagMap) {
let apiDataArr = List();
let content = [];
let nestLevel = [];
blocks.forEach((block) => {
// block is not a list-item
if (!nestedTagMap[block.type]) {
// if previous block is a list-item
if (content.length > 0 && nestLevel.length > 0) {
apiDataArr = apiDataArr.push(new ApiDataInstance({ type: nestLevel[0], content: content }));
content = [];
nestLevel.shift();
}
if (block.type.startsWith('atomic') || block.type.startsWith('media')) {
apiDataArr = apiDataArr.push(AtomicBlockProcessor.convertBlock(entityMap, block));
} else {
let converted = InlineStylesProcessor.convertToHtml(inlineTagMap, entityTagMap, entityMap, block);
let type = block.type;
// special case for block containing annotation entity
// set this block type as annotation
if (converted.indexOf(annotationIndicatorPrefix) > -1) {
type = ENTITY.ANNOTATION.type.toLowerCase();
}
apiDataArr = apiDataArr.push(new ApiDataInstance({ id: block.key, type: type, content: [converted] }));
}
} else {
let converted = InlineStylesProcessor.convertToHtml(inlineTagMap, entityTagMap, entityMap, block);
// previous block is not an item-list block
if (nestLevel.length === 0) {
nestLevel.unshift(block.type);
content.push(converted);
} else if (nestLevel[0] === block.type) {
// previous block is a item-list and current block is the same item-list
content.push(converted);
} else if (nestLevel[0] !== block.type) {
// previous block is a different item-list.
apiDataArr = apiDataArr.push(new ApiDataInstance({ id: block.key, type: nestLevel[0], content: content }));
content = [converted];
nestLevel[0] = block.type;
}
}
});
// last block is a item-list
if (blocks.length > 0 && nestLevel.length > 0) {
let block = blocks[blocks.length - 1];
apiDataArr = apiDataArr.push(new ApiDataInstance({ id: block.key, type: block.type, content: content }));
}
return apiDataArr;
}
function convertRawToHtml (raw, blockTagMap, entityTagMap) {
blockTagMap = _.merge({}, defaultBlockTagMap, blockTagMap);
entityTagMap = entityTagMap || defaultEntityTagMap;
let html = '';
raw = raw || {};
const blocks = Array.isArray(raw.blocks) ? raw.blocks : [];
const entityMap = typeof raw.entityMap === 'object' ? raw.entityMap : {};
html = _convertBlocksToHtml(blocks, entityMap, blockTagMap, entityTagMap);
return html;
}
function convertRawToApiData (raw) {
let apiData;
raw = raw || {};
const blocks = Array.isArray(raw.blocks) ? raw.blocks : [];
const entityMap = typeof raw.entityMap === 'object' ? raw.entityMap : {};
let entityTagMap = _.merge({}, defaultEntityTagMap, {
// special handling for annotation entity
// annotation entity data will be included in the speical comment.
[ENTITY.ANNOTATION.type]: [`<!--${annotationIndicatorPrefix}<%= JSON.stringify(data) %>--><!--`, '-->'],
});
apiData = convertBlocksToApiData(blocks, entityMap, entityTagMap);
return apiData;
}
export default {
convertToHtml: convertRawToHtml,
convertToApiData: convertRawToApiData,
};
| Java |
-- --------------------------------------------------------
-- Host: 127.0.0.1
-- Versión del servidor: 5.6.17 - MySQL Community Server (GPL)
-- SO del servidor: Win64
-- HeidiSQL Versión: 9.1.0.4867
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Volcando estructura para tabla ironfist_areslands.laravel_migrations
CREATE TABLE IF NOT EXISTS `laravel_migrations` (
`bundle` varchar(50) COLLATE utf8_bin NOT NULL,
`name` varchar(200) COLLATE utf8_bin NOT NULL,
`batch` int(11) NOT NULL,
PRIMARY KEY (`bundle`,`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- La exportación de datos fue deseleccionada.
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
| Java |
db_config = YAML.load(File.read(ROOT_DIR + '/../config/database.yaml'))['production']
ActiveRecord::Base.establish_connection(db_config)
class Node < ActiveRecord::Base
has_many :cidrs
has_one :limit
def flow_id
self.id + 10
end
def mark_in
$config['iptables']['mark_prefix_in'] + "%04d" % self.id
end
def mark_out
$config['iptables']['mark_prefix_out'] + "%04d" % self.id
end
end
class Cidr < ActiveRecord::Base
belongs_to :node
end
class Limit < ActiveRecord::Base
belongs_to :node
end
| Java |
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace CSharpGL
{
public partial class GL
{
#region OpenGL 2.0
// Constants
///// <summary>
/////
///// </summary>
//public const uint GL_BLEND_EQUATION_RGB = 0x8009;
///// <summary>
/////
///// </summary>
//public const uint GL_VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622;
///// <summary>
/////
///// </summary>
//public const uint GL_VERTEX_ATTRIB_ARRAY_SIZE = 0x8623;
///// <summary>
/////
///// </summary>
//public const uint GL_VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624;
///// <summary>
/////
///// </summary>
//public const uint GL_VERTEX_ATTRIB_ARRAY_TYPE = 0x8625;
///// <summary>
/////
///// </summary>
//public const uint GL_CURRENT_VERTEX_ATTRIB = 0x8626;
/// <summary>
///
/// </summary>
public const uint GL_VERTEX_PROGRAM_POINT_SIZE = 0x8642;
///// <summary>
/////
///// </summary>
//public const uint GL_VERTEX_ATTRIB_ARRAY_POINTER = 0x8645;
///// <summary>
/////
///// </summary>
//public const uint GL_STENCIL_BACK_FUNC = 0x8800;
///// <summary>
/////
///// </summary>
//public const uint GL_STENCIL_BACK_FAIL = 0x8801;
///// <summary>
/////
///// </summary>
//public const uint GL_STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802;
///// <summary>
/////
///// </summary>
//public const uint GL_STENCIL_BACK_PASS_DEPTH_PASS = 0x8803;
///// <summary>
/////
///// </summary>
//public const uint GL_MAX_DRAW_BUFFERS = 0x8824;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER0 = 0x8825;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER1 = 0x8826;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER2 = 0x8827;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER3 = 0x8828;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER4 = 0x8829;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER5 = 0x882A;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER6 = 0x882B;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER7 = 0x882C;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER8 = 0x882D;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER9 = 0x882E;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER10 = 0x882F;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER11 = 0x8830;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER12 = 0x8831;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER13 = 0x8832;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER14 = 0x8833;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER15 = 0x8834;
///// <summary>
/////
///// </summary>
//public const uint GL_BLEND_EQUATION_ALPHA = 0x883D;
///// <summary>
/////
///// </summary>
//public const uint GL_MAX_VERTEX_ATTRIBS = 0x8869;
///// <summary>
/////
///// </summary>
//public const uint GL_VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A;
///// <summary>
/////
///// </summary>
//public const uint GL_MAX_TEXTURE_IMAGE_UNITS = 0x8872;
/// <summary>
///
/// </summary>
public const uint GL_FRAGMENT_SHADER = 0x8B30;
/// <summary>
///
/// </summary>
public const uint GL_VERTEX_SHADER = 0x8B31;
/// <summary>
///
/// </summary>
public const uint GL_TESS_CONTROL_SHADER = 0x8E88;
/// <summary>
///
/// </summary>
public const uint GL_TESS_EVALUATION_SHADER = 0x8E87;
/// <summary>
///
/// </summary>
public const uint GL_MAX_FRAGMENT_UNIFORM_COMPONENTS = 0x8B49;
/// <summary>
///
/// </summary>
public const uint GL_MAX_VERTEX_UNIFORM_COMPONENTS = 0x8B4A;
/// <summary>
///
/// </summary>
public const uint GL_MAX_VARYING_FLOATS = 0x8B4B;
/// <summary>
///
/// </summary>
public const uint GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C;
/// <summary>
///
/// </summary>
public const uint GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D;
/// <summary>
///
/// </summary>
public const uint GL_SHADER_TYPE = 0x8B4F;
/// <summary>
///
/// </summary>
public const uint GL_FLOAT_VEC2 = 0x8B50;
/// <summary>
///
/// </summary>
public const uint GL_FLOAT_VEC3 = 0x8B51;
/// <summary>
///
/// </summary>
public const uint GL_FLOAT_VEC4 = 0x8B52;
/// <summary>
///
/// </summary>
public const uint GL_INT_VEC2 = 0x8B53;
/// <summary>
///
/// </summary>
public const uint GL_INT_VEC3 = 0x8B54;
/// <summary>
///
/// </summary>
public const uint GL_INT_VEC4 = 0x8B55;
/// <summary>
///
/// </summary>
public const uint GL_BOOL = 0x8B56;
/// <summary>
///
/// </summary>
public const uint GL_BOOL_VEC2 = 0x8B57;
/// <summary>
///
/// </summary>
public const uint GL_BOOL_VEC3 = 0x8B58;
/// <summary>
///
/// </summary>
public const uint GL_BOOL_VEC4 = 0x8B59;
/// <summary>
///
/// </summary>
public const uint GL_FLOAT_MAT2 = 0x8B5A;
/// <summary>
///
/// </summary>
public const uint GL_FLOAT_MAT3 = 0x8B5B;
/// <summary>
///
/// </summary>
public const uint GL_FLOAT_MAT4 = 0x8B5C;
/// <summary>
///
/// </summary>
public const uint GL_SAMPLER_1D = 0x8B5D;
/// <summary>
///
/// </summary>
public const uint GL_SAMPLER_2D = 0x8B5E;
/// <summary>
///
/// </summary>
public const uint GL_SAMPLER_3D = 0x8B5F;
/// <summary>
///
/// </summary>
public const uint GL_SAMPLER_CUBE = 0x8B60;
/// <summary>
///
/// </summary>
public const uint GL_SAMPLER_1D_SHADOW = 0x8B61;
/// <summary>
///
/// </summary>
public const uint GL_SAMPLER_2D_SHADOW = 0x8B62;
/// <summary>
///
/// </summary>
public const uint GL_DELETE_STATUS = 0x8B80;
/// <summary>
///
/// </summary>
public const uint GL_COMPILE_STATUS = 0x8B81;
/// <summary>
///
/// </summary>
public const uint GL_LINK_STATUS = 0x8B82;
/// <summary>
///
/// </summary>
public const uint GL_VALIDATE_STATUS = 0x8B83;
/// <summary>
///
/// </summary>
public const uint GL_INFO_LOG_LENGTH = 0x8B84;
/// <summary>
///
/// </summary>
public const uint GL_ATTACHED_SHADERS = 0x8B85;
/// <summary>
///
/// </summary>
public const uint GL_ACTIVE_UNIFORMS = 0x8B86;
/// <summary>
///
/// </summary>
public const uint GL_ACTIVE_UNIFORM_MAX_LENGTH = 0x8B87;
/// <summary>
///
/// </summary>
public const uint GL_SHADER_SOURCE_LENGTH = 0x8B88;
/// <summary>
///
/// </summary>
public const uint GL_ACTIVE_ATTRIBUTES = 0x8B89;
/// <summary>
///
/// </summary>
public const uint GL_ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8B8A;
/// <summary>
///
/// </summary>
public const uint GL_FRAGMENT_SHADER_DERIVATIVE_HINT = 0x8B8B;
/// <summary>
///
/// </summary>
public const uint GL_SHADING_LANGUAGE_VERSION = 0x8B8C;
/// <summary>
///
/// </summary>
public const uint GL_CURRENT_PROGRAM = 0x8B8D;
/// <summary>
///
/// </summary>
public const uint GL_POINT_SPRITE_COORD_ORIGIN = 0x8CA0;
/// <summary>
///
/// </summary>
public const uint GL_LOWER_LEFT = 0x8CA1;
/// <summary>
///
/// </summary>
public const uint GL_UPPER_LEFT = 0x8CA2;
/// <summary>
///
/// </summary>
public const uint GL_STENCIL_BACK_REF = 0x8CA3;
/// <summary>
///
/// </summary>
public const uint GL_STENCIL_BACK_VALUE_MASK = 0x8CA4;
/// <summary>
///
/// </summary>
public const uint GL_STENCIL_BACK_WRITEMASK = 0x8CA5;
#endregion OpenGL 2.0
}
} | Java |
package ch.hesso.master.caldynam;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Outline;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.Toast;
import ch.hesso.master.caldynam.ui.fragment.FoodAddFragment;
import ch.hesso.master.caldynam.ui.fragment.FoodCatalogFragment;
import ch.hesso.master.caldynam.ui.fragment.FoodViewFragment;
import ch.hesso.master.caldynam.ui.fragment.LoggingFragment;
import ch.hesso.master.caldynam.ui.fragment.NavigationDrawerFragment;
import ch.hesso.master.caldynam.ui.fragment.SummaryFragment;
import ch.hesso.master.caldynam.ui.fragment.WeightMeasurementFragment;
import me.drakeet.materialdialog.MaterialDialog;
public class MainActivity extends ActionBarActivity implements
NavigationDrawerFragment.NavigationDrawerCallbacks,
SummaryFragment.OnFragmentInteractionListener,
WeightMeasurementFragment.OnFragmentInteractionListener,
LoggingFragment.OnFragmentInteractionListener,
FoodCatalogFragment.OnFragmentInteractionListener,
FoodAddFragment.OnFragmentInteractionListener,
FoodViewFragment.OnFragmentInteractionListener {
private Fragment fragment = null;
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #updateToolbar()}.
*/
private CharSequence mTitle;
private Toolbar mToolbar;
private View mFabButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Handle Toolbar
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// Handle different Drawer States :D
// mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
// Fab Button
mFabButton = findViewById(R.id.fab_button);
mFabButton.setOnClickListener(fabClickListener);
mFabButton.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
int size = getResources().getDimensionPixelSize(R.dimen.fab_size);
outline.setOval(0, 0, size, size);
}
});
mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer);
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout)
);
updateToolbar();
mTitle = getTitle();
}
@Override
public void onNavigationDrawerItemSelected(int position) {
switch (position) {
case 0:
fragment = SummaryFragment.newInstance();
break;
case 1:
fragment = WeightMeasurementFragment.newInstance();
break;
case 2:
fragment = LoggingFragment.newInstance();
break;
case 3:
fragment = FoodCatalogFragment.newInstance();
break;
}
getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
loadFragment(fragment, false);
}
View.OnClickListener fabClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "New data", Toast.LENGTH_SHORT).show();
}
};
public void onSectionAttached(int resourceId) {
mTitle = (resourceId != 0) ? getString(resourceId) : null;
}
public void updateToolbar() {
if (mTitle != null) {
mToolbar.setTitle(mTitle);
}
resizeToolbar(mNavigationDrawerFragment.isToolbarLarge() ? 1.0f : 0.0f);
mFabButton.setAlpha(mNavigationDrawerFragment.isFABVisible() ? 1.0f : 0.0f);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
if (fragment != null) {
fragment.onCreateOptionsMenu(menu, getMenuInflater());
}
//getMenuInflater().inflate(R.menu.main, menu);
updateToolbar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
/**
* Handle action bar item clicks here. The action bar will
* automatically handle clicks on the Home/Up button, so long
* as you specify a parent activity in AndroidManifest.xml.
*
* @param item
* @return
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
fragment.onOptionsItemSelected(item);
if (id == R.id.action_about) {
showAboutDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed(){
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.d(Constants.PROJECT_NAME, "Popping backstack");
fm.popBackStackImmediate();
this.fragment = getActiveFragment();
} else {
Log.d(Constants.PROJECT_NAME, "Nothing on backstack, calling super");
super.onBackPressed();
}
}
private void showAboutDialog() {
View contentView = LayoutInflater.from(this)
.inflate(R.layout.fragment_about_dialog, null);
final MaterialDialog aboutDialog = new MaterialDialog(this);
aboutDialog
.setContentView(contentView)
.setPositiveButton(getString(R.string.ok), new View.OnClickListener() {
@Override
public void onClick(View v) {
aboutDialog.dismiss();
}
});
aboutDialog.show();
}
public Fragment getActiveFragment() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
return null;
}
String tag = getFragmentManager()
.getBackStackEntryAt(getFragmentManager().getBackStackEntryCount() - 1)
.getName();
return getFragmentManager().findFragmentByTag(tag);
}
public void loadFragment(Fragment fragment) {
loadFragment(fragment, true);
}
public void loadFragment(Fragment fragment, boolean addToBackStack) {
this.fragment = fragment;
String tag = fragment.getClass().getSimpleName();
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, this.fragment, tag);
if (addToBackStack) {
Log.d("Fragment", tag);
ft.addToBackStack(tag);
}
ft.commit();
// Replace current menu with the fragment menu
this.invalidateOptionsMenu();
}
public void resizeToolbar(float offset) {
float minSize = mToolbar.getMinimumHeight();
float maxSize = getResources().getDimension(R.dimen.toolbar_height_large);
ViewGroup.LayoutParams layout = mToolbar.getLayoutParams();
layout.height = (int) (minSize + (maxSize - minSize) * offset);
mToolbar.requestLayout();
}
public View getAddButton() {
return mFabButton;
}
/**
* an animation for resizing the view.
*/
private class ResizeAnimation extends Animation {
private View mView;
private float mToHeight;
private float mFromHeight;
private float mToWidth;
private float mFromWidth;
public ResizeAnimation(View v, float fromWidth, float fromHeight, float toWidth, float toHeight) {
mToHeight = toHeight;
mToWidth = toWidth;
mFromHeight = fromHeight;
mFromWidth = fromWidth;
mView = v;
setDuration(300);
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
float height = (mToHeight - mFromHeight) * interpolatedTime + mFromHeight;
float width = (mToWidth - mFromWidth) * interpolatedTime + mFromWidth;
ViewGroup.LayoutParams p = mView.getLayoutParams();
p.height = (int) height;
p.width = (int) width;
mView.requestLayout();
}
}
} | Java |
default:
@echo "'make check'" for tests
@echo "'make check-cov'" for tests with coverage
@echo "'make lint'" for source code checks
@echo "'make ckpatch'" to check a patch
@echo "'make clean'" to clean generated files
@echo "'make man'" to generate sphinx documentation
@echo "'make update-requirements'" to update the requirements files
.PHONY: check
check:
pytest --verbose
.PHONY: check-cov
check-cov:
pytest --verbose --with-cov libqtile --cov-report term-missing
.PHONY: lint
lint:
flake8 ./libqtile bin/q* ./test
.PHONY: ckpatch
ckpatch: lint check
.PHONY: clean
clean:
-rm -rf dist qtile.egg-info docs/_build build/
# This is a little ugly: we want to be able to have users just run
# 'python setup.py install' to install qtile, but we would also like to install
# the man pages. I can't figure out a way to have the 'build' target invoke the
# 'build_sphinx' target as well, so we commit the man pages, since they are
# used in the 'install' target.
.PHONY: man
man:
python setup.py build_sphinx -b man
cp build/sphinx/man/* resources/
.PHONY: update-requirements
update-requirements:
pip-compile requirements.in
| Java |
# encoding: utf-8
class DocsController < ApplicationController
get '/doc' do
before_all
haml :docs, :layout => :'layouts/main'
end
end | Java |
//
// SR_ForgotPasswordViewController.h
// scanreader
//
// Created by jbmac01 on 16/7/21.
// Copyright © 2016年 jb. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface SR_ForgotPasswordViewController : UIViewController
@end
| Java |
#include <iostream>
#include <string>
#include <tuple>
std::tuple<int,int> wczytaj_liczby();
int main ()
{
std::string opcja;
do {
int a,b;
std::cout << "wybierz opcje przeliczania" << std::endl;
std::cout << "dodawanie, odejmowanie, mnozenie czy dzielenie?" << std::endl;
std::cin >> opcja;
if (opcja=="dodawanie"){
std::tie(a,b)=wczytaj_liczby();
std::cout << "wynik dodawania " << a+b << std::endl;
}
else if (opcja=="odejmowanie"){
std::tie(a,b)=wczytaj_liczby();
std::cout << "wynik odejmowania " << a-b << std::endl;
}
else if (opcja=="mnozenie"){
std::tie(a,b)=wczytaj_liczby();
std::cout << "wynik mnozenia " << a*b << std::endl;
}
else if (opcja=="dzielenie"){
std::tie(a,b)=wczytaj_liczby();
std::cout << "wynik dzielenia " << a/b << std::endl;
}
else std::cout << "nieznana opcja" << std::endl;
} while(opcja!="koniec");
}
std::tuple<int,int> wczytaj_liczby() {
int a,b;
std::cout << "podaj pierwsza liczbe" << std::endl;
std::cin >> a;
std::cout << "podaj druga liczbe" << std::endl;
std::cin >> b;
return std::make_tuple(a,b);
}
| Java |
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/ads/googleads/v2/resources/expanded_landing_page_view.proto
package resources
import (
fmt "fmt"
math "math"
proto "github.com/golang/protobuf/proto"
wrappers "github.com/golang/protobuf/ptypes/wrappers"
_ "google.golang.org/genproto/googleapis/api/annotations"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
// A landing page view with metrics aggregated at the expanded final URL
// level.
type ExpandedLandingPageView struct {
// The resource name of the expanded landing page view.
// Expanded landing page view resource names have the form:
//
// `customers/{customer_id}/expandedLandingPageViews/{expanded_final_url_fingerprint}`
ResourceName string `protobuf:"bytes,1,opt,name=resource_name,json=resourceName,proto3" json:"resource_name,omitempty"`
// The final URL that clicks are directed to.
ExpandedFinalUrl *wrappers.StringValue `protobuf:"bytes,2,opt,name=expanded_final_url,json=expandedFinalUrl,proto3" json:"expanded_final_url,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *ExpandedLandingPageView) Reset() { *m = ExpandedLandingPageView{} }
func (m *ExpandedLandingPageView) String() string { return proto.CompactTextString(m) }
func (*ExpandedLandingPageView) ProtoMessage() {}
func (*ExpandedLandingPageView) Descriptor() ([]byte, []int) {
return fileDescriptor_f0d9f18d76cfc25b, []int{0}
}
func (m *ExpandedLandingPageView) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_ExpandedLandingPageView.Unmarshal(m, b)
}
func (m *ExpandedLandingPageView) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_ExpandedLandingPageView.Marshal(b, m, deterministic)
}
func (m *ExpandedLandingPageView) XXX_Merge(src proto.Message) {
xxx_messageInfo_ExpandedLandingPageView.Merge(m, src)
}
func (m *ExpandedLandingPageView) XXX_Size() int {
return xxx_messageInfo_ExpandedLandingPageView.Size(m)
}
func (m *ExpandedLandingPageView) XXX_DiscardUnknown() {
xxx_messageInfo_ExpandedLandingPageView.DiscardUnknown(m)
}
var xxx_messageInfo_ExpandedLandingPageView proto.InternalMessageInfo
func (m *ExpandedLandingPageView) GetResourceName() string {
if m != nil {
return m.ResourceName
}
return ""
}
func (m *ExpandedLandingPageView) GetExpandedFinalUrl() *wrappers.StringValue {
if m != nil {
return m.ExpandedFinalUrl
}
return nil
}
func init() {
proto.RegisterType((*ExpandedLandingPageView)(nil), "google.ads.googleads.v2.resources.ExpandedLandingPageView")
}
func init() {
proto.RegisterFile("google/ads/googleads/v2/resources/expanded_landing_page_view.proto", fileDescriptor_f0d9f18d76cfc25b)
}
var fileDescriptor_f0d9f18d76cfc25b = []byte{
// 342 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x91, 0xc1, 0x4a, 0xf3, 0x40,
0x14, 0x85, 0x49, 0x7e, 0xf8, 0xc1, 0xa8, 0x20, 0xd9, 0x58, 0x4a, 0x91, 0x56, 0x29, 0x74, 0x35,
0x81, 0xb8, 0x1b, 0x57, 0x29, 0x68, 0xa1, 0x88, 0x94, 0x8a, 0x59, 0x48, 0x20, 0xdc, 0x76, 0x6e,
0x87, 0x81, 0x74, 0x26, 0xcc, 0x24, 0xad, 0xaf, 0xa0, 0x8f, 0xe1, 0xd2, 0x47, 0xf1, 0x51, 0x7c,
0x0a, 0x49, 0x93, 0x99, 0x9d, 0xba, 0x3b, 0xcc, 0x9c, 0x73, 0xee, 0x77, 0xb9, 0xc1, 0x94, 0x2b,
0xc5, 0x0b, 0x8c, 0x80, 0x99, 0xa8, 0x95, 0x8d, 0xda, 0xc5, 0x91, 0x46, 0xa3, 0x6a, 0xbd, 0x46,
0x13, 0xe1, 0x4b, 0x09, 0x92, 0x21, 0xcb, 0x0b, 0x90, 0x4c, 0x48, 0x9e, 0x97, 0xc0, 0x31, 0xdf,
0x09, 0xdc, 0x93, 0x52, 0xab, 0x4a, 0x85, 0xa3, 0x36, 0x48, 0x80, 0x19, 0xe2, 0x3a, 0xc8, 0x2e,
0x26, 0xae, 0xa3, 0x7f, 0xd1, 0x8d, 0x39, 0x04, 0x56, 0xf5, 0x26, 0xda, 0x6b, 0x28, 0x4b, 0xd4,
0xa6, 0xad, 0xe8, 0x0f, 0x2c, 0x46, 0x29, 0x22, 0x90, 0x52, 0x55, 0x50, 0x09, 0x25, 0xbb, 0xdf,
0xcb, 0x37, 0x2f, 0x38, 0xbf, 0xed, 0x28, 0xee, 0x5b, 0x88, 0x05, 0x70, 0x4c, 0x05, 0xee, 0xc3,
0xab, 0xe0, 0xd4, 0x8e, 0xc9, 0x25, 0x6c, 0xb1, 0xe7, 0x0d, 0xbd, 0xc9, 0xd1, 0xf2, 0xc4, 0x3e,
0x3e, 0xc0, 0x16, 0xc3, 0x79, 0x10, 0xba, 0x2d, 0x36, 0x42, 0x42, 0x91, 0xd7, 0xba, 0xe8, 0xf9,
0x43, 0x6f, 0x72, 0x1c, 0x0f, 0x3a, 0x66, 0x62, 0xd9, 0xc8, 0x63, 0xa5, 0x85, 0xe4, 0x29, 0x14,
0x35, 0x2e, 0xcf, 0x6c, 0xee, 0xae, 0x89, 0x3d, 0xe9, 0x62, 0xfa, 0xea, 0x07, 0xe3, 0xb5, 0xda,
0x92, 0x3f, 0x97, 0x9e, 0x0e, 0x7e, 0x60, 0x5e, 0x34, 0x83, 0x16, 0xde, 0xf3, 0xbc, 0xab, 0xe0,
0xaa, 0x00, 0xc9, 0x89, 0xd2, 0x3c, 0xe2, 0x28, 0x0f, 0x18, 0xf6, 0x16, 0xa5, 0x30, 0xbf, 0x9c,
0xe6, 0xc6, 0xa9, 0x77, 0xff, 0xdf, 0x2c, 0x49, 0x3e, 0xfc, 0xd1, 0xac, 0xad, 0x4c, 0x98, 0x21,
0xad, 0x6c, 0x54, 0x1a, 0x93, 0xa5, 0x75, 0x7e, 0x5a, 0x4f, 0x96, 0x30, 0x93, 0x39, 0x4f, 0x96,
0xc6, 0x99, 0xf3, 0x7c, 0xf9, 0xe3, 0xf6, 0x83, 0xd2, 0x84, 0x19, 0x4a, 0x9d, 0x8b, 0xd2, 0x34,
0xa6, 0xd4, 0xf9, 0x56, 0xff, 0x0f, 0xb0, 0xd7, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x09, 0x2a,
0xe3, 0x32, 0x46, 0x02, 0x00, 0x00,
}
| Java |
var log = require('./logger')('reporter', 'yellow');
var colors = require('colors');
/* eslint no-console: 0 */
module.exports = function(diff) {
var keys = Object.keys(diff);
var count = 0;
var timer = log.timer('reporting');
if (keys.length === 0) {
log('✔ no diff detected', 'green');
} else {
log('✗ build doesn\'t match!', 'red');
console.log('\nREPORT\n' + colors.white.bgBlack(' [selector] ') + '\n [attribute] ' + '[actual] '.red + '[expected]'.green);
keys.forEach(function(key) {
var rules = Object.keys(diff[key]);
console.log(colors.white.bgBlack('\n ' + key + ' '));
rules.forEach(function(rule) {
count++;
var expected = pretty(diff[key][rule].expected);
var actual = pretty(diff[key][rule].actual);
console.log(' ' + rule + ': ' + actual.red + ' ' + expected.green);
});
});
}
console.log('');
var c = count === 0 ? 'green' : 'red';
log('Broken rules: ' + count, c);
log('Affected selectors: ' + keys.length, c);
timer();
};
function pretty(val) {
if (typeof val !== 'string') {
val = JSON.stringify(val, null, 4);
}
return val;
} | Java |
<html>
<head>
<title>%%%name%%% - Wright! Magazine</title>
%%%=templates/headers.html%%%
<link rel="stylesheet" href="%%%urlroot%%%fonts/stylesheet.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="%%%urlroot%%%js/wright.js?a=1"></script>
</head>
<body onload="onload()">
%%%=templates/headerbar.html%%%
<div id="banner">
<div class="image" style="background-image:url('%%%urltapes%%%%%%issueid%%%/screenshots/%%%screenshots.1%%%')"></div>
<div class="filter"></div>
<div class="text">
<h1><a href="#settings">%%%name%%% %%%edition%%%</a></h1>
<p>%%%genre%%%, © %%%author%%% %%%year%%%</p>
</div>
</div>
<div id="game"></div>
<div id="body">
<p>
<img src="%%%urltapes%%%%%%issueid%%%/screenshots/%%%screenshots.0%%%" class="articleimage">
%%%description%%%
</p>
<p class="small">
(Want to share something? You can find me <a href="https://twitter.com/KesieV">on Twitter</a>!)
</p>
<p class="links">
<a href="https://www.kesiev.com%%%urlroot%%%webapp/%%%issueid%%%/index.html"><img src="%%%urlroot%%%publishers/site/images/tape.png">Install / Add to home</a>
<a href="https://github.com/kesiev/Wright/tree/master/tapes/%%%issueid%%%"><img src="%%%urlroot%%%publishers/site/images/github.png">View game sources</a>
<span>...or play it online below!</span>
</p>
</div>
<div id="settingscontainer">
<div id="settings"></div>
</div>
%%%=templates/footerbar.html%%%
</body>
<script>
function onload() {
runSingleWright('%%%issueid%%%',
{
controllerDefaults:{
PeerJSApiKey:'tlaw8l8f0kiysyvi',
ChromecastApplicationID:'60B7E7EC',
ChromecastNamespace:'urn:x-cast:com.kesiev.wright'
},
tapesRoot:'%%%urltapes%%%',
systemRoot:'%%%urlroot%%%system',
gameContainer:document.getElementById('game'),settingsContainer:document.getElementById('settings'),
onRun:function(){document.getElementById('body').innerHTML='';}
}
);
}
</script>
</html> | Java |
/**
* The MIT License
* Copyright (c) 2003 David G Jones
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package info.dgjones.abora.white.edgeregion;
import java.io.PrintWriter;
import info.dgjones.abora.white.rcvr.Rcvr;
import info.dgjones.abora.white.rcvr.Xmtr;
import info.dgjones.abora.white.spaces.basic.Position;
import info.dgjones.abora.white.xpp.basic.Heaper;
/**
* Clients of EdgeManager define concrete subclasses of this, which are then used by the
* EdgeManager code
*/
public abstract class TransitionEdge extends Heaper {
/*
udanax-top.st:63348:
Heaper subclass: #TransitionEdge
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Xanadu-EdgeRegion'!
*/
/*
udanax-top.st:63352:
TransitionEdge comment:
'Clients of EdgeManager define concrete subclasses of this, which are then used by the EdgeManager code'!
*/
/*
udanax-top.st:63354:
(TransitionEdge getOrMakeCxxClassDescription)
attributes: ((Set new) add: #DEFERRED; add: #COPY; yourself)!
*/
/////////////////////////////////////////////
// Constructors
protected TransitionEdge() {
super();
}
public TransitionEdge ceiling(TransitionEdge other) {
if (other.isGE(this)) {
return other;
} else {
return this;
}
/*
udanax-top.st:63359:TransitionEdge methodsFor: 'accessing'!
{TransitionEdge} ceiling: other {TransitionEdge}
(other isGE: self)
ifTrue: [^other]
ifFalse: [^self]!
*/
}
public TransitionEdge floor(TransitionEdge other) {
if (isGE(other)) {
return other;
} else {
return this;
}
/*
udanax-top.st:63365:TransitionEdge methodsFor: 'accessing'!
{TransitionEdge} floor: other {TransitionEdge}
(self isGE: other)
ifTrue: [^other]
ifFalse: [^self]!
*/
}
public int actualHashForEqual() {
return System.identityHashCode(this);
// return Heaper.takeOop();
/*
udanax-top.st:63373:TransitionEdge methodsFor: 'testing'!
{UInt32} actualHashForEqual
^Heaper takeOop!
*/
}
/**
* Whether the position is strictly less than this edge
*/
public abstract boolean follows(Position pos);
/*
udanax-top.st:63377:TransitionEdge methodsFor: 'testing'!
{BooleanVar} follows: pos {Position}
"Whether the position is strictly less than this edge"
self subclassResponsibility!
*/
public abstract boolean isEqual(Heaper other);
/*
udanax-top.st:63382:TransitionEdge methodsFor: 'testing'!
{BooleanVar} isEqual: other {Heaper}
self subclassResponsibility!
*/
/**
* Whether there is precisely one position between this edge and the next one
*/
public abstract boolean isFollowedBy(TransitionEdge next);
/*
udanax-top.st:63386:TransitionEdge methodsFor: 'testing'!
{BooleanVar} isFollowedBy: next {TransitionEdge}
"Whether there is precisely one position between this edge and the next one"
self subclassResponsibility!
*/
/**
* Defines a full ordering among all edges in a given CoordinateSpace
*/
public abstract boolean isGE(TransitionEdge other);
/*
udanax-top.st:63391:TransitionEdge methodsFor: 'testing'!
{BooleanVar} isGE: other {TransitionEdge}
"Defines a full ordering among all edges in a given CoordinateSpace"
self subclassResponsibility!
*/
/**
* Whether this edge touches the same position the other does
*/
public abstract boolean touches(TransitionEdge other);
/*
udanax-top.st:63396:TransitionEdge methodsFor: 'testing'!
{BooleanVar} touches: other {TransitionEdge}
"Whether this edge touches the same position the other does"
self subclassResponsibility!
*/
/**
* Print a description of this transition
*/
public abstract void printTransitionOn(PrintWriter oo, boolean entering, boolean touchesPrevious);
/*
udanax-top.st:63403:TransitionEdge methodsFor: 'printing'!
{void} printTransitionOn: oo {ostream reference}
with: entering {BooleanVar}
with: touchesPrevious {BooleanVar}
"Print a description of this transition"
self subclassResponsibility!
*/
public TransitionEdge(Rcvr receiver) {
super(receiver);
/*
udanax-top.st:63412:TransitionEdge methodsFor: 'generated:'!
create.Rcvr: receiver {Rcvr}
super create.Rcvr: receiver.!
*/
}
public void sendSelfTo(Xmtr xmtr) {
super.sendSelfTo(xmtr);
/*
udanax-top.st:63415:TransitionEdge methodsFor: 'generated:'!
{void} sendSelfTo: xmtr {Xmtr}
super sendSelfTo: xmtr.!
*/
}
}
| Java |
<?php
namespace App\Repository;
/**
* ImageRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ImageRepository extends \Doctrine\ORM\EntityRepository
{
}
| Java |
'use strict';
const moment = require('moment-timezone');
const mongoose = web.require('mongoose');
const Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
const OTHERS = {key: 'OTH', value: 'Others'};
module.exports = function({
modelName,
displayName,
cols,
colMap = {},
enableDangerousClientFiltering = false,
style,
addPermission,
editPermission,
populate,
// do you validations, extra save logic here
// throw an error or handle it yourself by returning true
beforeSave = (record, req, res)=>{},
beforeRender,
afterSave,
parentTemplate,
shouldShowDeleteAction = true,
shouldShowSaveButton = true,
additionalSubmitButtons = [],
handlers = {},
} = {}) {
return {
get: async function(req, res) {
let queryModel = enableDangerousClientFiltering && req.query.model;
let modelStr = modelName || queryModel;
let recId = req.query._id;
let isUpdateMode = recId;
let isInsertMode = !isUpdateMode;
let querySaveView = req.query.saveView;
let queryDisplayName = displayName || req.query.displayName;
let colIds = [];
for (let col of cols || []) {
if (web.objectUtils.isString(col)) {
colIds.push(col);
} else {
colIds.push(col.id);
colMap[col.id] = Object.assign({}, col, colMap[col.id]);
}
}
let model = web.cms.dbedit.utils.searchModel(modelStr);
// deep clone
let modelAttr = model.getModelDictionary();
let modelSchema = modelAttr.schema;
let filterCols = (colIds.length > 0 ? colIds : null)
|| (enableDangerousClientFiltering && req.query.filterCols && req.query.filterCols.split(','))
|| Object.keys(modelSchema);
for (let colId of filterCols) {
if (!colMap[colId]) {
colMap[colId] = {};
}
}
const readOnly = (enableDangerousClientFiltering && req.query.readOnly && req.query.readOnly.split(','));
let myShouldShowDeleteAction = shouldShowDeleteAction;
if (enableDangerousClientFiltering && req.query.shouldShowDeleteAction) {
myShouldShowDeleteAction = req.query.shouldShowDeleteAction === "Y";
}
let myModelName = modelAttr.name;
let modelDisplayName = queryDisplayName || modelAttr.displayName || modelAttr.name;
parentTemplate = parentTemplate || web.cms.conf.adminTemplate;
let redirectAfter = req.query._backUrl
|| ('/admin/dbedit/list'
+ (queryModel ? ('?model=' + encodeURIComponent(queryModel)) : ''));
//can be optimized by avoiding query if there's no id
let rec = {};
if (isUpdateMode) {
let recProm = model.findOne({_id:recId});
if (populate) {
recProm.populate(populate);
}
rec = await recProm.exec();
if (!rec) {
req.flash('error', 'Record not found.');
res.redirect(redirectAfter);
return;
}
}
if (req.session.recCache
&& req.session.recCache[req.url]) {
rec = req.session.recCache[req.url];
req.session.recCache[req.url] = null;
}
let pageTitle = null;
if (isUpdateMode) {
pageTitle = 'Update ' + modelDisplayName;
} else {
pageTitle = 'Create ' + modelDisplayName;
}
for (let colName in colMap) {
let colMapObj = colMap[colName];
if (colMapObj.default && rec[colName] === undefined) {
rec[colName] = colMapObj.default;
}
if (colMapObj.colSpan) {
colMapObj.colSpanStr = '-' + colMapObj.colSpan.toString();
}
if (colMapObj.inline) {
colMapObj.inlineStr = " form-check-inline mr-2";
}
if (colMapObj.hideLabel === true) {
colMapObj._hideLabel = colMapObj.hideLabel;
} else {
colMapObj._hideLabel = false;
}
if (colMapObj.addOthers) {
colMapObj._addOthers = Object.assign({
value: getVal(rec, colMapObj.addOthers.id),
placeholder: 'If Others, please specify'
}, colMapObj.addOthers);
}
if (colMapObj._addOthers) {
colMapObj.inputValues.set(OTHERS.key, OTHERS.value)
}
handleModelSchemaForColObj(modelSchema, colName, colMap, rec)
if (handlers[colName]) {
colMapObj.htmlValue = await handlers[colName](rec, isUpdateMode, req);
}
handleColObjMultiple(colMapObj, colName, rec);
if (colMapObj.inputValues && web.objectUtils.isFunction(colMapObj.inputValues)) {
// need to do this to avoid the cache and overwriting the existing
colMapObj.inputValuesFunc = colMapObj.inputValues;
}
if (colMapObj.inputValuesFunc) {
colMapObj.inputValues = await colMapObj.inputValuesFunc(rec, req, isInsertMode);
}
colMapObj.readOnlyComputed = (readOnly && readOnly.indexOf(colName) !== -1)
|| (colMapObj.readOnly === 'U' && isUpdateMode)
|| (colMapObj.readOnly === 'I' && isInsertMode)
|| (web.objectUtils.isFunction(colMapObj.readOnly) && await colMapObj.readOnly(rec, req, isInsertMode))
|| colMapObj.readOnly === true;
colMapObj.visibleComputed = true;
if (colMapObj.visible !== undefined) {
colMapObj.visibleComputed = await colMapObj.visible(rec, req, isInsertMode);
}
if (colMapObj.header) {
colMapObj.headerComputed = (web.objectUtils.isFunction(colMapObj.header) && await colMapObj.header(rec, req, isInsertMode))
|| colMapObj.header;
}
let propsStrArr = [];
colMapObj.props = colMapObj.props || {};
let inputType = colMapObj.inputType || colMapObj.props.type || 'text';
if (inputType === 'money') {
inputType = 'number';
colMapObj.props.step = '0.01';
}
switch (inputType) {
case 'datetime':
case 'date':
case 'radio':
case 'checkbox':
case 'select': break;
default: colMapObj.props.type = inputType;
}
for (let propName in colMapObj.props) {
let propsValStr = colMapObj.props[propName] || '';
propsStrArr.push(`${propName}="${web.stringUtils.escapeHTML(propsValStr)}"`)
}
// TODO: unify all props later
colMapObj._propsHtml = propsStrArr.join(' ');
}
let myShowSaveButton = true;
if (isUpdateMode && shouldShowSaveButton !== undefined) {
myShowSaveButton =
(web.objectUtils.isFunction(shouldShowSaveButton) && await shouldShowSaveButton(rec, req, isInsertMode))
|| shouldShowSaveButton === true;
}
for (let submitBtnObj of additionalSubmitButtons) {
submitBtnObj.visibleComputed = true;
if (submitBtnObj.visible) {
submitBtnObj.visibleComputed = await submitBtnObj.visible(rec, req, isInsertMode);
}
}
let fileBackUrl = encodeURIComponent(req.url);
let options = {
rec: rec,
style: style,
isUpdateMode: isUpdateMode,
modelAttr: modelAttr,
queryModelName: queryModel,
pageTitle: pageTitle,
redirectAfter: redirectAfter,
fileBackUrl: fileBackUrl,
colMap: colMap,
parentTemplate: parentTemplate,
filterCols: filterCols,
shouldShowDeleteAction: myShouldShowDeleteAction,
shouldShowSaveButton: myShowSaveButton,
additionalSubmitButtons: additionalSubmitButtons,
};
if (beforeRender) {
await beforeRender(req, res, options);
}
let saveView = (enableDangerousClientFiltering && querySaveView) || web.cms.dbedit.conf.saveView;
res.render(saveView, options);
},
post: async function(req, res) {
// TODO: proper error handling
let queryModelName = enableDangerousClientFiltering && req.body.modelName;
let myModelName = modelName || queryModelName || '';
let recId = req.body._id;
if (recId == "") {
recId = null;
}
let isInsertMode = !recId;
if (isInsertMode) {
if (addPermission && !req.user.hasPermission(addPermission)) {
throw new Error("You don't have a permission to add this record.");
}
} else {
if (editPermission && !req.user.hasPermission(editPermission)) {
throw new Error("You don't have a permission to edit this record.");
}
}
let model = web.models(myModelName);
let rec = await save(recId, req, res, model, beforeSave, colMap, isInsertMode, queryModelName);
if (!rec) {
return;
}
if (afterSave && await afterSave(rec, req, res, isInsertMode)) {
return;
}
let handled = false;
for (let submitBtnObj of additionalSubmitButtons) {
if (req.body.hasOwnProperty(submitBtnObj.actionName)) {
handled = await submitBtnObj.handler(rec, req, res);
}
}
if (!handled) {
req.flash('info', 'Record saved.');
res.redirect(getRedirectAfter(rec, req, queryModelName));
}
}
}
}
async function save(recId, req, res, model, beforeSave, colMap, isInsertMode, queryModelName) {
let rec = await model.findOne({_id:recId});
let modelAttr = model.getModelDictionary();
let modelSchema = modelAttr.schema;
// TODO: use the col list to set one by one
let attrToSet = Object.assign({}, req.body);
const shouldSetProperTimezone = web.conf.timezone;
for (let colName in modelAttr.schema) {
if (attrToSet[colName] || attrToSet[colName] === "") {
if (web.objectUtils.isArray(modelSchema[colName])) {
attrToSet[colName] = web.ext.arrayUtils.removeDuplicateAndEmpty(attrToSet[colName]);
}
let dbCol = modelAttr.schema[colName];
if (shouldSetProperTimezone && dbCol.type == Date) {
if (attrToSet[colName]) {
let date = attrToSet[colName];
let dateFormat = 'MM/DD/YYYY';
if (colMap[colName] && colMap[colName].inputType === "datetime") {
dateFormat = 'MM/DD/YYYY hh:mm A';
}
if (!web.ext.dateTimeUtils.momentFromString(date, dateFormat).isValid()) {
req.flash('error', `${colMap[colName].label} is an invalid date.`);
res.redirect(req.url);
return;
}
attrToSet[colName] = moment.tz(attrToSet[colName], dateFormat, web.conf.timezone).toDate();
} else if (attrToSet[colName] === "") {
attrToSet[colName] = null;
}
} else if (dbCol.type == ObjectId) {
if (attrToSet[colName] === "") {
// for errors of casting empty string to object id
attrToSet[colName] = null;
}
}
}
}
if (!rec) {
rec = new model();
attrToSet.createDt = new Date();
attrToSet.createBy = req.user._id;
}
delete attrToSet._id;
attrToSet[web.cms.dbedit.conf.updateDtCol] = new Date();
attrToSet[web.cms.dbedit.conf.updateByCol] = req.user._id;
rec.set(attrToSet);
try {
if (await beforeSave(rec, req, res, isInsertMode)) {
return null;
}
} catch (ex) {
console.error("beforeSave threw an error", ex);
let errStr = ex.message || "Error on saving record.";
req.flash('error', errStr);
req.session.recCache[req.url] = req.body;
res.redirect(req.url);
return null;
}
if (web.ext && web.ext.dbUtils) {
await web.ext.dbUtils.save(rec, req);
} else {
await rec.save();
}
return rec;
}
function handleModelSchemaForColObj(modelSchema, colName, colMap, rec) {
let colMapObj = colMap[colName];
if (modelSchema[colName]) {
let attr = modelSchema[colName];
if (!colMap[colName]) {
colMap[colName] = {};
}
if (attr.default && rec[colName] === undefined) {
// assign default values if non existing
rec[colName] = attr.default;
}
colMapObj.required = colMapObj.required || attr.required;
colMapObj.label = colMapObj.label == null ? attr.dbeditDisplay || web.cms.dbedit.utils.camelToTitle(colName) : colMapObj.label;
}
}
function getRedirectAfter(rec, req, queryModelName) {
let redirectAfter = 'save?_id=' + encodeURIComponent(rec._id.toString());
if (queryModelName) {
redirectAfter += '&model=' + encodeURIComponent(queryModelName);
}
if (req.body._backUrl) {
redirectAfter += '&_backUrl=' + encodeURIComponent(req.body._backUrl);
}
return redirectAfter;
}
function handleColObjMultiple(colMapObj, colName, rec) {
colMapObj.multiple = colMapObj.multiple;
if (colMapObj.multiple) {
colMapObj.inputName = colName + '[]';
colMapObj._copies = colMapObj.copies;
if (!colMapObj._copies) {
if (colMapObj.inputType === 'checkbox') {
colMapObj._copies = 1;
} else {
colMapObj._copies = 3;
}
}
if (rec[colName]
&& rec[colName].length > colMapObj._copies
&& colMapObj.inputType !== 'checkbox') {
colMapObj._copies = rec[colName].length;
}
} else {
colMapObj.inputName = colName;
colMapObj._copies = colMapObj._copies || 1;
}
}
function getVal(recObj, key) {
if (key.indexOf('.') == -1) {
return recObj[key];
} else {
return web.objectUtils.resolvePath(recObj, key);
}
} | Java |
//
// NYSegmentedControl+CBDSettings.h
// SmartMathsMP
//
// Created by Colas on 11/08/2015.
// Copyright (c) 2015 cassiopeia. All rights reserved.
//
#import "NYSegmentedControl.h"
@interface NYSegmentedControl (CBDSettings)
- (void)setUpForSegmentColor:(UIColor *)segmentColor
titleColor:(UIColor *)titleColor
selectedTitleColor:(UIColor *)selectedTitleColor
font:(UIFont *)font
cornerRadius:(CGFloat)cornerRadius ;
@end
| Java |
<?php declare(strict_types=1);
namespace Y0lk\SQLDumper;
use ArrayObject;
use PDO;
use InvalidArgumentException;
/**
* A TableDumperCollection is used to group TableDumper objects together, allowing you to specify dump options on multiple table at once.
* All TableDumper methods can be called directly on a TableDumperCollection, and will be executed on all the TableDumper instances in that collection.
*
* @author Gabriel Jean <gabriel@inkrebit.com>
*/
class TableDumperCollection extends ArrayObject
{
/**
* {@inheritDoc}
*/
public function append($value): void
{
//Make sure we're adding a TableDumper object
if (!($value instanceof TableDumper)) {
throw new InvalidArgumentException("TableDumperCollection only accepts TableDumper objects", 1);
}
//Append with table_name as key
$this->offsetSet($value->getTable()->getName(), $value);
}
/**
* {@inheritDoc}
*/
public function offsetSet($index, $newval): void
{
//Make sure we're adding a TableDumper object
if (!($newval instanceof TableDumper)) {
throw new InvalidArgumentException("TableDumperCollection only accepts TableDumper objects", 1);
}
//Append with table_name as key
parent::offsetSet($newval->getTable()->getName(), $newval);
}
/**
* @param Table|string $table Adds a table, either by name, or by Table instance, to the collection
*
* @return TableDumper Returns a TableDumper of the table that was just added
*/
public function addTable($table): TableDumper
{
if ($table instanceof Table) {
$tableName = $table->getName();
} else {
$tableName = $table;
$table = new Table($tableName);
}
//First check if a dumper already exists for this table
if (!$this->offsetExists($tableName)) {
//Create new one
$this->offsetSet($tableName, new TableDumper($table));
}
return $this->offsetGet($tableName);
}
/**
* @param TableDumperCollection|array<TableDumper|Table|string> $listTables Adds a list of tables, either by passing TableDumperCollection, or an array containing either TableDumper objects, Table objects or table naes
*
* @return TableDumperCollection Returns a TableDumperCollection of the list of tables that was just added
*/
public function addListTables($listTables): TableDumperCollection
{
//If arg is a TableDumperCollection, merge into this one
if ($listTables instanceof TableDumperCollection) {
foreach ($listTables as $table) {
$this->append($table);
}
return $listTables;
} else {
return $this->addListTableArray($listTables);
}
}
/**
* Adds a list of tables passed as an array
* @param array $listTables Array of tables to add
*
* @return TableDumperCollection Returns a TableDumperCollection of the list of tables that was just added
*/
protected function addListTableArray(array $listTables): TableDumperCollection
{
//Create TableDumperCollection
$listDumpers = new TableDumperCollection;
foreach ($listTables as $table) {
//If table is already a Dumper, simply append to this
if ($table instanceof TableDumper) {
$listDumpers[] = $table;
$this->append($table);
} else {
$listDumpers[] = $this->addTable($table);
}
}
return $listDumpers;
}
/**
* Writes all DROP statements to the dump stream
*
* @param resource $stream Stream to write the dump to
*
* @return void
*/
public function dumpDropStatements($stream): void
{
foreach ($this as $dumper) {
if ($dumper->hasDrop()) {
$dumper->dumpDropStatement($stream);
}
}
}
/**
* Writes all INSERT statements to the dump stream
*
* @param PDO $db PDO instance to use for DB queries
* @param resource $stream Stream to write the dump to
*
* @return void
*/
public function dumpInsertStatements(PDO $db, $stream): void
{
foreach ($this as $dumper) {
if ($dumper->hasData()) {
$dumper->dumpInsertStatement($db, $stream);
}
}
}
/**
* Writes all the SQL statements of this dumper to the dump stream
*
* @param PDO $db PDO instance to use for DB queries
* @param resource $stream Stream to write the dump to
* @param boolean $groupDrops Determines if DROP statements will be grouped
* @param boolean $groupInserts Determines if INSERT statements will be grouped
*
* @return void
*/
public function dump(PDO $db, $stream, bool $groupDrops = false, bool $groupInserts = false): void
{
if ($groupDrops) {
$this->dumpDropStatements($stream);
}
foreach ($this as $dumper) {
if (!$groupDrops) {
$dumper->dumpDropStatement($stream);
}
$dumper->dumpCreateStatement($db, $stream);
if (!$groupInserts) {
$dumper->dumpInsertStatement($db, $stream);
}
}
if ($groupInserts) {
$this->dumpInsertStatements($db, $stream);
}
}
public function __call(string $name, array $arguments)
{
//Call methods on TableDumper values
foreach ($this as $value) {
call_user_func_array([$value, $name], $arguments);
}
return $this;
}
} | Java |
<?php
namespace modules\admin\controllers;
use vendor\Controller;
class Option extends Controller
{
public function index()
{
echo $this->render('module.admin@views/option.php', ['mainTitle' => '站点设置']);
}
} | Java |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.resources.implementation;
import com.microsoft.azure.management.resources.ResourceGroupProperties;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Resource group information.
*/
public class ResourceGroupInner {
/**
* The ID of the resource group.
*/
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String id;
/**
* The name of the resource group.
*/
private String name;
/**
* The properties property.
*/
private ResourceGroupProperties properties;
/**
* The location of the resource group. It cannot be changed after the
* resource group has been created. It muct be one of the supported Azure
* locations.
*/
@JsonProperty(required = true)
private String location;
/**
* The ID of the resource that manages this resource group.
*/
private String managedBy;
/**
* The tags attached to the resource group.
*/
private Map<String, String> tags;
/**
* Get the id value.
*
* @return the id value
*/
public String id() {
return this.id;
}
/**
* Get the name value.
*
* @return the name value
*/
public String name() {
return this.name;
}
/**
* Set the name value.
*
* @param name the name value to set
* @return the ResourceGroupInner object itself.
*/
public ResourceGroupInner withName(String name) {
this.name = name;
return this;
}
/**
* Get the properties value.
*
* @return the properties value
*/
public ResourceGroupProperties properties() {
return this.properties;
}
/**
* Set the properties value.
*
* @param properties the properties value to set
* @return the ResourceGroupInner object itself.
*/
public ResourceGroupInner withProperties(ResourceGroupProperties properties) {
this.properties = properties;
return this;
}
/**
* Get the location value.
*
* @return the location value
*/
public String location() {
return this.location;
}
/**
* Set the location value.
*
* @param location the location value to set
* @return the ResourceGroupInner object itself.
*/
public ResourceGroupInner withLocation(String location) {
this.location = location;
return this;
}
/**
* Get the managedBy value.
*
* @return the managedBy value
*/
public String managedBy() {
return this.managedBy;
}
/**
* Set the managedBy value.
*
* @param managedBy the managedBy value to set
* @return the ResourceGroupInner object itself.
*/
public ResourceGroupInner withManagedBy(String managedBy) {
this.managedBy = managedBy;
return this;
}
/**
* Get the tags value.
*
* @return the tags value
*/
public Map<String, String> tags() {
return this.tags;
}
/**
* Set the tags value.
*
* @param tags the tags value to set
* @return the ResourceGroupInner object itself.
*/
public ResourceGroupInner withTags(Map<String, String> tags) {
this.tags = tags;
return this;
}
}
| Java |
#include <net/http/CServer.hpp>
namespace net { namespace http
{
CServer::CServer(void) : net::CServer(net::EProtocol::TCP)
{
}
}}
| Java |
require "spec_helper"
require "tidy_i18n/duplicate_keys"
describe "Finding duplicate translations" do
def locale_file_paths(file_names)
file_names.collect do |path|
File.expand_path(File.join(File.dirname(__FILE__), "fixtures", path))
end
end
it "finds duplicate keys when the locale only has one file" do
duplicate_keys = TidyI18n::DuplicateKeys.new("en", locale_file_paths(["en_with_duplicate_keys.yml"]))
expect(duplicate_keys.locale).to eq("en")
expect(duplicate_keys.all.size).to eq(2)
first_key = duplicate_keys.all.first
expect(first_key.name).to eq("a.b")
expect(first_key.values).to eq(["b1", "b2"])
second_key = duplicate_keys.all[1]
expect(second_key.name).to eq("d.f")
expect(second_key.values).to eq(["f1", "f2"])
end
it "finds duplicate keys when the locale is split has multiple files" do
file_paths = locale_file_paths(["en_with_duplicate_keys.yml", "en_with_more_duplicates.yml"])
duplicate_keys = TidyI18n::DuplicateKeys.new("en", file_paths)
expect(duplicate_keys.locale).to eq("en")
duplicate_key_names = duplicate_keys.all.map(&:name)
expect(duplicate_key_names).to contain_exactly("a.b", "d.f", "c", "d.e")
end
end
| Java |
//
// partial2js
// Copyright (c) 2014 Dennis Sänger
// Licensed under the MIT
// http://opensource.org/licenses/MIT
//
"use strict";
var glob = require('glob-all');
var fs = require('fs');
var path = require('path');
var stream = require('stream');
var htmlmin = require('html-minifier').minify;
var escape = require('js-string-escape');
var eol = require('os').EOL;
function Partial2Js( opts ) {
opts = opts || {};
var self = this;
this.debug = !!opts.debug;
this.patterns = [];
this.files = [];
this.contents = {};
this.uniqueFn = function( file ) {
return file;
};
var log = (function log() {
if ( this.debug ) {
console.log.apply( console, arguments );
}
}).bind( this );
var find = (function() {
this.files = glob.sync( this.patterns.slice( 0 )) || [];
}).bind( this );
function cleanPatterns( patterns ) {
return patterns.map(function( entry ) {
return entry.replace(/\/\*+/g, '');
});
}
function compare( patterns, a, b ) {
return matchInPattern( patterns, a ) - matchInPattern( patterns, b );
}
var sort = (function() {
var clean = cleanPatterns( this.patterns );
this.files.sort(function( a, b ) {
return compare( clean, a, b );
});
}).bind( this );
//
// this function is not every functional ;)
// Should use findIndex() [ES6] as soon as possible
//
function matchInPattern( patterns, entry ) {
var res = patterns.length + 100;
patterns.every(function( pattern, index ) {
if ( entry.indexOf( pattern ) > -1 ) {
res = index;
return false;
}
return true;
});
return res;
}
var unique = (function() {
if ( typeof this.uniqueFn === 'function' && this.files && this.files.length ) {
var obj = {};
this.files.forEach(function( file ) {
var key = self.uniqueFn( file );
if ( !obj[key] ) {
obj[key] = file;
}
});
this.files = obj;
}
}).bind( this );
var asString = (function( moduleName ) {
var buffer = '';
buffer += '(function(window,document){' + eol;
buffer += '"use strict";' + eol;
buffer += 'angular.module("'+moduleName+'",[]).run(["$templateCache",function($templateCache){' + eol;
for ( var k in this.contents ) {
buffer += ' $templateCache.put("'+k+'","'+this.contents[k]+'");' + eol;
}
buffer += '}]);' + eol;
buffer += '})(window,document);';
return buffer;
}).bind( this );
var read = (function() {
var id, path, stat;
this.contents = {};
for( var k in this.files ) {
id = k;
path = this.files[k];
stat = fs.statSync( path );
if ( stat.isFile()) {
log('read file:', path, '=>', id );
this.contents[id] = fs.readFileSync( path );
}
}
return this.contents;
}).bind( this );
var asStream = function( string ) {
var s = new stream.Readable();
s._read = function noop() {};
s.push( string );
s.push(null);
return s;
};
var minify = (function() {
var opts = {
collapseWhitespace: true,
preserveLineBreaks: false,
removeComments: true,
removeRedundantAttributes: true,
removeEmptyAttributes: false,
keepClosingSlash: true,
maxLineLength: 0,
customAttrCollapse: /.+/,
html5: true
};
for ( var k in this.contents ) {
this.contents[k] = escape(htmlmin( String(this.contents[k]), opts ));
}
}).bind( this );
this.add = function( pattern ) {
this.patterns.push( pattern );
return this;
};
this.not = function( pattern ) {
this.patterns.push( '!'+pattern );
return this;
};
this.folder = function( folder ) {
if ( folder && String( folder ) === folder ) {
folder = path.resolve( folder ) + '/**/*';
this.patterns.push( folder );
}
return this;
};
this.unique = function( fn ) {
this.uniqueFn = fn;
return this;
};
this.stringify = function( moduleName ) {
find();
sort();
unique();
read();
minify();
return asString( moduleName );
};
this.stream = function( moduleName ) {
return asStream( this.stringify( moduleName ) );
};
}
module.exports = function( opts ) {
return new Partial2Js( opts );
};
| Java |
---
layout: post
title: Creating a gem with bundler
date: 2013-11-26 10:48:31
disqus: n
---
A trick I am learning since 2 years ago : splitting up even more of the main code base into smaller parts. The ideas behind this are numerous : from speeding up tests to keeping things simple.
Defining sub parts of the product as gems allows to enforce stricter rules on the APIs changes, keep each test suite small and independent and stick to principles and rules dear to OO programmers and OO designers.
And in the same manner rather than using Rspec and tons of gems to test drive the development of each gem I rely on something that’s already coming with Ruby : Minitest.
## A great companion for the journey
After a quick search I found a great Minitest quick reference from Matt Sears (http://mattsears.com/articles/2011/12/10/minitest-quick-reference). It has been very helpful to jump on the minitest train with my Rspec habits. I only had to look for something else when I started to mock objects and messages.
## Starting a gem
Bundler has the great taste to come with a way to create a gem skeleton : ```bundle gem```.
And if you ask bundle a bit of details about that ```gem``` command :
```
bundle help gem
Usage:
bundle gem GEM
Options:
-b, [--bin=Generate a binary for your library.]
-t, [--test=Generate a test directory for your library: 'rspec' is the default, but 'minitest' is also supported.]
-e, [--edit=/path/to/your/editor] # Open generated gemspec in the specified editor (defaults to $EDITOR or $BUNDLER_EDITOR)
[--no-color=Disable colorization in output]
-V, [--verbose=Enable verbose output mode]
Creates a skeleton for creating a rubygem
```
Let’s run it :
```
$ bundle gem foo -t minitest
create foo/Gemfile
create foo/Rakefile
create foo/LICENSE.txt
create foo/README.md
create foo/.gitignore
create foo/foo.gemspec
create foo/lib/foo.rb
create foo/lib/foo/version.rb
create foo/test/minitest_helper.rb
create foo/test/test_foo.rb
create foo/.travis.yml
Initializating git repo in /Users/ange/Code/gems/test/foo
```
The command creates a *foo* directory and create everything you need to start working on a new gem :
* a *Gemfile* (yet it’s mostly empty)
* a *Rakefile*
* a *LICENSE* (MIT license, by default it considers you are going open source)
* a basic *README* with minimal sections
* a *.gitignore* file already filed with usual files and paths
* a *foo.gemspec* file that contains the description of your gem, the gem development and running dependencies and your contact informations
* then there is the initial, almost empty, files for your gem placed and named following the classic practices of the Ruby community, including *minitest* base setup.
* as a bonus there is a minimal *.travis.yml* config file so you can push your code to a public repository on github and get the tests runnings right away !
## Gemspec
Contrary to a Ruby application (such as a Sinatra or Rails app) you don’t define your gem dependencies in a Gemfile. You define them in the gem spec file :
```
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'foo/version'
Gem::Specification.new do |spec|
spec.name = "foo"
spec.version = Foo::VERSION
spec.authors = ["Thomas Riboulet"]
spec.email = ["riboulet+gem@som.thing”]
spec.description = %q{TODO: Write a gem description}
spec.summary = %q{TODO: Write a gem summary}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "minitest"
spec.add_dependency “faraday”
end
```
This gemspec is the one generated by bundler. We can see that it includes the gem name, the version (using the Foo::VERSION constant inherited from the ```require ‘foo/version’``` line. It also includes my name, email, the description and summary of the gem, a homepage and license.
Bundler will use git tricks to list the files, and some ruby tricks to list executables and test files.
The dependencies come last with first the development dependencies and then the dependencies. The first ones will be needed to develop, the later just to use the gem.
## Minitest
Now I do like to have a default test setup ready but this one lacks colours and readability to my taste.
I did not know about the -t flag until I did some research for this post. I was happy to see it in but I do prefer my setup and way :
```
# test helper
require 'minitest/autorun'
require 'minitest/pride'
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'foo'
```
Pride will add a bit of colours to the output. (Look around there is also a way to have a nyan cat running across the screen).
The Rake file is ok but here is an alternative one :
```
# Rakefile
require "bundler/gem_tasks"
desc "Run all tests"
task :test do
Dir.glob('./test/**/test_*.rb').each { |file| require file }
end
task :default => :test
```
It’s a bit simpler to read and there is less libs required. It’s using a very simple mechanism to run all tests : *Dir.glob* call on the test directory plus a *require* for each test file.
## Test file template
As you can see from the previous Rakefile and the initial run of bundler the naming rule for minitest test files is to *prefix* the name of the tested class with *test_*.
I am not going to give a crash course on Minitest : all you have to know is described in the **excellent** article from Matt Sears.
What I can show you is a basic template.
```
require_relative ‘../../minitest_helper'
describe Foo do
describe "setup" do
it “should respond to setup” do
subject.must_respond_to(:setup)
end
end
end
```
The first line might look odd to some : I usually keep the Rails’ habit to sort my tests the same way the tested classes are. It keeps thing a bit nittier all around.
```
Foo/
lib/
foo.rb
foo/
sub_foo.rb
test/
minitest_helper.rb
lib/
test_foo.rb
foo/
test_sub_foo.rb
```
That’s why the require relative is a playing with paths.
## Other gems I use with Minitest
### VCR
For those who don’t know VCR it’s a nifty tool that allows you to record http transactions with external services and replay them. It allows you to speed up test and also to avoid calling 100 times a minute a remote service. Bonus point : you can work offline if you have a set of recordings.
VCR uses *cassettes* to record and replay. Cassettes are YAML files that you can edit yourself if you ever want to. There is a simple setup to do in your test helper :
```
VCR.configure do |c|
c.default_cassette_options = { :record => :new_episodes }
c.cassette_library_dir = 'test/vcr/cassettes'
c.hook_into :faraday
end
```
You can setup default cassette options such as the preference to record (never, every time, once, …), where to store the cassettes and what library to use to pass the http calls and replay them.
For the options the simple way is to request *new_episodes*. That will record new requests and store them to be replayed when they are requested again. It’s what you would usually want.
For the cassette dir, again I like my directories organised so I put all the vcr stuff inside the test directory.
For the library I usually go for Faraday. It’s the http lib I use most of the time now : it’s simple, allows for some clean code and fast tricks while doing the job properly. It’s also pretty simple to configure.
Back to the test template : the before and after blocks setup and cleanup the VCR run. ```VCR.insert_cassette __name__``` will create a cassette named after the current test file and tell VCR to write to it.
```VCR.eject_cassette``` does what you might imagine : close the file to avoid further writes.
```
before do
VCR.insert_cassette __name__
end
after do
VCR.eject_cassette
end
```
The problem with VCR is that once it’s setup all your http calls will go through it and it’s a bit tedious to setup paths around it to avoid that.
> An alternative to using record and replay tools such as VCR is to use tools such as Artifice (https://github.com/wycats/artifice).
> Artifice allows you to mock remote service replies by plugging http calls to mini Rack apps.
> It’s a bit more difficult to setup and maintain than VCR but it’s way faster and if you have a proper documentation of the remote API or recordings of how it’s behaving it can be a nicer solution.
### Faker
Faker is another really handy tool : it allows you to generate realistic data for you model attributes. Names, email addresses, phone numbers, domain names, … It’s a handy companion for people writing tests everyday.
### Fake-redis
I often use redis for all sort of things in my applications and gems. Fake redis is a memory only, super fast implementation of Redis. It will save you time and make tests faster.
### Mocha
If Minitest is not enough Mocha can bring a bit more bang to it, it’s also easy to use and will ease your path to mocks.
## Packaging up the gem
Once it’s ready you can build the gem using ```gem build```. Then you can push to Rubygems, if it’s to be open source that it is.
Create an account on Rubygems.org if it’s not the case yet and check the documentation over there. Once it’s done you can ```gem push foo-0.0.1.gem``` to get your gem out there.
## Using your gems privately
There is commercial private gem servers as a service such as Gemfury (http://www.gemfury.com) but you can use private git repositories to store your private gems too.
## The point
I hope that this article has shown you how easy it has become to create a gem with tests. I am quite sad I did not know about these steps few years ago, it would have made it easier for me to keep my projects tighter and cleaner.
### Thanks
Big thanks to @joelazemar for his advices when I was searching around and learning about gem making.
Big thanks to Matt Sears for his great article about Minitest.
Big thanks to Claudio Ortolina for his brilliant piece (http://net.tutsplus.com/tutorials/ruby/gem-creation-with-bundler/) that served as inspiration for this article. If you need more details go check it out. The present article is intended to be a quick read to give you the minimal things you need to get going but Claudio’s has lot of details.
And a huge thank you to the Bundler team for the tool and commands it brings.
| Java |
<?php
/* Cachekey: cache/stash_default/doctrine/doctrinenamespacecachekey[dc2_b1b70927f4ac11a36c774dc0f41356a4_]/ */
/* Type: array */
$loaded = true;
$expiration = 1425255999;
$data = array();
/* Child Type: integer */
$data['return'] = 1;
/* Child Type: integer */
$data['createdOn'] = 1424843731;
| Java |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blocks & Guidelines</title>
<link rel="stylesheet" type="text/css" href="./css/ui.css">
<script src='https://code.jquery.com/jquery-2.1.3.min.js' type='application/javascript'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/ace/1.1.8/ace.js' type='application/javascript'></script>
<script src='./js/blocks.and.guidelines.js' type='application/javascript'></script>
<script src='./js/rapheal-min.js' type='application/javascript'></script>
<script src='./js/util.js' type='application/javascript'></script>
<script src='./js/ui.js' type='application/javascript'></script>
</head>
<body id='body'>
<!-- <div id='canvas'></div> -->
<div id='rendering-context'></div>
<div id='documents'>
<div class='addlevel'>+</div>
<h3>Diagrams</h3>
<span class='button' id='Import'><input type="file" id="input"></span><p></p>
<span class='button' id='Export'><a href='' target="_blank">Export</a></span>
<span class='button' id='Delete'>Delete</span>
<div id='scroller'>
<ul id="saves"></ul>
</div>
</div>
</body>
</html>
| Java |
<?php
class AsuransiForm extends CFormModel
{
public $stringNIM;
public $arrayNIM;
public function rules()
{
return array(
array('stringNIM', 'required'),
);
}
public function attributeLabels()
{
return array(
'stringNIM' => Yii::t('app','NIM'),
);
}
protected function beforeValidate()
{
preg_match_all('([0-9]+)',$this->stringNIM,$nims);
$this->arrayNIM = $nims[0];
return parent::beforeValidate();
}
public function preview()
{
$criteria = new CDbCriteria;
$criteria->addInCondition('nim',$this->arrayNIM);
return new CActiveDataProvider('Mahasiswa', array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>50
),
));
}
public function lunasi()
{
$criteria = new CDbCriteria;
$criteria->addInCondition('nim',$this->arrayNIM);
foreach(Mahasiswa::model()->findAll($criteria) as $mahasiswa) {
$mahasiswa->lunasiAsuransi();
}
}
}
| Java |
# The MIT License (MIT)
Copyright (c) 2017 Eric Scuccimarra <skooch@gmail.com>
> 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.
| Java |
function main()
while true do
print('Hello')
end
end
live.patch('main', main)
live.start(main)
| Java |
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#nullable disable
namespace StyleCop.Analyzers.OrderingRules
{
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using StyleCop.Analyzers.Helpers;
using StyleCop.Analyzers.Settings.ObjectModel;
/// <summary>
/// A constant field is placed beneath a non-constant field.
/// </summary>
/// <remarks>
/// <para>A violation of this rule occurs when a constant field is placed beneath a non-constant field. Constants
/// should be placed above fields to indicate that the two are fundamentally different types of elements with
/// different considerations for the compiler, different naming requirements, etc.</para>
/// </remarks>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class SA1203ConstantsMustAppearBeforeFields : DiagnosticAnalyzer
{
/// <summary>
/// The ID for diagnostics produced by the <see cref="SA1203ConstantsMustAppearBeforeFields"/> analyzer.
/// </summary>
public const string DiagnosticId = "SA1203";
private const string HelpLink = "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1203.md";
private static readonly LocalizableString Title = new LocalizableResourceString(nameof(OrderingResources.SA1203Title), OrderingResources.ResourceManager, typeof(OrderingResources));
private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(OrderingResources.SA1203MessageFormat), OrderingResources.ResourceManager, typeof(OrderingResources));
private static readonly LocalizableString Description = new LocalizableResourceString(nameof(OrderingResources.SA1203Description), OrderingResources.ResourceManager, typeof(OrderingResources));
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, AnalyzerCategory.OrderingRules, DiagnosticSeverity.Warning, AnalyzerConstants.EnabledByDefault, Description, HelpLink);
private static readonly ImmutableArray<SyntaxKind> TypeDeclarationKinds =
ImmutableArray.Create(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration);
private static readonly Action<SyntaxNodeAnalysisContext, StyleCopSettings> TypeDeclarationAction = HandleTypeDeclaration;
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
ImmutableArray.Create(Descriptor);
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterSyntaxNodeAction(TypeDeclarationAction, TypeDeclarationKinds);
}
private static void HandleTypeDeclaration(SyntaxNodeAnalysisContext context, StyleCopSettings settings)
{
var elementOrder = settings.OrderingRules.ElementOrder;
int constantIndex = elementOrder.IndexOf(OrderingTrait.Constant);
if (constantIndex < 0)
{
return;
}
var typeDeclaration = (TypeDeclarationSyntax)context.Node;
var members = typeDeclaration.Members;
var previousFieldConstant = true;
var previousFieldStatic = false;
var previousFieldReadonly = false;
var previousAccessLevel = AccessLevel.NotSpecified;
foreach (var member in members)
{
if (!(member is FieldDeclarationSyntax field))
{
continue;
}
AccessLevel currentAccessLevel = MemberOrderHelper.GetAccessLevelForOrdering(field, field.Modifiers);
bool currentFieldConstant = field.Modifiers.Any(SyntaxKind.ConstKeyword);
bool currentFieldReadonly = currentFieldConstant || field.Modifiers.Any(SyntaxKind.ReadOnlyKeyword);
bool currentFieldStatic = currentFieldConstant || field.Modifiers.Any(SyntaxKind.StaticKeyword);
bool compareConst = true;
for (int j = 0; compareConst && j < constantIndex; j++)
{
switch (elementOrder[j])
{
case OrderingTrait.Accessibility:
if (currentAccessLevel != previousAccessLevel)
{
compareConst = false;
}
continue;
case OrderingTrait.Readonly:
if (currentFieldReadonly != previousFieldReadonly)
{
compareConst = false;
}
continue;
case OrderingTrait.Static:
if (currentFieldStatic != previousFieldStatic)
{
compareConst = false;
}
continue;
case OrderingTrait.Kind:
// Only fields may be marked const, and all fields have the same kind.
continue;
case OrderingTrait.Constant:
default:
continue;
}
}
if (compareConst)
{
if (!previousFieldConstant && currentFieldConstant)
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, NamedTypeHelpers.GetNameOrIdentifierLocation(member)));
}
}
previousFieldConstant = currentFieldConstant;
previousFieldReadonly = currentFieldReadonly;
previousFieldStatic = currentFieldStatic;
previousAccessLevel = currentAccessLevel;
}
}
}
}
| Java |
//
// Created by Kévin POLOSSAT on 14/01/2018.
//
#ifndef LW_TCP_SERVER_SOCKET_H
#define LW_TCP_SERVER_SOCKET_H
#include <memory>
#include <type_traits>
#include "Socket.h"
#include "Reactor.h"
#include "Buffer.h"
#include "Operation.h"
#include "SSLSocket.h"
namespace lw_network {
template<typename Sock = Socket>
class ReactiveSocketBase : public Sock {
static_assert(std::is_base_of<Socket, Sock>::value, "Socket base should be a derived class of Socket");
public:
explicit ReactiveSocketBase(Reactor &reactor) : Sock(), reactor_(reactor) { register_(); }
ReactiveSocketBase(Reactor &reactor, Sock socket): Sock(socket), reactor_(reactor) { register_(); }
~ReactiveSocketBase() = default;
ReactiveSocketBase(ReactiveSocketBase const &other) = default;
ReactiveSocketBase(ReactiveSocketBase &&other) = default;
ReactiveSocketBase &operator=(ReactiveSocketBase const &other) {
Sock::operator=(other);
return *this;
}
ReactiveSocketBase &operator=(ReactiveSocketBase &&other) {
Sock::operator=(other);
return *this;
}
void close() {
reactor_.unregisterHandler(this->getImpl(), lw_network::Reactor::read);
reactor_.unregisterHandler(this->getImpl(), lw_network::Reactor::write);
error_code ec = no_error;
Sock::close(ec);
}
void async_read_some(Buffer b, std::function<void(std::size_t nbyte, error_code ec)> completionHandler);
void async_read(Buffer b, std::function<void(std::size_t nbyte, error_code ec)> completionHandler);
void async_write_some(Buffer b, std::function<void(std::size_t nbyte, error_code ec)> completionHandler);
void async_write(Buffer b, std::function<void(std::size_t nbyte, error_code ec)> completionHandler);
private:
Reactor &reactor_;
private:
void register_() {
reactor_.registerHandler(this->getImpl(), lw_network::Reactor::read);
reactor_.registerHandler(this->getImpl(), lw_network::Reactor::write);
}
};
using ReactiveSocket = ReactiveSocketBase<>;
using SSLReactiveSocket = ReactiveSocketBase<SSLSocket>;
// TODO FACTORIZE
template<typename T>
class ReadOperation : public Operation {
public:
ReadOperation(
ReactiveSocketBase<T> &s,
Buffer b,
std::function<void(std::size_t nbyte, error_code ec)> completionHandler):
s_(s), ec_(no_error), nbyte_(0), b_(std::move(b)), completionHandler_(std::move(completionHandler)) {}
bool handle() {
nbyte_ = s_.recv(b_, 0, ec_);
return b_.exhausted();
}
void complete() {
completionHandler_(nbyte_, ec_);
}
private:
ReactiveSocketBase<T> &s_;
error_code ec_;
std::size_t nbyte_;
Buffer b_;
std::function<void(std::size_t nbyte, error_code ec)> completionHandler_;
};
template<typename T>
class WriteOperation : public Operation {
public:
WriteOperation(
lw_network::ReactiveSocketBase<T> &s,
lw_network::Buffer b,
std::function<void(size_t, lw_network::error_code)> completionHandler):
s_(s), ec_(no_error), nbyte_(0), b_(std::move(b)), completionHandler_(std::move(completionHandler)) {}
bool handle() {
nbyte_ = s_.send(b_, 0, ec_);
return b_.exhausted();
}
void complete() {
completionHandler_(nbyte_, ec_);
}
private:
ReactiveSocketBase<T> &s_;
error_code ec_;
std::size_t nbyte_;
Buffer b_;
std::function<void(std::size_t nbyte, error_code ec)> completionHandler_;
};
template<typename T>
class ReadSomeOperation : public Operation {
public:
ReadSomeOperation(
lw_network::ReactiveSocketBase<T> &s,
lw_network::Buffer b,
std::function<void(size_t, lw_network::error_code)> completionHandler):
s_(s), ec_(no_error), nbyte_(0), b_(std::move(b)), completionHandler_(std::move(completionHandler)) {
}
bool handle() {
nbyte_ = s_.recv(b_, 0, ec_);
return true;
}
void complete() {
completionHandler_(nbyte_, ec_);
}
private:
ReactiveSocketBase<T> &s_;
error_code ec_;
std::size_t nbyte_;
Buffer b_;
std::function<void(std::size_t nbyte, error_code ec)> completionHandler_;
};
template<typename T>
class WriteSomeOperation : public Operation {
public:
WriteSomeOperation(
lw_network::ReactiveSocketBase<T> &s,
lw_network::Buffer b,
std::function<void(size_t, lw_network::error_code)> completionHandler):
s_(s), ec_(no_error), nbyte_(0), b_(std::move(b)), completionHandler_(std::move(completionHandler)) {}
bool handle() {
nbyte_ = s_.send(b_, 0, ec_);
return true;
}
void complete() {
completionHandler_(nbyte_, ec_);
}
private:
ReactiveSocketBase<T> &s_;
error_code ec_;
std::size_t nbyte_;
Buffer b_;
std::function<void(std::size_t nbyte, error_code ec)> completionHandler_;
};
}
#include "ReactiveSocketBase.icc"
#endif //LW_TCP_SERVER_SOCKET_H
| Java |
var testLogin = function(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
alert("username="+username+" , password="+password);
}
window.onload = function (){
}
| Java |
from __future__ import absolute_import, division, print_function, unicode_literals
# Statsd client. Loosely based on the version by Steve Ivy <steveivy@gmail.com>
import logging
import random
import socket
import time
from contextlib import contextmanager
log = logging.getLogger(__name__)
class StatsD(object):
def __init__(self, host='localhost', port=8125, enabled=True, prefix=''):
self.addr = None
self.enabled = enabled
if enabled:
self.set_address(host, port)
self.prefix = prefix
self.udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def set_address(self, host, port=8125):
try:
self.addr = (socket.gethostbyname(host), port)
except socket.gaierror:
self.addr = None
self.enabled = False
@contextmanager
def timed(self, stat, sample_rate=1):
log.debug('Entering timed context for %r' % (stat,))
start = time.time()
yield
duration = int((time.time() - start) * 1000)
log.debug('Exiting timed context for %r' % (stat,))
self.timing(stat, duration, sample_rate)
def timing(self, stats, time, sample_rate=1):
"""
Log timing information
"""
unit = 'ms'
log.debug('%r took %s %s' % (stats, time, unit))
self.update_stats(stats, "%s|%s" % (time, unit), sample_rate)
def increment(self, stats, sample_rate=1):
"""
Increments one or more stats counters
"""
self.update_stats(stats, 1, sample_rate)
def decrement(self, stats, sample_rate=1):
"""
Decrements one or more stats counters
"""
self.update_stats(stats, -1, sample_rate)
def update_stats(self, stats, delta=1, sampleRate=1):
"""
Updates one or more stats counters by arbitrary amounts
"""
if not self.enabled or self.addr is None:
return
if type(stats) is not list:
stats = [stats]
data = {}
for stat in stats:
data["%s%s" % (self.prefix, stat)] = "%s|c" % delta
self.send(data, sampleRate)
def send(self, data, sample_rate):
sampled_data = {}
if sample_rate < 1:
if random.random() <= sample_rate:
for stat, value in data.items():
sampled_data[stat] = "%s|@%s" % (value, sample_rate)
else:
sampled_data = data
try:
for stat, value in sampled_data.items():
self.udp_sock.sendto("%s:%s" % (stat, value), self.addr)
except Exception as e:
log.exception('Failed to send data to the server: %r', e)
if __name__ == '__main__':
sd = StatsD()
for i in range(1, 100):
sd.increment('test')
| Java |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Profiler.cs" company="Kephas Software SRL">
// Copyright (c) Kephas Software SRL. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
// Provides operations for profiling the code.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Diagnostics
{
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Kephas.Logging;
using Kephas.Operations;
using Kephas.Threading.Tasks;
/// <summary>
/// Provides operations for profiling the code.
/// </summary>
public static class Profiler
{
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Warning"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult WithWarningStopwatch(
this Action action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Warning, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Warning"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult<T> WithWarningStopwatch<T>(
this Func<T> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Warning, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Info"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult WithInfoStopwatch(
this Action action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Info, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Info"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult<T> WithInfoStopwatch<T>(
this Func<T> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Info, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Debug"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult WithDebugStopwatch(
this Action action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Debug, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Debug"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult<T> WithDebugStopwatch<T>(
this Func<T> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Debug, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Trace"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult WithTraceStopwatch(
this Action action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Trace, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Trace"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult<T> WithTraceStopwatch<T>(
this Func<T> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Trace, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at the indicated log level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="logLevel">The log level.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult WithStopwatch(
this Action action,
ILogger? logger = null,
LogLevel logLevel = LogLevel.Debug,
[CallerMemberName] string? memberName = null)
{
var result = new OperationResult();
if (action == null)
{
return result.MergeMessage($"No action provided for {memberName}.");
}
result.MergeMessage($"{memberName}. Started at: {DateTime.Now:s}.");
logger?.Log(logLevel, "{operation}. Started at: {startedAt:s}.", memberName, DateTime.Now);
var stopwatch = new Stopwatch();
stopwatch.Start();
action();
stopwatch.Stop();
result
.MergeMessage($"{memberName}. Ended at: {DateTime.Now:s}. Elapsed: {stopwatch.Elapsed:c}.")
.Complete(stopwatch.Elapsed);
logger?.Log(logLevel, "{operation}. Ended at: {endedAt:s}. Elapsed: {elapsed:c}.", memberName, DateTime.Now, stopwatch.Elapsed);
return result;
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at the indicated
/// log level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">Optional. The logger.</param>
/// <param name="logLevel">Optional. The log level.</param>
/// <param name="memberName">Optional. Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult<T> WithStopwatch<T>(
this Func<T> action,
ILogger? logger = null,
LogLevel logLevel = LogLevel.Debug,
[CallerMemberName] string? memberName = null)
{
var result = new OperationResult<T>();
if (action == null)
{
return result.MergeMessage($"No action provided for {memberName}.");
}
result.MergeMessage($"{memberName}. Started at: {DateTime.Now:s}.");
logger?.Log(logLevel, "{operation}. Started at: {startedAt:s}.", memberName, DateTime.Now);
var stopwatch = new Stopwatch();
stopwatch.Start();
result.Value = action();
stopwatch.Stop();
result
.MergeMessage($"{memberName}. Ended at: {DateTime.Now:s}. Elapsed: {stopwatch.Elapsed:c}.")
.Complete(stopwatch.Elapsed);
logger?.Log(logLevel, "{operation}. Ended at: {endedAt:s}. Elapsed: {elapsed:c}.", memberName, DateTime.Now, stopwatch.Elapsed);
return result;
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Warning"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult> WithWarningStopwatchAsync(
this Func<Task> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Warning, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Warning"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult<T>> WithWarningStopwatchAsync<T>(
this Func<Task<T>> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Warning, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Info"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult> WithInfoStopwatchAsync(
this Func<Task> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Info, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Info"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult<T>> WithInfoStopwatchAsync<T>(
this Func<Task<T>> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Info, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Debug"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult> WithDebugStopwatchAsync(
this Func<Task> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Debug, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Debug"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult<T>> WithDebugStopwatchAsync<T>(
this Func<Task<T>> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Debug, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Trace"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult> WithTraceStopwatchAsync(
this Func<Task> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Trace, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Trace"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult<T>> WithTraceStopwatchAsync<T>(
this Func<Task<T>> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync<T>(action, logger, LogLevel.Trace, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at the indicated log level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="logLevel">The log level.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static async Task<IOperationResult> WithStopwatchAsync(
this Func<Task> action,
ILogger? logger = null,
LogLevel logLevel = LogLevel.Debug,
[CallerMemberName] string? memberName = null)
{
var result = new OperationResult();
if (action == null)
{
return result.MergeMessage($"No action provided for {memberName}.");
}
result.MergeMessage($"{memberName}. Started at: {DateTime.Now:s}.");
logger?.Log(logLevel, "{operation}. Started at: {startedAt:s}.", memberName, DateTime.Now);
var stopwatch = new Stopwatch();
stopwatch.Start();
await action().PreserveThreadContext();
stopwatch.Stop();
result
.MergeMessage($"{memberName}. Ended at: {DateTime.Now:s}. Elapsed: {stopwatch.Elapsed:c}.")
.Complete(stopwatch.Elapsed);
logger?.Log(logLevel, "{operation}. Ended at: {endedAt:s}. Elapsed: {elapsed:c}.", memberName, DateTime.Now, stopwatch.Elapsed);
return result;
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed
/// time at the indicated log level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">Optional. The logger.</param>
/// <param name="logLevel">Optional. The log level.</param>
/// <param name="memberName">Optional. Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static async Task<IOperationResult<T>> WithStopwatchAsync<T>(
this Func<Task<T>> action,
ILogger? logger = null,
LogLevel logLevel = LogLevel.Debug,
[CallerMemberName] string? memberName = null)
{
var result = new OperationResult<T>();
if (action == null)
{
return result.MergeMessage($"No action provided for {memberName}.");
}
result.MergeMessage($"{memberName}. Started at: {DateTime.Now:s}.");
logger?.Log(logLevel, "{operation}. Started at: {startedAt:s}.", memberName, DateTime.Now);
var stopwatch = new Stopwatch();
stopwatch.Start();
result.Value = await action().PreserveThreadContext();
stopwatch.Stop();
result
.MergeMessage($"{memberName}. Ended at: {DateTime.Now:s}. Elapsed: {stopwatch.Elapsed:c}.")
.Complete(stopwatch.Elapsed);
logger?.Log(logLevel, "{operation}. Ended at: {endedAt:s}. Elapsed: {elapsed:c}.", memberName, DateTime.Now, stopwatch.Elapsed);
return result;
}
}
} | Java |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Examples
{
class Program
{
[STAThread]
static void Main(string[] args)
{
SolidEdgeFramework.Application application = null;
SolidEdgePart.PartDocument partDocument = null;
SolidEdgePart.Models models = null;
SolidEdgePart.Model model = null;
SolidEdgePart.RevolvedCutouts revolvedCutouts = null;
SolidEdgePart.RevolvedCutout revolvedCutout = null;
try
{
// See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register();
// Attempt to connect to a running instance of Solid Edge.
application = (SolidEdgeFramework.Application)Marshal.GetActiveObject("SolidEdge.Application");
partDocument = application.ActiveDocument as SolidEdgePart.PartDocument;
if (partDocument != null)
{
models = partDocument.Models;
model = models.Item(1);
revolvedCutouts = model.RevolvedCutouts;
for (int i = 1; i <= revolvedCutouts.Count; i++)
{
revolvedCutout = revolvedCutouts.Item(i);
var topCap = (SolidEdgeGeometry.Face)revolvedCutout.TopCap;
}
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex);
}
finally
{
OleMessageFilter.Unregister();
}
}
}
} | Java |
class MySessionsController < ApplicationController
prepend_before_filter :stop_tracking, :only => [:destroy]
def stop_tracking
current_user.update_attributes(:current_sign_in_ip => nil)
end
end
| Java |
using System.ComponentModel;
namespace LinqAn.Google.Metrics
{
/// <summary>
/// The total number of completions for the requested goal number.
/// </summary>
[Description("The total number of completions for the requested goal number.")]
public class Goal19Completions: Metric<int>
{
/// <summary>
/// Instantiates a <seealso cref="Goal19Completions" />.
/// </summary>
public Goal19Completions(): base("Goal 19 Completions",true,"ga:goal19Completions")
{
}
}
}
| Java |
using Silk.NET.Input;
using Silk.NET.Maths;
using Silk.NET.Windowing;
namespace WemkuhewhallYekaherehohurnije
{
class Program
{
private static IWindow _window;
private static void Main(string[] args)
{
//Create a window.
var options = WindowOptions.Default;
options = new WindowOptions
(
true,
new Vector2D<int>(50, 50),
new Vector2D<int>(1280, 720),
0.0,
0.0,
new GraphicsAPI
(
ContextAPI.OpenGL,
ContextProfile.Core,
ContextFlags.ForwardCompatible,
new APIVersion(3, 3)
),
"",
WindowState.Normal,
WindowBorder.Resizable,
false,
false,
VideoMode.Default
);
options.Size = new Vector2D<int>(800, 600);
options.Title = "LearnOpenGL with Silk.NET";
_window = Window.Create(options);
//Assign events.
_window.Load += OnLoad;
_window.Update += OnUpdate;
_window.Render += OnRender;
//Run the window.
_window.Run();
}
private static void OnLoad()
{
//Set-up input context.
IInputContext input = _window.CreateInput();
for (int i = 0; i < input.Keyboards.Count; i++)
{
input.Keyboards[i].KeyDown += KeyDown;
}
}
private static void OnRender(double obj)
{
//Here all rendering should be done.
}
private static void OnUpdate(double obj)
{
//Here all updates to the program should be done.
}
private static void KeyDown(IKeyboard arg1, Key arg2, int arg3)
{
//Check to close the window on escape.
if (arg2 == Key.Escape)
{
_window.Close();
}
}
}
} | Java |
FILE(REMOVE_RECURSE
"CMakeFiles/polynomialutils_4.dir/polynomialutils.cpp.o"
"polynomialutils_4.pdb"
"polynomialutils_4"
)
# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
INCLUDE(CMakeFiles/polynomialutils_4.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)
| Java |
---
title: Overdose Fatality Review Teams Literature Review
_template: publication
area:
- Criminal Justice System
pubtype:
- Research Report
pubstatatus: 'true'
summary: States and localities across the United States have implemented overdose fatality review teams to address the impact of the opioid crisis on their communities. Overdose fatality review teams are designed to increase cross-system collaboration among various public safety, public health, and social service agencies; identify missed opportunities and system gaps; and develop recommendations for intervention efforts in hopes of preventing future overdose deaths. However, limitations in peer-reviewed research on the effectiveness of overdose fatality review teams limit the understanding of their usefulness. This article provides a review of literature on overdose fatality review teams, including goals, recommendations, and information sharing protocols, as well as considerations from other fatality review teams.
articleLink: /articles/overdose-fatality-review-teams-literature-review
puburl: /assets/articles/Overdose Fatality Review Team Literature Review Final-210219T19112457.pdf
---
States and localities across the United States have implemented overdose fatality review teams to address the impact of the opioid crisis on their communities. Overdose fatality review teams are designed to increase cross-system collaboration among various public safety, public health, and social service agencies; identify missed opportunities and system gaps; and develop recommendations for intervention efforts in hopes of preventing future overdose deaths. However, limitations in peer-reviewed research on the effectiveness of overdose fatality review teams limit the understanding of their usefulness. This article provides a review of literature on overdose fatality review teams, including goals, recommendations, and information sharing protocols, as well as considerations from other fatality review teams. | Java |
<?php
namespace Libreame\BackendBundle\Helpers;
use Libreame\BackendBundle\Controller\AccesoController;
use Libreame\BackendBundle\Repository\ManejoDataRepository;
use Libreame\BackendBundle\Entity\LbIdiomas;
use Libreame\BackendBundle\Entity\LbUsuarios;
use Libreame\BackendBundle\Entity\LbEjemplares;
use Libreame\BackendBundle\Entity\LbSesiones;
use Libreame\BackendBundle\Entity\LbEditoriales;
use Libreame\BackendBundle\Entity\LbAutores;
/**
* Description of Feeds
*
* @author mramirez
*/
class GestionEjemplares {
/*
* feeds
* Retorna la lista de todos los ejemplares nuevos cargados en la plataforma.
* Solo a partir del ID que envía el cliente (Android), en adelante.
* Por ahora solo tendrá Ejemplares, luego se evaluará si tambien se cargan TRATOS Cerrados / Ofertas realizadas
*/
public function buscarEjemplares(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
$usuario = new LbUsuarios();
$sesion = new LbSesiones();
$ejemplares = new LbEjemplares();
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//echo "<script>alert(' buscaEjemplares :: FindAll ')</script>";
//Busca el usuario
$usuario = ManejoDataRepository::getUsuarioByEmail($psolicitud->getEmail());
//$membresia= ManejoDataRepository::getMembresiasUsuario($usuario);
//echo "<script>alert('MEM ".count($membresia)." regs ')</script>";
$grupo= ManejoDataRepository::getObjetoGruposUsuario($usuario);
$arrGru = array();
foreach ($grupo as $gru){
$arrGru[] = $gru->getIngrupo();
}
$ejemplares = ManejoDataRepository::getBuscarEjemplares($usuario, $arrGru, $psolicitud->getTextoBuscar());
//echo "Recuperó ejemplares...gestionejemplares:buscarEjemplares \n";
$respuesta->setRespuesta(AccesoController::inExitoso);
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
} else {
$respuesta->setRespuesta($respSesionVali);
$ejemplares = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
$ejemplares = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
}
}
public function recuperarFeedEjemplares(Solicitud $psolicitud)
{
/*
http://ex4read.co/services/web/img/p/1/1/11.jpg
*/
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
$usuario = new LbUsuarios();
$sesion = new LbSesiones();
//$ejemplares = new LbEjemplares();
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' recuperarFeedEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//echo "<script>alert(' recuperarFeedEjemplares :: FindAll ')</script>";
//Busca el usuario
$usuario = ManejoDataRepository::getUsuarioByEmail($psolicitud->getEmail());
//$membresia= ManejoDataRepository::getMembresiasUsuario($usuario);
//echo "<script>alert('MEM ".count($membresia)." regs ')</script>";
$grupo= ManejoDataRepository::getObjetoGruposUsuario($usuario);
$arrGru = array();
foreach ($grupo as $gru){
$arrGru[] = $gru->getIngrupo();
}
$ejemplares = ManejoDataRepository::getEjemplaresDisponibles($arrGru, $psolicitud->getUltEjemplar());
//echo "Imagen ".$ejemplares;
$respuesta->setRespuesta(AccesoController::inExitoso);
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
} else {
$respuesta->setRespuesta($respSesionVali);
$ejemplares = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
$ejemplares = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
}
}
public function publicarEjemplar(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' Publicar :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//Genera la oferta para el ejemplar si la accion es 1}
//echo "Decide accion para ejemplar : ".$psolicitud->getAccionComm();
if ($psolicitud->getAccionComm() == AccesoController::inAccPublica) {
//echo "\n La acion es publicar";
$respPub = ManejoDataRepository::generarPublicacionEjemplar($psolicitud);
$respuesta->setRespuesta($respPub);
} elseif ($psolicitud->getAccionComm() == AccesoController::inAccDespubl) {
} elseif ($psolicitud->getAccionComm() == AccesoController::inAccModific) {
} elseif ($psolicitud->getAccionComm() == AccesoController::inAccElimina) {}
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
} else {
$respuesta->setRespuesta($respSesionVali);
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
}
}
public function visualizarBiblioteca(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
$usuario = new LbUsuarios();
$sesion = new LbSesiones();
$ejemplares = new LbEjemplares();
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//echo "<script>alert(' buscaEjemplares :: FindAll ')</script>";
//Busca el usuario
$usuario = ManejoDataRepository::getUsuarioByEmail($psolicitud->getEmail());
//$membresia= ManejoDataRepository::getMembresiasUsuario($usuario);
//echo "<script>alert('MEM ".count($membresia)." regs ')</script>";
$grupo= ManejoDataRepository::getObjetoGruposUsuario($usuario);
$arrGru = array();
foreach ($grupo as $gru){
$arrGru[] = $gru->getIngrupo();
}
$ejemplares = ManejoDataRepository::getVisualizarBiblioteca($usuario, $arrGru, $psolicitud->getFiltro());
//echo "Recuperó ejemplares...gestionejemplares:buscarEjemplares \n";
$respuesta->setRespuesta(AccesoController::inExitoso);
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
} else {
$respuesta->setRespuesta($respSesionVali);
$ejemplares = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
$ejemplares = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
}
}
public function recuperarOferta(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
$usuario = new LbUsuarios();
$sesion = new LbSesiones();
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//echo "<script>alert(' recuperarFeedEjemplares :: FindAll ')</script>";
//Busca el usuario
$usuario = ManejoDataRepository::getUsuarioByEmail($psolicitud->getEmail());
//$membresia= ManejoDataRepository::getMembresiasUsuario($usuario);
//echo "<script>alert('MEM ".count($membresia)." regs ')</script>";
$oferta = ManejoDataRepository::getOfertaById($psolicitud->getIdOferta());
//echo "<script>alert('Oferta ".$psolicitud->getIdOferta()." ')</script>";
if ($oferta != NULL){
if ($oferta->getInofeactiva() == AccesoController::inExitoso){
$respuesta->setRespuesta(AccesoController::inExitoso);
} else {
$respuesta->setRespuesta(AccesoController::inMenNoAc);
}
} else {
$respuesta->setRespuesta(AccesoController::inMenNoEx);
}
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
return $objLogica::generaRespuesta($respuesta, $psolicitud, $oferta);
} else {
$respuesta->setRespuesta($respSesionVali);
$oferta = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $oferta);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
$oferta = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $oferta);
}
}
public function listarIdiomas(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
$respuesta->setRespuesta(AccesoController::inExitoso);
//echo "Respuesta Idiomas: ".$respuesta->getRespuesta()." \n";
$idiomas = ManejoDataRepository::getListaIdiomas();
$idioma = new LbIdiomas();
$arIdiomas = array();
//$contador = 0;
foreach ($idiomas as $idioma) {
$arIdiomas[] = array("ididioma"=>$idioma->getInididioma(), "nomidioma"=>utf8_encode($idioma->getTxidinombre()));
//echo "Idioma=".$idioma->getInididioma()." - ".$idioma->getTxidinombre()." \n";
//$contador++;
}
//echo "esto es lo que hay en respuesta";
//print_r($respuesta);
//echo $contador." - lugares hallados";
//$arIdiomas = array("Español","Inglés","Frances","Alemán","Ruso","Portugues",
// "Catalán","Árabe","Bosnio","Croata","Serbio","Italiano","Griego","Turco","Húngaro","Hindi");
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arIdiomas);
} else {
$respuesta->setRespuesta($respSesionVali);
$arIdiomas = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arIdiomas);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
$arIdiomas = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arIdiomas);
}
}
public function megustaEjemplar(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
$resp = ManejoDataRepository::setMegustaEjemplar($psolicitud->getIdEjemplar(), $psolicitud->getMegusta(), $psolicitud->getEmail());
$respuesta->setRespuesta($resp);
$respuesta->setCantComenta(ManejoDataRepository::getCantComment($psolicitud->getIdEjemplar()));
$respuesta->setCantMegusta(ManejoDataRepository::getCantMegusta($psolicitud->getIdEjemplar()));
//echo "esto es lo que hay en respuesta";
//print_r($respuesta);
//echo $contador." - lugares hallados";
//$arIdiomas = array("Español","Inglés","Frances","Alemán","Ruso","Portugues",
// "Catalán","Árabe","Bosnio","Croata","Serbio","Italiano","Griego","Turco","Húngaro","Hindi");
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
} else {
//echo 'sesion invalida';
$respuesta->setRespuesta($respSesionVali);
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
}
}
public function VerUsrgustaEjemplar(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
$UsrMegusta = ManejoDataRepository::getUsrMegustaEjemplar($psolicitud);
$respuesta->setRespuesta(AccesoController::inExitoso);
//echo "esto es lo que hay en respuesta";
//print_r($respuesta);
//echo $contador." - lugares hallados";
//$arIdiomas = array("Español","Inglés","Frances","Alemán","Ruso","Portugues",
// "Catalán","Árabe","Bosnio","Croata","Serbio","Italiano","Griego","Turco","Húngaro","Hindi");
return $objLogica::generaRespuesta($respuesta, $psolicitud, $UsrMegusta);
} else {
$respuesta->setRespuesta($respSesionVali);
return $objLogica::generaRespuesta($respuesta, $psolicitud, $UsrMegusta);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
return $objLogica::generaRespuesta($respuesta, $psolicitud, $UsrMegusta);
}
}
public function comentarEjemplar(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
$resp = ManejoDataRepository::setComentarioEjemplar($psolicitud);
$respuesta->setRespuesta($resp);
$respuesta->setCantComenta(ManejoDataRepository::getCantComment($psolicitud->getIdEjemplar()));
$respuesta->setCantMegusta(ManejoDataRepository::getCantMegusta($psolicitud->getIdEjemplar()));
//echo "esto es lo que hay en respuesta";
//print_r($respuesta);
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
} else {
$respuesta->setRespuesta($respSesionVali);
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
}
}
public function VerComentariosEjemplar(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
$ComenEjemplar = ManejoDataRepository::getComentariosEjemplar($psolicitud);
$respuesta->setRespuesta(AccesoController::inExitoso);
//echo "esto es lo que hay en respuesta";
//print_r($respuesta);
//echo $contador." - lugares hallados";
//$arIdiomas = array("Español","Inglés","Frances","Alemán","Ruso","Portugues",
// "Catalán","Árabe","Bosnio","Croata","Serbio","Italiano","Griego","Turco","Húngaro","Hindi");
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ComenEjemplar);
} else {
$respuesta->setRespuesta($respSesionVali);
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ComenEjemplar);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ComenEjemplar);
}
}
public function enviarMensajeChat(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
//Guarda la acion del usuario en una variable
$ultAccion = $psolicitud->getTratoAcep();
//Guarda el chat
$resp = ManejoDataRepository::setMensajeChat($psolicitud);
//echo "respuesta ".$resp;
if (is_null($resp)) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
} else {
$usrDueno = AccesoController::inDatoCer; //Default: no es el dueño
$respuesta->setRespuesta(AccesoController::inDatoUno);
$arrConversacion = array();
$objConv = new LbNegociacion();
$objConv = ManejoDataRepository::getChatNegociacionById($resp);
//echo "respuesta ".$resp;
//
if (!empty($objConv)) {
$usuarioEnv = ManejoDataRepository::getUsuarioByEmail($psolicitud->getEmail());
$usuarioDes = ManejoDataRepository::getUsuarioById($psolicitud->getIdusuariodes());
foreach ($objConv as $neg){
$idconversa = $neg->getTxnegidconversacion();
if($neg->getInnegusuescribe() == $neg->getInnegusuduenho()){
$usrrecibe = $neg->getInnegususolicita();
$usrDueno = AccesoController::inDatoUno;
} else {
$usrrecibe = $neg->getInnegusuduenho();
$usrDueno = AccesoController::inDatoCer;
}
$arrConversacion[] = array('fecha' => $neg->getFenegfechamens()->format(("Y-m-d H:i:s")),
'usrescribe' => $neg->getInnegusuescribe()->getInusuario(),
'nommostusrescribe' => utf8_encode($neg->getInnegusuescribe()->getTxusunommostrar()),
'idusrdestino' => $usrrecibe->getInusuario(),
'nommostusrdest' => utf8_encode($usrrecibe->getTxusunommostrar()),
'txmensaje' => utf8_encode($neg->getTxnegmensaje()),
'idconversa' => utf8_encode($neg->getTxnegidconversacion()),
'tratoacep' => $neg->getInnegtratoacep());
}
$respuesta->setIndAcept(ManejoDataRepository::getUsAceptTrato($usuarioEnv, $idconversa));
$respuesta->setIndOtroAcept(ManejoDataRepository::getUsAceptTrato($usuarioDes, $idconversa));
$respuesta->setBotonesMostrar(ManejoDataRepository::getBotonesMostrar($idconversa,$usrDueno,$ultAccion));
}
}
//echo "esto es lo que hay en respuesta";
//print_r($respuesta);
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arrConversacion);
} else {
$respuesta->setRespuesta($respSesionVali);
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arrConversacion);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arrConversacion);
}
}
public function listarEditoriales(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
$respuesta->setRespuesta(AccesoController::inExitoso);
//echo "Respuesta Idiomas: ".$respuesta->getRespuesta()." \n";
$editoriales = ManejoDataRepository::getListaEditoriales();
$editorial = new LbEditoriales();
$arEditoriales = array();
//$contador = 0;
foreach ($editoriales as $editorial) {
$arEditoriales[] = array("ideditor"=>$editorial->getInideditorial(), "nomeditor"=>utf8_encode($editorial->getTxedinombre()));
//echo "Idioma=".$idioma->getInididioma()." - ".$idioma->getTxidinombre()." \n";
//$contador++;
}
//echo "esto es lo que hay en respuesta";
//print_r($respuesta);
//echo $contador." - lugares hallados";
//$arIdiomas = array("Español","Inglés","Frances","Alemán","Ruso","Portugues",
// "Catalán","Árabe","Bosnio","Croata","Serbio","Italiano","Griego","Turco","Húngaro","Hindi");
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arEditoriales);
} else {
$respuesta->setRespuesta($respSesionVali);
$arEditoriales = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arEditoriales);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
$arEditoriales = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arEditoriales);
}
}
public function listarAutores(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
$respuesta->setRespuesta(AccesoController::inExitoso);
//echo "Respuesta Idiomas: ".$respuesta->getRespuesta()." \n";
$autores = ManejoDataRepository::getListaAutores();
$autor = new LbAutores();
$arAutores = array();
//$contador = 0;
foreach ($autores as $autor) {
$arAutores[] = array("idautor"=>$autor->getInidautor(), "nomautor"=>utf8_encode($autor->getTxautnombre()));
//echo "Idioma=".$idioma->getInididioma()." - ".$idioma->getTxidinombre()." \n";
//$contador++;
}
//echo "esto es lo que hay en respuesta";
//print_r($respuesta);
//echo $contador." - lugares hallados";
//$arIdiomas = array("Español","Inglés","Frances","Alemán","Ruso","Portugues",
// "Catalán","Árabe","Bosnio","Croata","Serbio","Italiano","Griego","Turco","Húngaro","Hindi");
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arAutores);
} else {
$respuesta->setRespuesta($respSesionVali);
$arAutores = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arAutores);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
$arAutores= array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arAutores);
}
}
}
| Java |
/**
* marked - a markdown parser
* Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
* https://github.com/chjj/marked
*/
;(function() {
/**
* Block-Level Grammar
*/
var block = {
newline: /^\n+/,
code: /^( {4}[^\n]+\n*)+/,
fences: noop,
hr: /^( *[-*_]){3,} *(?:\n+|$)/,
heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
nptable: noop,
lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
table: noop,
paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
text: /^[^\n]+/
};
block.bullet = /(?:[*+-]|\d+\.)/;
block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
block.item = replace(block.item, 'gm')
(/bull/g, block.bullet)
();
block.list = replace(block.list)
(/bull/g, block.bullet)
('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
('def', '\\n+(?=' + block.def.source + ')')
();
block.blockquote = replace(block.blockquote)
('def', block.def)
();
block._tag = '(?!(?:'
+ 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
+ '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
+ '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
block.html = replace(block.html)
('comment', /<!--[\s\S]*?-->/)
('closed', /<(tag)[\s\S]+?<\/\1>/)
('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
(/tag/g, block._tag)
();
block.paragraph = replace(block.paragraph)
('hr', block.hr)
('heading', block.heading)
('lheading', block.lheading)
('blockquote', block.blockquote)
('tag', '<' + block._tag)
('def', block.def)
();
/**
* Normal Block Grammar
*/
block.normal = merge({}, block);
/**
* GFM Block Grammar
*/
block.gfm = merge({}, block.normal, {
fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
paragraph: /^/,
heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
});
block.gfm.paragraph = replace(block.paragraph)
('(?!', '(?!'
+ block.gfm.fences.source.replace('\\1', '\\2') + '|'
+ block.list.source.replace('\\1', '\\3') + '|')
();
/**
* GFM + Tables Block Grammar
*/
block.tables = merge({}, block.gfm, {
nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
});
/**
* Block Lexer
*/
function Lexer(options) {
this.tokens = [];
this.tokens.links = {};
this.options = options || marked.defaults;
this.rules = block.normal;
if (this.options.gfm) {
if (this.options.tables) {
this.rules = block.tables;
} else {
this.rules = block.gfm;
}
}
}
/**
* Expose Block Rules
*/
Lexer.rules = block;
/**
* Static Lex Method
*/
Lexer.lex = function(src, options) {
var lexer = new Lexer(options);
return lexer.lex(src);
};
/**
* Preprocessing
*/
Lexer.prototype.lex = function(src) {
src = src
.replace(/\r\n|\r/g, '\n')
.replace(/\t/g, ' ')
.replace(/\u00a0/g, ' ')
.replace(/\u2424/g, '\n');
return this.token(src, true);
};
/**
* Lexing
*/
Lexer.prototype.token = function(src, top, bq) {
var src = src.replace(/^ +$/gm, '')
, next
, loose
, cap
, bull
, b
, item
, space
, i
, l;
while (src) {
// newline
if (cap = this.rules.newline.exec(src)) {
src = src.substring(cap[0].length);
if (cap[0].length > 1) {
this.tokens.push({
type: 'space'
});
}
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
cap = cap[0].replace(/^ {4}/gm, '');
this.tokens.push({
type: 'code',
text: !this.options.pedantic
? cap.replace(/\n+$/, '')
: cap
});
continue;
}
// fences (gfm)
if (cap = this.rules.fences.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'code',
lang: cap[2],
text: cap[3] || ''
});
continue;
}
// heading
if (cap = this.rules.heading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[1].length,
text: cap[2]
});
continue;
}
// table no leading pipe (gfm)
if (top && (cap = this.rules.nptable.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/\n$/, '').split('\n')
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i].split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// lheading
if (cap = this.rules.lheading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[2] === '=' ? 1 : 2,
text: cap[1]
});
continue;
}
// hr
if (cap = this.rules.hr.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'hr'
});
continue;
}
// blockquote
if (cap = this.rules.blockquote.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'blockquote_start'
});
cap = cap[0].replace(/^ *> ?/gm, '');
// Pass `top` to keep the current
// "toplevel" state. This is exactly
// how markdown.pl works.
this.token(cap, top, true);
this.tokens.push({
type: 'blockquote_end'
});
continue;
}
// list
if (cap = this.rules.list.exec(src)) {
src = src.substring(cap[0].length);
bull = cap[2];
this.tokens.push({
type: 'list_start',
ordered: bull.length > 1
});
// Get each top-level item.
cap = cap[0].match(this.rules.item);
next = false;
l = cap.length;
i = 0;
for (; i < l; i++) {
item = cap[i];
// Remove the list item's bullet
// so it is seen as the next token.
space = item.length;
item = item.replace(/^ *([*+-]|\d+\.) +/, '');
// Outdent whatever the
// list item contains. Hacky.
if (~item.indexOf('\n ')) {
space -= item.length;
item = !this.options.pedantic
? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
: item.replace(/^ {1,4}/gm, '');
}
// Determine whether the next list item belongs here.
// Backpedal if it does not belong in this list.
if (this.options.smartLists && i !== l - 1) {
b = block.bullet.exec(cap[i + 1])[0];
if (bull !== b && !(bull.length > 1 && b.length > 1)) {
src = cap.slice(i + 1).join('\n') + src;
i = l - 1;
}
}
// Determine whether item is loose or not.
// Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
// for discount behavior.
loose = next || /\n\n(?!\s*$)/.test(item);
if (i !== l - 1) {
next = item.charAt(item.length - 1) === '\n';
if (!loose) loose = next;
}
this.tokens.push({
type: loose
? 'loose_item_start'
: 'list_item_start'
});
// Recurse.
this.token(item, false, bq);
this.tokens.push({
type: 'list_item_end'
});
}
this.tokens.push({
type: 'list_end'
});
continue;
}
// html
if (cap = this.rules.html.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: this.options.sanitize
? 'paragraph'
: 'html',
pre: !this.options.sanitizer
&& (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
text: cap[0]
});
continue;
}
// def
if ((!bq && top) && (cap = this.rules.def.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.links[cap[1].toLowerCase()] = {
href: cap[2],
title: cap[3]
};
continue;
}
// table (gfm)
if (top && (cap = this.rules.table.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i]
.replace(/^ *\| *| *\| *$/g, '')
.split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// top-level paragraph
if (top && (cap = this.rules.paragraph.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'paragraph',
text: cap[1].charAt(cap[1].length - 1) === '\n'
? cap[1].slice(0, -1)
: cap[1]
});
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
// Top-level should never reach here.
src = src.substring(cap[0].length);
this.tokens.push({
type: 'text',
text: cap[0]
});
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return this.tokens;
};
/**
* Inline-Level Grammar
*/
var inline = {
escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
url: noop,
tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
link: /^!?\[(inside)\]\(href\)/,
reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
code: /^(`+)([\s\S]*?[^`])\1(?!`)/,
br: /^ {2,}\n(?!\s*$)/,
del: noop,
text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
};
inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
inline.link = replace(inline.link)
('inside', inline._inside)
('href', inline._href)
();
inline.reflink = replace(inline.reflink)
('inside', inline._inside)
();
/**
* Normal Inline Grammar
*/
inline.normal = merge({}, inline);
/**
* Pedantic Inline Grammar
*/
inline.pedantic = merge({}, inline.normal, {
strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
});
/**
* GFM Inline Grammar
*/
inline.gfm = merge({}, inline.normal, {
escape: replace(inline.escape)('])', '~|])')(),
url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
del: /^~~(?=\S)([\s\S]*?\S)~~/,
text: replace(inline.text)
(']|', '~]|')
('|', '|https?://|')
()
});
/**
* GFM + Line Breaks Inline Grammar
*/
inline.breaks = merge({}, inline.gfm, {
br: replace(inline.br)('{2,}', '*')(),
text: replace(inline.gfm.text)('{2,}', '*')()
});
/**
* Inline Lexer & Compiler
*/
function InlineLexer(links, options) {
this.options = options || marked.defaults;
this.links = links;
this.rules = inline.normal;
this.renderer = this.options.renderer || new Renderer;
this.renderer.options = this.options;
if (!this.links) {
throw new
Error('Tokens array requires a `links` property.');
}
if (this.options.gfm) {
if (this.options.breaks) {
this.rules = inline.breaks;
} else {
this.rules = inline.gfm;
}
} else if (this.options.pedantic) {
this.rules = inline.pedantic;
}
}
/**
* Expose Inline Rules
*/
InlineLexer.rules = inline;
/**
* Static Lexing/Compiling Method
*/
InlineLexer.output = function(src, links, options) {
var inline = new InlineLexer(links, options);
return inline.output(src);
};
/**
* Lexing/Compiling
*/
InlineLexer.prototype.output = function(src) {
var out = ''
, link
, text
, href
, cap;
while (src) {
// escape
if (cap = this.rules.escape.exec(src)) {
src = src.substring(cap[0].length);
out += cap[1];
continue;
}
// autolink
if (cap = this.rules.autolink.exec(src)) {
src = src.substring(cap[0].length);
if (cap[2] === '@') {
text = cap[1].charAt(6) === ':'
? this.mangle(cap[1].substring(7))
: this.mangle(cap[1]);
href = this.mangle('mailto:') + text;
} else {
text = escape(cap[1]);
href = text;
}
out += this.renderer.link(href, null, text);
continue;
}
// url (gfm)
if (!this.inLink && (cap = this.rules.url.exec(src))) {
src = src.substring(cap[0].length);
text = escape(cap[1]);
href = text;
out += this.renderer.link(href, null, text);
continue;
}
// tag
if (cap = this.rules.tag.exec(src)) {
if (!this.inLink && /^<a /i.test(cap[0])) {
this.inLink = true;
} else if (this.inLink && /^<\/a>/i.test(cap[0])) {
this.inLink = false;
}
src = src.substring(cap[0].length);
out += this.options.sanitize
? this.options.sanitizer
? this.options.sanitizer(cap[0])
: escape(cap[0])
: cap[0]
continue;
}
// link
if (cap = this.rules.link.exec(src)) {
src = src.substring(cap[0].length);
this.inLink = true;
out += this.outputLink(cap, {
href: cap[2],
title: cap[3]
});
this.inLink = false;
continue;
}
// reflink, nolink
if ((cap = this.rules.reflink.exec(src))
|| (cap = this.rules.nolink.exec(src))) {
src = src.substring(cap[0].length);
link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
link = this.links[link.toLowerCase()];
if (!link || !link.href) {
out += cap[0].charAt(0);
src = cap[0].substring(1) + src;
continue;
}
this.inLink = true;
out += this.outputLink(cap, link);
this.inLink = false;
continue;
}
// strong
if (cap = this.rules.strong.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.strong(this.output(cap[2] || cap[1]));
continue;
}
// em
if (cap = this.rules.em.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.em(this.output(cap[2] || cap[1]));
continue;
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.codespan(escape(cap[2].trim(), true));
continue;
}
// br
if (cap = this.rules.br.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.br();
continue;
}
// del (gfm)
if (cap = this.rules.del.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.del(this.output(cap[1]));
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.text(escape(this.smartypants(cap[0])));
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return out;
};
/**
* Compile Link
*/
InlineLexer.prototype.outputLink = function(cap, link) {
var href = escape(link.href)
, title = link.title ? escape(link.title) : null;
return cap[0].charAt(0) !== '!'
? this.renderer.link(href, title, this.output(cap[1]))
: this.renderer.image(href, title, escape(cap[1]));
};
/**
* Smartypants Transformations
*/
InlineLexer.prototype.smartypants = function(text) {
if (!this.options.smartypants) return text;
return text
// em-dashes
.replace(/---/g, '\u2014')
// en-dashes
.replace(/--/g, '\u2013')
// opening singles
.replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
// closing singles & apostrophes
.replace(/'/g, '\u2019')
// opening doubles
.replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
// closing doubles
.replace(/"/g, '\u201d')
// ellipses
.replace(/\.{3}/g, '\u2026');
};
/**
* Mangle Links
*/
InlineLexer.prototype.mangle = function(text) {
if (!this.options.mangle) return text;
var out = ''
, l = text.length
, i = 0
, ch;
for (; i < l; i++) {
ch = text.charCodeAt(i);
if (Math.random() > 0.5) {
ch = 'x' + ch.toString(16);
}
out += '&#' + ch + ';';
}
return out;
};
/**
* Renderer
*/
function Renderer(options) {
this.options = options || {};
}
Renderer.prototype.code = function(code, lang, escaped) {
if (this.options.highlight) {
var out = this.options.highlight(code, lang);
if (out != null && out !== code) {
escaped = true;
code = out;
}
}
if (!lang) {
return '<pre><code>'
+ (escaped ? code : escape(code, true))
+ '\n</code></pre>';
}
return '<pre><code class="'
+ this.options.langPrefix
+ escape(lang, true)
+ '">'
+ (escaped ? code : escape(code, true))
+ '\n</code></pre>\n';
};
Renderer.prototype.blockquote = function(quote) {
return '<blockquote>\n' + quote + '</blockquote>\n';
};
Renderer.prototype.html = function(html) {
return html;
};
Renderer.prototype.heading = function(text, level, raw) {
return '<h'
+ level
+ ' id="'
+ this.options.headerPrefix
+ raw.toLowerCase().replace(/[^\w]+/g, '-')
+ '">'
+ text
+ '</h'
+ level
+ '>\n';
};
Renderer.prototype.hr = function() {
return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
};
Renderer.prototype.list = function(body, ordered) {
var type = ordered ? 'ol' : 'ul';
return '<' + type + '>\n' + body + '</' + type + '>\n';
};
Renderer.prototype.listitem = function(text) {
return '<li>' + text + '</li>\n';
};
Renderer.prototype.paragraph = function(text) {
return '<p>' + text + '</p>\n';
};
Renderer.prototype.table = function(header, body) {
return '<table>\n'
+ '<thead>\n'
+ header
+ '</thead>\n'
+ '<tbody>\n'
+ body
+ '</tbody>\n'
+ '</table>\n';
};
Renderer.prototype.tablerow = function(content) {
return '<tr>\n' + content + '</tr>\n';
};
Renderer.prototype.tablecell = function(content, flags) {
var type = flags.header ? 'th' : 'td';
var tag = flags.align
? '<' + type + ' style="text-align:' + flags.align + '">'
: '<' + type + '>';
return tag + content + '</' + type + '>\n';
};
// span level renderer
Renderer.prototype.strong = function(text) {
return '<strong>' + text + '</strong>';
};
Renderer.prototype.em = function(text) {
return '<em>' + text + '</em>';
};
Renderer.prototype.codespan = function(text) {
return '<code>' + text + '</code>';
};
Renderer.prototype.br = function() {
return this.options.xhtml ? '<br/>' : '<br>';
};
Renderer.prototype.del = function(text) {
return '<del>' + text + '</del>';
};
Renderer.prototype.link = function(href, title, text) {
if (this.options.sanitize) {
try {
var prot = decodeURIComponent(unescape(href))
.replace(/[^\w:]/g, '')
.toLowerCase();
} catch (e) {
return '';
}
if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
return '';
}
}
if (this.options.baseUrl && !originIndependentUrl.test(href)) {
href = resolveUrl(this.options.baseUrl, href);
}
var out = '<a href="' + href + '"';
if (title) {
out += ' title="' + title + '"';
}
out += '>' + text + '</a>';
return out;
};
Renderer.prototype.image = function(href, title, text) {
if (this.options.baseUrl && !originIndependentUrl.test(href)) {
href = resolveUrl(this.options.baseUrl, href);
}
var out = '<img src="' + href + '" alt="' + text + '"';
if (title) {
out += ' title="' + title + '"';
}
out += this.options.xhtml ? '/>' : '>';
return out;
};
Renderer.prototype.text = function(text) {
return text;
};
/**
* Parsing & Compiling
*/
function Parser(options) {
this.tokens = [];
this.token = null;
this.options = options || marked.defaults;
this.options.renderer = this.options.renderer || new Renderer;
this.renderer = this.options.renderer;
this.renderer.options = this.options;
}
/**
* Static Parse Method
*/
Parser.parse = function(src, options, renderer) {
var parser = new Parser(options, renderer);
return parser.parse(src);
};
/**
* Parse Loop
*/
Parser.prototype.parse = function(src) {
this.inline = new InlineLexer(src.links, this.options, this.renderer);
this.tokens = src.reverse();
var out = '';
while (this.next()) {
out += this.tok();
}
return out;
};
/**
* Next Token
*/
Parser.prototype.next = function() {
return this.token = this.tokens.pop();
};
/**
* Preview Next Token
*/
Parser.prototype.peek = function() {
return this.tokens[this.tokens.length - 1] || 0;
};
/**
* Parse Text Tokens
*/
Parser.prototype.parseText = function() {
var body = this.token.text;
while (this.peek().type === 'text') {
body += '\n' + this.next().text;
}
return this.inline.output(body);
};
/**
* Parse Current Token
*/
Parser.prototype.tok = function() {
switch (this.token.type) {
case 'space': {
return '';
}
case 'hr': {
return this.renderer.hr();
}
case 'heading': {
return this.renderer.heading(
this.inline.output(this.token.text),
this.token.depth,
this.token.text);
}
case 'code': {
return this.renderer.code(this.token.text,
this.token.lang,
this.token.escaped);
}
case 'table': {
var header = ''
, body = ''
, i
, row
, cell
, flags
, j;
// header
cell = '';
for (i = 0; i < this.token.header.length; i++) {
flags = { header: true, align: this.token.align[i] };
cell += this.renderer.tablecell(
this.inline.output(this.token.header[i]),
{ header: true, align: this.token.align[i] }
);
}
header += this.renderer.tablerow(cell);
for (i = 0; i < this.token.cells.length; i++) {
row = this.token.cells[i];
cell = '';
for (j = 0; j < row.length; j++) {
cell += this.renderer.tablecell(
this.inline.output(row[j]),
{ header: false, align: this.token.align[j] }
);
}
body += this.renderer.tablerow(cell);
}
return this.renderer.table(header, body);
}
case 'blockquote_start': {
var body = '';
while (this.next().type !== 'blockquote_end') {
body += this.tok();
}
return this.renderer.blockquote(body);
}
case 'list_start': {
var body = ''
, ordered = this.token.ordered;
while (this.next().type !== 'list_end') {
body += this.tok();
}
return this.renderer.list(body, ordered);
}
case 'list_item_start': {
var body = '';
while (this.next().type !== 'list_item_end') {
body += this.token.type === 'text'
? this.parseText()
: this.tok();
}
return this.renderer.listitem(body);
}
case 'loose_item_start': {
var body = '';
while (this.next().type !== 'list_item_end') {
body += this.tok();
}
return this.renderer.listitem(body);
}
case 'html': {
var html = !this.token.pre && !this.options.pedantic
? this.inline.output(this.token.text)
: this.token.text;
return this.renderer.html(html);
}
case 'paragraph': {
return this.renderer.paragraph(this.inline.output(this.token.text));
}
case 'text': {
return this.renderer.paragraph(this.parseText());
}
}
};
/**
* Helpers
*/
function escape(html, encode) {
return html
.replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function unescape(html) {
// explicitly match decimal, hex, and named HTML entities
return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
n = n.toLowerCase();
if (n === 'colon') return ':';
if (n.charAt(0) === '#') {
return n.charAt(1) === 'x'
? String.fromCharCode(parseInt(n.substring(2), 16))
: String.fromCharCode(+n.substring(1));
}
return '';
});
}
function replace(regex, opt) {
regex = regex.source;
opt = opt || '';
return function self(name, val) {
if (!name) return new RegExp(regex, opt);
val = val.source || val;
val = val.replace(/(^|[^\[])\^/g, '$1');
regex = regex.replace(name, val);
return self;
};
}
function resolveUrl(base, href) {
if (!baseUrls[' ' + base]) {
// we can ignore everything in base after the last slash of its path component,
// but we might need to add _that_
// https://tools.ietf.org/html/rfc3986#section-3
if (/^[^:]+:\/*[^/]*$/.test(base)) {
baseUrls[' ' + base] = base + '/';
} else {
baseUrls[' ' + base] = base.replace(/[^/]*$/, '');
}
}
base = baseUrls[' ' + base];
if (href.slice(0, 2) === '//') {
return base.replace(/:[^]*/, ':') + href;
} else if (href.charAt(0) === '/') {
return base.replace(/(:\/*[^/]*)[^]*/, '$1') + href;
} else {
return base + href;
}
}
baseUrls = {};
originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;
function noop() {}
noop.exec = noop;
function merge(obj) {
var i = 1
, target
, key;
for (; i < arguments.length; i++) {
target = arguments[i];
for (key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
obj[key] = target[key];
}
}
}
return obj;
}
/**
* Marked
*/
function marked(src, opt, callback) {
if (callback || typeof opt === 'function') {
if (!callback) {
callback = opt;
opt = null;
}
opt = merge({}, marked.defaults, opt || {});
var highlight = opt.highlight
, tokens
, pending
, i = 0;
try {
tokens = Lexer.lex(src, opt)
} catch (e) {
return callback(e);
}
pending = tokens.length;
var done = function(err) {
if (err) {
opt.highlight = highlight;
return callback(err);
}
var out;
try {
out = Parser.parse(tokens, opt);
} catch (e) {
err = e;
}
opt.highlight = highlight;
return err
? callback(err)
: callback(null, out);
};
if (!highlight || highlight.length < 3) {
return done();
}
delete opt.highlight;
if (!pending) return done();
for (; i < tokens.length; i++) {
(function(token) {
if (token.type !== 'code') {
return --pending || done();
}
return highlight(token.text, token.lang, function(err, code) {
if (err) return done(err);
if (code == null || code === token.text) {
return --pending || done();
}
token.text = code;
token.escaped = true;
--pending || done();
});
})(tokens[i]);
}
return;
}
try {
if (opt) opt = merge({}, marked.defaults, opt);
return Parser.parse(Lexer.lex(src, opt), opt);
} catch (e) {
e.message += '\nPlease report this to https://github.com/chjj/marked.';
if ((opt || marked.defaults).silent) {
return '<p>An error occured:</p><pre>'
+ escape(e.message + '', true)
+ '</pre>';
}
throw e;
}
}
/**
* Options
*/
marked.options =
marked.setOptions = function(opt) {
merge(marked.defaults, opt);
return marked;
};
marked.defaults = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
sanitizer: null,
mangle: true,
smartLists: false,
silent: false,
highlight: null,
langPrefix: 'lang-',
smartypants: false,
headerPrefix: '',
renderer: new Renderer,
xhtml: false,
baseUrl: null
};
/**
* Expose
*/
marked.Parser = Parser;
marked.parser = Parser.parse;
marked.Renderer = Renderer;
marked.Lexer = Lexer;
marked.lexer = Lexer.lex;
marked.InlineLexer = InlineLexer;
marked.inlineLexer = InlineLexer.output;
marked.parse = marked;
if (typeof module !== 'undefined' && typeof exports === 'object') {
module.exports = marked;
} else if (typeof define === 'function' && define.amd) {
define(function() { return marked; });
} else {
this.marked = marked;
}
}).call(function() {
return this || (typeof window !== 'undefined' ? window : global);
}());
| Java |
// Unit Test (numerical differentiation)
#include <gtest/gtest.h>
#include <cmath>
#include "diff.h"
#include "matrix.h"
using namespace nmlib;
static double f_11(double x){ return cos(x); }
static double f_n1(const Matrix& x){ return cos(x(0))*cos(2*x(1)); }
static Matrix f_nm(const Matrix& x){ Matrix y(3); y(0)=cos(x(0)-x(1)); y(1)=sin(x(0)-x(1)); y(2)=sin(x(0)); return y; }
TEST(diff,gradient11){
for(int i=-10; i<=10; i++){
double x=i*0.9, dx=1.e-3;
EXPECT_NEAR(gradient(f_11,x,dx,false), -sin(x), 10.e-6); // df/dx
EXPECT_NEAR(gradient(f_11,x,dx,true ), -sin(x), 10.e-12); // higher order version
}
}
TEST(diff,gradientN1){
for(int i=-10; i<=10; i++){
Matrix x(2), dx(2), dy(2);
x(0)=i*0.9;
x(1)=1.2;
dx(0)=1.e-3;
dx(1)=1.e-3;
dy(0)=-sin(x(0))*cos(2*x(1));
dy(1)=-cos(x(0))*sin(2*x(1))*2;
for(size_t j=0; j<x.nrow(); j++){
EXPECT_NEAR(gradient(f_n1,x,j,dx(j),false), dy(j), 10.e-6); // df/dxj
EXPECT_NEAR(gradient(f_n1,x,j,dx(j),true ), dy(j), 10.e-12);
}
EXPECT_NEAR(norm(gradient(f_n1,x,dx,false)-dy), 0, 10.e-6); // (df/dxj)_j
EXPECT_NEAR(norm(gradient(f_n1,x,dx,true )-dy), 0, 10.e-12);
EXPECT_NEAR(norm(gradient(f_n1,x,dx(0),false)-dy), 0, 10.e-6);
EXPECT_NEAR(norm(gradient(f_n1,x,dx(0),true)-dy), 0, 10.e-12);
}
}
TEST(diff,jacobian){
for(int i=-10; i<=10; i++){
Matrix x(2), dx(2), dy(3,2);
x(0)=i*0.9;
x(1)=1.2;
dx(0)=1.e-3;
dx(1)=1.e-3;
dy(0,0)=-sin(x(0)-x(1)); dy(0,1)=+sin(x(0)-x(1));
dy(1,0)=+cos(x(0)-x(1)); dy(1,1)=-cos(x(0)-x(1));
dy(2,0)=+cos(x(0)); dy(2,1)=0;
for(size_t j=0; j<x.nrow(); j++){
EXPECT_NEAR(norm(jacobian(f_nm,x,j,dx(j),false)-getvec(dy,j)), 0, 10.e-6); // (dfi/dxj)_i
EXPECT_NEAR(norm(jacobian(f_nm,x,j,dx(j),true )-getvec(dy,j)), 0, 10.e-12);
}
EXPECT_NEAR(norm(jacobian(f_nm,x,dx,false)-dy), 0, 10.e-6); // (dfi/dxj)_ij
EXPECT_NEAR(norm(jacobian(f_nm,x,dx,true )-dy), 0, 10.e-12);
EXPECT_NEAR(norm(jacobian(f_nm,x,dx(0),false)-dy), 0, 10.e-6);
EXPECT_NEAR(norm(jacobian(f_nm,x,dx(0),true )-dy), 0, 10.e-12);
}
}
TEST(diff,hessian){
Matrix x({1,2}), dx({1.e-3,1.e-3}), h=hessian(f_n1,x,dx);
Matrix h1(2,2);
h1(0,0) = -cos(x(0))*cos(2*x(1));
h1(1,1) = -cos(x(0))*cos(2*x(1))*4;
h1(0,1) = h1(1,0) = +sin(x(0))*sin(2*x(1))*2;
EXPECT_NEAR(norm(h-h1), 0, 1.e-5*norm(h));
EXPECT_NEAR(norm(h-tp(h)), 0, 1.e-5*norm(h));
}
| Java |
import React from "react";
import { Message } from "semantic-ui-react";
import Bracket from "./Bracket";
import "./index.scss";
import parseStats from './parseStats';
export default class Brackets extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
data: this.updateStats(props),
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.stats !== this.props.stats) {
this.setState({
data: this.updateStats(nextProps),
});
}
}
updateStats = (props) => {
return parseStats(props.stats);
};
render () {
if (!this.props.stats) {
return (
<Message>Waiting for Tournament Stats...</Message>
);
}
return (
<div>
{this.state.data.map((bracket, $index) => (
<div className="tournament-bracket" key={ bracket.match.matchID }>
<Bracket
finished={ this.props.stats.finished }
item={bracket}
key={$index}
totalGames={ this.props.stats.options.numberOfGames }
/>
</div>
))}
</div>
);
}
}
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>18 --> 19</title>
<link href="./../../assets/style.css" rel="stylesheet">
</head>
<body>
<h2>You have to be fast</h2>
<a href="./41814c947891496a1acc2233f71c55d6d8d51db20b34ea7b2815cc76b4bf13c8.html">Teleport</a>
<hr>
<a href="./../../about.md">About</a> (Spoilers! )
<script src="./../../assets/md5.js"></script>
<script>
window.currentLevel = 7;
</script>
<script src="./../../assets/script.js"></script>
</body>
</html> | Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>18 --> 19</title>
<link href="./../../assets/style.css" rel="stylesheet">
</head>
<body>
<h2>You have to be fast</h2>
<a href="./d2fe18e71c8455c6ae9719209877704ba01fd0b8a3641bcff330a4d9c8a66210.html">Teleport</a>
<hr>
<a href="./../../about.md">About</a> (Spoilers! )
<script src="./../../assets/md5.js"></script>
<script>
window.currentLevel = 7;
</script>
<script src="./../../assets/script.js"></script>
</body>
</html> | Java |
define([ 'backbone', 'metro', 'util' ], function(Backbone, Metro, Util) {
var MotivationBtnView = Backbone.View.extend({
className: 'motivation-btn-view menu-btn',
events: {
'click': 'toggle',
'mouseover': 'over',
'mouseout': 'out',
},
initialize: function(){
//ensure correct scope
_.bindAll(this, 'render', 'unrender', 'toggle', 'over', 'out');
//initial param
this.motivationView = new MotivationView();
//add to page
this.render();
},
render: function() {
var $button = $('<span class="mif-compass">');
$(this.el).html($button);
$(this.el).attr('title', 'motivation...');
$('body > .container').append($(this.el));
return this;
},
unrender: function() {
this.drawElementsView.unrender();
$(this.el).remove();
},
toggle: function() {
this.drawElementsView.toggle();
},
over: function() {
$(this.el).addClass('expand');
},
out: function() {
$(this.el).removeClass('expand');
}
});
var MotivationView = Backbone.View.extend({
className: 'motivation-view',
events: {
'click .draw': 'draw',
'click .clean': 'clean',
'change .input-type > select': 'clean'
},
initialize: function(){
//ensure correct scope
_.bindAll(this, 'render', 'unrender', 'toggle',
'drawMotivation', 'drawGPS', 'drawAssignedSection', 'drawAugmentedSection');
//motivation param
this.param = {};
this.param.o_lng = 114.05604600906372;
this.param.o_lat = 22.551225247189432;
this.param.d_lng = 114.09120440483093;
this.param.d_lat = 22.545463347318833;
this.param.path = "33879,33880,33881,33882,33883,33884,33885,41084,421,422,423,2383,2377,2376,2334,2335,2565,2566,2567,2568,2569,2570,2571,2572,2573,39716,39717,39718,39719,39720,39721,39722,39723,448,39677,39678";
//GPS param
this.param.gps = "114.05538082122803,22.551086528436926#114.05844390392303,22.551324331927283#114.06151771545409,22.551264881093118#114.06260132789612,22.54908499948478#114.06269788742065,22.5456862971879#114.06271934509277,22.54315951091646#114.06271934509277,22.538938188315093#114.06284809112547,22.53441944644356";
//assigned section param
this.param.assign = "33878,33881,33883,2874,2877,2347,937,941";
//augmented section param //33878,33879,33880,33881,33882,33883,2874,2875,2876,2877,2878,2347,935,936,937,938,939,940,941,
this.param.augment = "33879,33880,33882,2875,2876,2878,935,936,938,939,940";
//add to page
this.render();
},
render: function() {
//this.drawMotivation();
this.drawAssignedSection();
this.drawAugmentedSection();
this.drawGPS();
return this;
},
unrender: function() {
$(this.el).remove();
},
toggle: function() {
$(this.el).css('display') == 'none' ? $(this.el).show() : $(this.el).hide();
},
drawMotivation: function() {
$.get('api/trajectories/motivation', this.param, function(data){
Backbone.trigger('MapView:drawMotivation', data);
});
},
drawGPS: function() {
var self = this;
setTimeout(function() {
var points = self.param.gps.split('#');
_.each(points, function(point_text, index) {
var data = {};
data.geojson = self._getPoint(point_text);
data.options = {};
Backbone.trigger('MapView:drawSampleGPSPoint', data);
});
}, 2000);
},
drawAssignedSection: function() {
$.get('api/elements/sections', {id: this.param.assign}, function(data){
Backbone.trigger('MapView:drawSampleAssignedSection', data);
});
},
drawAugmentedSection: function() {
$.get('api/elements/sections', {id: this.param.augment}, function(data){
Backbone.trigger('MapView:drawSampleAugmentedSection', data);
});
},
_getPoint: function(text) {
var point = text.split(',');
var geojson = {
"type": "FeatureCollection",
"features":[{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [parseFloat(point[0]), parseFloat(point[1])]
}
}]
};
return geojson;
},
});
return MotivationBtnView;
}); | Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_11) on Wed Mar 06 13:52:23 HST 2013 -->
<title>S-Index</title>
<meta name="date" content="2013-03-06">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="S-Index";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../jsl/package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li><a href="../jsl/package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-8.html">Prev Letter</a></li>
<li><a href="index-10.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-9.html" target="_top">Frames</a></li>
<li><a href="index-9.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="contentContainer"><a href="index-1.html">D</a> <a href="index-2.html">E</a> <a href="index-3.html">G</a> <a href="index-4.html">I</a> <a href="index-5.html">J</a> <a href="index-6.html">M</a> <a href="index-7.html">O</a> <a href="index-8.html">R</a> <a href="index-9.html">S</a> <a href="index-10.html">T</a> <a name="_S_">
<!-- -->
</a>
<h2 class="title">S</h2>
<dl>
<dt><span class="strong"><a href="../jsl/EasyKillBot.html#setRobotFire()">setRobotFire()</a></span> - Method in class jsl.<a href="../jsl/EasyKillBot.html" title="class in jsl">EasyKillBot</a></dt>
<dd>
<div class="block">Method <code>setRobotFire</code> sets action to fire at a
robot in range and power is proportional to distance.</div>
</dd>
<dt><span class="strong"><a href="../jsl/EasyKillBot.html#setRobotGun()">setRobotGun()</a></span> - Method in class jsl.<a href="../jsl/EasyKillBot.html" title="class in jsl">EasyKillBot</a></dt>
<dd>
<div class="block">Method <code>setRobotGun</code> sets the gun turning for the robot.</div>
</dd>
<dt><span class="strong"><a href="../jsl/EasyKillBot.html#setRobotMove()">setRobotMove()</a></span> - Method in class jsl.<a href="../jsl/EasyKillBot.html" title="class in jsl">EasyKillBot</a></dt>
<dd>
<div class="block">Method <code>setRobotMove</code> sets the turn and traveling
portion of the robot.</div>
</dd>
<dt><span class="strong"><a href="../jsl/EasyKillBot.html#setRobotRadar()">setRobotRadar()</a></span> - Method in class jsl.<a href="../jsl/EasyKillBot.html" title="class in jsl">EasyKillBot</a></dt>
<dd>
<div class="block">Method <code>setRobotRadar</code> sets the radar determines
radar action based on current information.</div>
</dd>
<dt><span class="strong"><a href="../jsl/EasyKillBot.html#setTrackedRadar()">setTrackedRadar()</a></span> - Method in class jsl.<a href="../jsl/EasyKillBot.html" title="class in jsl">EasyKillBot</a></dt>
<dd>
<div class="block">Method <code>setTrackedRadar</code> sets the radar turning for the robot.</div>
</dd>
<dt><span class="strong"><a href="../jsl/EnemyRobot.html#storeEvent(robocode.ScannedRobotEvent)">storeEvent(ScannedRobotEvent)</a></span> - Method in class jsl.<a href="../jsl/EnemyRobot.html" title="class in jsl">EnemyRobot</a></dt>
<dd>
<div class="block">Method <code>storeEvent</code> stores an event to be used later.</div>
</dd>
</dl>
<a href="index-1.html">D</a> <a href="index-2.html">E</a> <a href="index-3.html">G</a> <a href="index-4.html">I</a> <a href="index-5.html">J</a> <a href="index-6.html">M</a> <a href="index-7.html">O</a> <a href="index-8.html">R</a> <a href="index-9.html">S</a> <a href="index-10.html">T</a> </div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../jsl/package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li><a href="../jsl/package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-8.html">Prev Letter</a></li>
<li><a href="index-10.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-9.html" target="_top">Frames</a></li>
<li><a href="index-9.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Java |
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_NETADDRESS_H
#define BITCOIN_NETADDRESS_H
#include "compat.h"
#include "serialize.h"
#include <stdint.h>
#include <string>
#include <vector>
extern bool fAllowPrivateNet;
enum Network
{
NET_UNROUTABLE = 0,
NET_IPV4,
NET_IPV6,
NET_TOR,
NET_MAX,
};
/** IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96)) */
class CNetAddr
{
protected:
unsigned char ip[16]; // in network byte order
uint32_t scopeId; // for scoped/link-local ipv6 addresses
public:
CNetAddr();
CNetAddr(const struct in_addr& ipv4Addr);
explicit CNetAddr(const char *pszIp, bool fAllowLookup = false);
explicit CNetAddr(const std::string &strIp, bool fAllowLookup = false);
void Init();
void SetIP(const CNetAddr& ip);
/**
* Set raw IPv4 or IPv6 address (in network byte order)
* @note Only NET_IPV4 and NET_IPV6 are allowed for network.
*/
void SetRaw(Network network, const uint8_t *data);
bool SetSpecial(const std::string &strName); // for Tor addresses
bool IsIPv4() const; // IPv4 mapped address (::FFFF:0:0/96, 0.0.0.0/0)
bool IsIPv6() const; // IPv6 address (not mapped IPv4, not Tor)
bool IsRFC1918() const; // IPv4 private networks (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12)
bool IsRFC2544() const; // IPv4 inter-network communications (192.18.0.0/15)
bool IsRFC6598() const; // IPv4 ISP-level NAT (100.64.0.0/10)
bool IsRFC5737() const; // IPv4 documentation addresses (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24)
bool IsRFC3849() const; // IPv6 documentation address (2001:0DB8::/32)
bool IsRFC3927() const; // IPv4 autoconfig (169.254.0.0/16)
bool IsRFC3964() const; // IPv6 6to4 tunnelling (2002::/16)
bool IsRFC4193() const; // IPv6 unique local (FC00::/7)
bool IsRFC4380() const; // IPv6 Teredo tunnelling (2001::/32)
bool IsRFC4843() const; // IPv6 ORCHID (2001:10::/28)
bool IsRFC4862() const; // IPv6 autoconfig (FE80::/64)
bool IsRFC6052() const; // IPv6 well-known prefix (64:FF9B::/96)
bool IsRFC6145() const; // IPv6 IPv4-translated address (::FFFF:0:0:0/96)
bool IsTor() const;
bool IsLocal() const;
bool IsRoutable() const;
bool IsValid() const;
bool IsMulticast() const;
enum Network GetNetwork() const;
std::string ToString() const;
std::string ToStringIP(bool fUseGetnameinfo = true) const;
unsigned int GetByte(int n) const;
uint64_t GetHash() const;
bool GetInAddr(struct in_addr* pipv4Addr) const;
std::vector<unsigned char> GetGroup() const;
int GetReachabilityFrom(const CNetAddr *paddrPartner = NULL) const;
void print() const;
CNetAddr(const struct in6_addr& pipv6Addr, const uint32_t scope = 0);
bool GetIn6Addr(struct in6_addr* pipv6Addr) const;
friend bool operator==(const CNetAddr& a, const CNetAddr& b);
friend bool operator!=(const CNetAddr& a, const CNetAddr& b);
friend bool operator<(const CNetAddr& a, const CNetAddr& b);
IMPLEMENT_SERIALIZE
(
READWRITE(FLATDATA(ip));
)
friend class CSubNet;
};
class CSubNet
{
protected:
/// Network (base) address
CNetAddr network;
/// Netmask, in network byte order
uint8_t netmask[16];
/// Is this value valid? (only used to signal parse errors)
bool valid;
public:
CSubNet();
CSubNet(const CNetAddr &addr, int32_t mask);
CSubNet(const CNetAddr &addr, const CNetAddr &mask);
//constructor for single ip subnet (<ipv4>/32 or <ipv6>/128)
explicit CSubNet(const CNetAddr &addr);
bool Match(const CNetAddr &addr) const;
std::string ToString() const;
bool IsValid() const;
friend bool operator==(const CSubNet& a, const CSubNet& b);
friend bool operator!=(const CSubNet& a, const CSubNet& b);
friend bool operator<(const CSubNet& a, const CSubNet& b);
IMPLEMENT_SERIALIZE
(
READWRITE(network);
READWRITE(FLATDATA(netmask));
READWRITE(FLATDATA(valid));
)
};
/** A combination of a network address (CNetAddr) and a (TCP) port */
class CService : public CNetAddr
{
protected:
unsigned short port; // host order
public:
CService();
CService(const CNetAddr& ip, unsigned short port);
CService(const struct in_addr& ipv4Addr, unsigned short port);
CService(const struct sockaddr_in& addr);
explicit CService(const char *pszIpPort, int portDefault, bool fAllowLookup = false);
explicit CService(const char *pszIpPort, bool fAllowLookup = false);
explicit CService(const std::string& strIpPort, int portDefault, bool fAllowLookup = false);
explicit CService(const std::string& strIpPort, bool fAllowLookup = false);
void Init();
void SetPort(unsigned short portIn);
unsigned short GetPort() const;
bool GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const;
bool SetSockAddr(const struct sockaddr* paddr);
friend bool operator==(const CService& a, const CService& b);
friend bool operator!=(const CService& a, const CService& b);
friend bool operator<(const CService& a, const CService& b);
std::vector<unsigned char> GetKey() const;
std::string ToString(bool fUseGetnameinfo = true) const;
std::string ToStringPort() const;
std::string ToStringIPPort(bool fUseGetnameinfo = true) const;
void print() const;
CService(const struct in6_addr& ipv6Addr, unsigned short port);
CService(const struct sockaddr_in6& addr);
IMPLEMENT_SERIALIZE
(
CService* pthis = const_cast<CService*>(this);
READWRITE(FLATDATA(ip));
unsigned short portN = htons(port);
READWRITE(portN);
if (fRead)
pthis->port = ntohs(portN);
)
};
#endif // BITCOIN_NETADDRESS_H
| Java |
<?php
/**
* Switch shortcode
*
* @category TacticalWP-Theme
* @package TacticalWP
* @author Tyler Kemme <dev@tylerkemme.com>
* @license MIT https://opensource.org/licenses/MIT
* @version 1.0.4
* @link https://github.com/tpkemme/tacticalwp-theme
* @since 1.0.0
*/
/**
* Outputs an switch when the [twp-switch] is used
*
* @param [string] $atts shortcode attributes, required.
* @param [string] $content shortcode content, optional.
* @return output of shortcode
* @since 1.0.0
* @version 1.0.4
*/
function twp_switch( $atts, $content = '' ) {
$atts = shortcode_atts( array(
'id' => wp_generate_password( 6, false ),
'size' => 'small',
), $atts, 'twp-switch' );
$out = '';
$out .= '<div class="switch ' . $atts['size'] . '">
<input class="switch-input" id="' . $atts['id'] . '" type="checkbox" name="' . $atts['id'] . '"">
<label class="switch-paddle" for="' . $atts['id'] . '">
<span class="show-for-sr">Tiny Sandwiches Enabled</span>
</label>
</div>';
return $out;
}
add_shortcode( 'twp-switch', 'twp_switch' );
| Java |
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='fcit',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='1.2.0',
description='A decision-tree based conditional independence test',
long_description=long_description,
# The project's main homepage.
url = 'https://github.com/kjchalup/fcit',
# Author details
author = 'Krzysztof Chalupka',
author_email = 'janchatko@gmail.com',
# Choose your license
license='MIT',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 3 - Alpha',
# Indicate who your project is intended for
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
# What does your project relate to?
keywords='machine learning statistics decision trees',
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
# Alternatively, if you want to distribute just a my_module.py, uncomment
# this:
# py_modules=["my_module"],
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=['numpy', 'sklearn', 'scipy', 'joblib'],
)
| Java |
import pandas as pd
import os
import time
from datetime import datetime
import re
from time import mktime
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import style
style.use("dark_background")
# path = "X:/Backups/intraQuarter" # for Windows with X files :)
# if git clone'ed then use relative path,
# assuming you extracted the downloaded zip into this project's folder:
path = "intraQuarter"
def Key_Stats(gather="Total Debt/Equity (mrq)"):
statspath = path+'/_KeyStats'
stock_list = [x[0] for x in os.walk(statspath)]
df = pd.DataFrame(
columns = [
'Date',
'Unix',
'Ticker',
'DE Ratio',
'Price',
'stock_p_change',
'SP500',
'sp500_p_change',
'Difference',
'Status'
]
)
sp500_df = pd.DataFrame.from_csv("YAHOO-INDEX_GSPC.csv")
ticker_list = []
for each_dir in stock_list[1:25]:
each_file = os.listdir(each_dir)
# ticker = each_dir.split("\\")[1] # Windows only
# ticker = each_dir.split("/")[1] # this didn't work so do this:
ticker = os.path.basename(os.path.normpath(each_dir))
# print(ticker) # uncomment to verify
ticker_list.append(ticker)
starting_stock_value = False
starting_sp500_value = False
if len(each_file) > 0:
for file in each_file:
date_stamp = datetime.strptime(file, '%Y%m%d%H%M%S.html')
unix_time = time.mktime(date_stamp.timetuple())
full_file_path = each_dir + '/' + file
source = open(full_file_path,'r').read()
try:
try:
value = float(source.split(gather+':</td><td class="yfnc_tabledata1">')[1].split('</td>')[0])
except:
value = float(source.split(gather+':</td>\n<td class="yfnc_tabledata1">')[1].split('</td>')[0])
try:
sp500_date = datetime.fromtimestamp(unix_time).strftime('%Y-%m-%d')
row = sp500_df[(sp500_df.index == sp500_date)]
sp500_value = float(row['Adjusted Close'])
except:
sp500_date = datetime.fromtimestamp(unix_time-259200).strftime('%Y-%m-%d')
row = sp500_df[(sp500_df.index == sp500_date)]
sp500_value = float(row['Adjusted Close'])
try:
stock_price = float(source.split('</small><big><b>')[1].split('</b></big>')[0])
except:
try:
stock_price = (source.split('</small><big><b>')[1].split('</b></big>')[0])
#print(stock_price)
stock_price = re.search(r'(\d{1,8}\.\d{1,8})', stock_price)
stock_price = float(stock_price.group(1))
#print(stock_price)
except:
try:
stock_price = (source.split('<span class="time_rtq_ticker">')[1].split('</span>')[0])
#print(stock_price)
stock_price = re.search(r'(\d{1,8}\.\d{1,8})', stock_price)
stock_price = float(stock_price.group(1))
#print(stock_price)
except:
print('wtf stock price lol',ticker,file, value)
time.sleep(5)
if not starting_stock_value:
starting_stock_value = stock_price
if not starting_sp500_value:
starting_sp500_value = sp500_value
stock_p_change = ((stock_price - starting_stock_value) / starting_stock_value) * 100
sp500_p_change = ((sp500_value - starting_sp500_value) / starting_sp500_value) * 100
location = len(df['Date'])
difference = stock_p_change-sp500_p_change
if difference > 0:
status = "outperform"
else:
status = "underperform"
df = df.append({'Date':date_stamp,
'Unix':unix_time,
'Ticker':ticker,
'DE Ratio':value,
'Price':stock_price,
'stock_p_change':stock_p_change,
'SP500':sp500_value,
'sp500_p_change':sp500_p_change,
############################
'Difference':difference,
'Status':status},
ignore_index=True)
except Exception as e:
pass
#print(ticker,e,file, value)
#print(ticker_list)
#print(df)
for each_ticker in ticker_list:
try:
plot_df = df[(df['Ticker'] == each_ticker)]
plot_df = plot_df.set_index(['Date'])
if plot_df['Status'][-1] == 'underperform':
color = 'r'
else:
color = 'g'
plot_df['Difference'].plot(label=each_ticker, color=color)
plt.legend()
except Exception as e:
print(str(e))
plt.show()
save = gather.replace(' ','').replace(')','').replace('(','').replace('/','')+str('.csv')
print(save)
df.to_csv(save)
Key_Stats()
| Java |
/*
* App Actions
*
* Actions change things in your application
* Since this boilerplate uses a uni-directional data flow, specifically redux,
* we have these actions which are the only way your application interacts with
* your application state. This guarantees that your state is up to date and nobody
* messes it up weirdly somewhere.
*
* To add a new Action:
* 1) Import your constant
* 2) Add a function like this:
* export function yourAction(var) {
* return { type: YOUR_ACTION_CONSTANT, var: var }
* }
*/
import {
LOAD_SONGS,
LOAD_SONGS_SUCCESS,
LOAD_SONGS_ERROR,
} from './constants';
// /**
// * Load the repositories, this action starts the request saga
// *
// * @return {object} An action object with a type of LOAD_REPOS
// */
export function loadSongs() {
return {
type: LOAD_SONGS,
};
}
// /**
// * Dispatched when the repositories are loaded by the request saga
// *
// * @param {array} repos The repository data
// * @param {string} username The current username
// *
// * @return {object} An action object with a type of LOAD_REPOS_SUCCESS passing the repos
// */
export function songsLoaded(repos, username) {
return {
type: LOAD_SONGS_SUCCESS,
repos,
username,
};
}
// /**
// * Dispatched when loading the repositories fails
// *
// * @param {object} error The error
// *
// * @return {object} An action object with a type of LOAD_REPOS_ERROR passing the error
// */
export function songsLoadingError(error) {
return {
type: LOAD_SONGS_ERROR,
error,
};
}
| Java |
# oninput-fix
>Fix input event in jquery, support low version of ie.
### Introduction:
Default is CommonJS module
If not CommonJS you must do this:
>1.Remove first and last line of the code
>
>2.Wrap code useing:
```js
(function ($){
// the code of remove first and last line
}(jQuery));
```
### API:
Sample:
>
```js
$('#input').on('input', callback);
$('#input').input(callback);
$('#input').off('input', callback);
$('#input').uninput(callback);
```
### Notice:
Dot change input value in low version of ie without condition statement, because it will go into an infinite loop!
| Java |
package cmd
import (
"errors"
"github.com/cretz/go-safeclient/client"
"github.com/spf13/cobra"
"log"
"os"
)
var lsShared bool
var lsCmd = &cobra.Command{
Use: "ls [dir]",
Short: "Fetch directory information",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return errors.New("One and only one argument allowed")
}
c, err := getClient()
if err != nil {
log.Fatalf("Unable to obtain client: %v", err)
}
info := client.GetDirInfo{DirPath: args[0], Shared: lsShared}
dir, err := c.GetDir(info)
if err != nil {
log.Fatalf("Failed to list dir: %v", err)
}
writeDirResponseTable(os.Stdout, dir)
return nil
},
}
func init() {
lsCmd.Flags().BoolVarP(&lsShared, "shared", "s", false, "Use shared area for user")
RootCmd.AddCommand(lsCmd)
}
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>rb-aem manual | 3. Packing and unpacking data</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style type="text/css" media="all"><!--@import url(../full.css);--></style>
</head>
<body>
<h1><img src="../rb-appscript-logo.png" alt="rb-appscript" title="rb-appscript" /></h1>
<!-- top navigation -->
<div class="navbar">
<a href="02_apioverview.html">Previous</a> •
<a href="index.html">Up</a> •
<a href="04_references.html">Next</a>
<span>
<a href="../appscript-manual/index.html">appscript</a> /
<a href="../mactypes-manual/index.html">mactypes</a> /
<a href="../osax-manual/index.html">osax</a> /
<strong><a href="../aem-manual/index.html">aem</a></strong>
</span>
</div>
<!-- content -->
<div id="content">
<h2>3. Packing and unpacking data</h2>
<h3>Codecs</h3>
<p>The <code>AEM::Codecs</code> class provides methods for converting Ruby data to <code>AE::AEDesc</code> objects, and vice-versa.</p>
<pre><code>Codecs
Constructor:
new
Methods:
# pack/unpack data
pack(data) -- convert Ruby data to an AEDesc; will raise
a TypeError if data's type/class is unsupported
data : anything
Result : AEDesc
unpack(desc) -- convert an AEDesc to Ruby data; will return
the AEDesc unchanged if it's an unsupported type
desc : AEDesc
Result : anything
# compatibility options
add_unit_types(types) -- register custom unit type
definitions
types : list -- a list of lists, where each sublist
is of form [name, code, pack_proc, unpack_proc]
or [name, code]; if the packer and unpacker
procs are omitted, the AEDesc data is packed/
unpacked as a double-precision float
dont_cache_unpacked_specifiers -- by default, object
specifier descriptors returned by an application
are reused for efficiency; invoke this method to
use AppleScript-style behavior instead (i.e. fully
unpacking and repacking object specifiers each time)
for better compatibility with problem applications
pack_strings_as_type(code) -- by default, strings are
packed as typeUnicodeText descriptors; some older
non-Unicode-aware applications may require text
to be supplied as typeChar/typeIntlText descriptors
code : String -- four-char code, e.g. KAE::TypeChar
(see KAE module for available text types)
use_ascii_8bit -- by default, text descriptors are unpacked
as Strings with UTF-8 Encoding on Ruby 1.9+; invoke
this method to mimic Ruby 1.8-style behavior where
Strings contain UTF-8 encoded data and ASCII-8BIT
Encoding
use_datetime -- by default, dates are unpacked as Time
instances; invoke this method to unpack dates as
DateTime instances instead</code></pre>
<h3>AE types</h3>
<p>The Apple Event Manager defines several types for representing type/class names, enumerator names, etc. that have no direct equivalent in Ruby. Accordingly, aem defines several classes to represent these types on the Ruby side. All share a common abstract base class, <code>AETypeBase</code>:</p>
<pre><code>AETypeBase -- Abstract base class
Constructor:
new(code)
code : str -- a four-character Apple event code
Methods:
code
Result : str -- Apple event code</code></pre>
<p>The four concrete classes are:</p>
<pre><code>AEType < AETypeBase -- represents an AE object of typeType
AEEnum < AETypeBase -- represents an AE object of typeEnumeration
AEProp < AETypeBase -- represents an AE object of typeProperty
AEKey < AETypeBase -- represents an AE object of typeKeyword</code></pre>
</div>
<!-- bottom navigation -->
<div class="footer">
<a href="02_apioverview.html">Previous</a> •
<a href="index.html">Up</a> •
<a href="04_references.html">Next</a>
</div>
</body>
</html> | Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<base data-ice="baseUrl">
<title data-ice="title">Home | incarnate</title>
<link type="text/css" rel="stylesheet" href="css/style.css">
<link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">
<script src="script/prettify/prettify.js"></script>
<script src="script/manual.js"></script>
<meta name="description" content="Dependency Injection (DI) with Lifecycle features for JavaScript."><meta property="twitter:card" content="summary"><meta property="twitter:title" content="incarnate"><meta property="twitter:description" content="Dependency Injection (DI) with Lifecycle features for JavaScript."></head>
<body class="layout-container" data-ice="rootContainer">
<header>
<a href="./">Home</a>
<a href="identifiers.html">Reference</a>
<a href="source.html">Source</a>
<div class="search-box">
<span>
<img src="./image/search.png">
<span class="search-input-edge"></span><input class="search-input"><span class="search-input-edge"></span>
</span>
<ul class="search-result"></ul>
</div>
<a style="position:relative; top:3px;" href="https://github.com/resistdesign/incarnate"><img width="20px" src="./image/github.png"></a></header>
<nav class="navigation" data-ice="nav"><div>
<ul>
<li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/ConfigurableInstance.jsx~ConfigurableInstance.html">ConfigurableInstance</a></span></span></li>
<li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/DependencyDeclaration.jsx~DependencyDeclaration.html">DependencyDeclaration</a></span></span></li>
<li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/HashMatrix.jsx~HashMatrix.html">HashMatrix</a></span></span></li>
<li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/Incarnate.jsx~Incarnate.html">Incarnate</a></span></span></li>
<li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/LifePod.jsx~LifePod.html">LifePod</a></span></span></li>
<li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/SubMapDeclaration.jsx~SubMapDeclaration.html">SubMapDeclaration</a></span></span></li>
</ul>
</div>
</nav>
<div class="content" data-ice="content"><div data-ice="index" class="github-markdown"><h1 id="incarnate--a-href--https---travis-ci-org-resistdesign-incarnate---img-src--https---travis-ci-org-resistdesign-incarnate-svg-branch-master--alt--build-status----a-">Incarnate <a href="https://travis-ci.org/resistdesign/incarnate"><img src="https://travis-ci.org/resistdesign/incarnate.svg?branch=master" alt="Build Status"></a></h1><p>Runtime Dependency Lifecycle Management for JavaScript.</p>
<h2 id="install">Install</h2><p><code>npm i -S incarnate</code></p>
<h2 id="api-docs">API Docs</h2><p><a href="http://incarnate.resist.design">http://incarnate.resist.design</a></p>
<h2 id="usage-example">Usage Example</h2><pre><code class="lang-jsx"><code class="source-code prettyprint">import Incarnate from 'incarnate';
// Declare your application dependencies.
const inc = new Incarnate({
subMap: {
// Keep track of your state.
state: {
subMap: {
user: {
factory: () => ({
authToken: undefined
})
}
}
},
// Supply some services.
services: {
// Some services need authorization information.
shared: {
user: 'state.user'
},
subMap: {
user: true,
login: {
factory: () => {
return async (username, password) => {
// Make a login request, get the `authToken`.
const fakeToken = `${username}:${password}`;
// For demo purposes we'll use the `Buffer` API in node.js to base64 encode the credentials.
return Buffer.from(fakeToken).toString('base64');
};
}
},
accounts: {
dependencies: {
user: 'user'
},
factory: ({dependencies: {user: {authToken = ''} = {}} = {}} = {}) => {
return async () => {
// NOTE: IF we call this service method AFTER `login`,
// the `authToken` will have been automatically updated,
// in this service, by Incarnate.
if (!authToken) {
throw new Error('The accounts service requires an authorization token but one was not supplied.');
}
// Get a list of accounts with the `authToken` in the headers.
console.log('Getting accounts with headers:', {
Authorization: `Bearer: ${authToken}`
});
return [
{name: 'Account 1'},
{name: 'Account 2'},
{name: 'Account 3'},
{name: 'Account 4'}
];
};
}
}
}
},
// Expose some actions that call services and store the results in a nice, tidy, reproducible way.
actions: {
shared: {
user: 'state.user',
loginService: 'services.login'
},
subMap: {
user: true,
loginService: true,
login: {
dependencies: {
loginService: 'loginService'
},
setters: {
setUser: 'user'
},
factory: ({dependencies: {loginService} = {}, setters: {setUser} = {}} = {}) => {
return async ({username, password} = {}) => {
// Login
const authToken = await loginService(username, password);
// Store the `authToken`.
setUser({
authToken
});
return true;
};
}
}
}
}
}
});
// Here's your app.
export default async function app() {
// Get the Login Action.
const loginAction = inc.getResolvedPath('actions.login');
// Do the login.
const loginResult = await loginAction({
username: 'TestUser',
password: 'StopTryingToReadThis'
});
// Get the Accounts Service. It needs the User's `authToken`,
// but you declared it as a Dependency,
// so Incarnate took care of that for you.
const accountsService = inc.getResolvedPath('services.accounts');
// Get those accounts you've been dying to see...
const accounts = await accountsService();
// Here they are!
console.log('These are the accounts:', accounts);
}
// You need to run your app.
app();</code>
</code></pre>
<h2 id="license">License</h2><p><a href="LICENSE.txt">MIT</a></p>
</div>
</div>
<footer class="footer">
Generated by <a href="https://esdoc.org">ESDoc<span data-ice="esdocVersion">(1.0.4)</span><img src="./image/esdoc-logo-mini-black.png"></a>
</footer>
<script src="script/search_index.js"></script>
<script src="script/search.js"></script>
<script src="script/pretty-print.js"></script>
<script src="script/inherited-summary.js"></script>
<script src="script/test-summary.js"></script>
<script src="script/inner-link.js"></script>
<script src="script/patch-for-local.js"></script>
</body>
</html>
| Java |
const simple_sort = (key, a, b) => {
if (a[key] < b[key]) return -1
if (a[key] > b[key]) return 1
return 0
}
const name_sort = (a, b) => simple_sort('name', a, b)
const skill_sort = (a, b) => simple_sort('skill', a, b)
const speed_sort = (a, b) => simple_sort('speed', a, b)
export {
simple_sort,
name_sort,
skill_sort,
speed_sort
} | Java |
export { default } from './EditData';
| Java |
<footer id="footer" role="contentinfo">
<a href="#" class="gotop js-gotop"><i class="icon-arrow-up2"></i></a>
<div class="container">
<div class="">
<div class="col-md-12 text-center">
<p>{{ with .Site.Params.footer.copyright }}{{ . | markdownify }}{{ end }}</p>
</div>
</div>
<div class="row">
<div class="col-md-12 text-center">
<ul class="social social-circle">
{{ range .Site.Params.footer.links }}
<li><a href="{{ with index . 1}}{{ . }}{{ end }}"><i class="{{ with index . 0}}{{ . }}{{ end }}"></i></a></li>
{{ end }}
</ul>
</div>
</div>
</div>
</footer>
| Java |
using System.Xml.Linq;
namespace Lux.Serialization.Xml
{
public interface IXmlConfigurable
{
void Configure(XElement element);
}
} | Java |
<?php
/*
Section: signup
Language: Hungarian
Translator: uno20001 <regisztralo111@gmail.com>
*/
$translations = array(
'h1' => 'Regisztráció',
'mysql-db-name' => 'MySQL adatbázis név',
'mysql-user-name' => 'MySQL felhasználónév',
'mysql-user-password' => 'MySQL jelszó',
'mysql-user-password-verification' => 'MySQL jelszó megerősítése',
'email-address' => 'Email cím',
'agree-conditions' => 'Elolvastam a <a href="conditions.php">felhasználási feltételeket</a> és egyetértek velük.',
'ph1' => '6-16 karakter, nem lehet nagybetű, az 1. karakternek betűnek kell lennie.',
'ph2' => 'Min. 8 karakter.',
'ph3' => 'Írd be az email címed',
'explanation' => 'A felhasználónév és az adatbázis név tartalmazhat kisbetűket, számokat és \'_\' (aláhúzás) karaktert, a hosszának 6 és 16 karakter között kell lennie. Nem használhatsz <a href="https://dev.mysql.com/doc/refman/8.0/en/keywords.html">a MySQL számára fenntartott szavakat</a>!',
'maintenance-notice' => 'Karbantartás miatt a regisztráció jelenleg nem érhető el.',
'agm-p1' => 'A regisztrációddal elfogadod a következőket:',
'agm-li1' => 'A db4free.net egy tesztelési környezet',
'agm-li2' => 'A db4free.net nem megfelelő nem teszt jellegű használathoz',
'agm-li3' => 'Ha úgy döntesz, hogy nem teszt jellegű dolgokhoz kívánod használni a db4free.net-et, akkor azt csak a saját felelősségedre tedd (a nagyon gyakori mentések nagyon ajánlottak)',
'agm-li4' => 'Adatvesztések és üzemidő kiesések bármikor történhetnek (az ezzel kapcsolatos panaszok valószínűleg figyelmen kívül lesznek hagyva)',
'agm-li5' => 'A db4free.net csapata nem biztosít semmilyen garanciát, felelősséget',
'agm-li6' => 'A db4free.net csapata fenntartja a jogot, hogy bármikor, figyelmeztetés nélkül törölje az adatbázisod és/vagy fiókod',
'agm-li7' => 'A db4free.net-tel kapcsolatos legfrissebb információkat elérheted a <a href="twitter.php">Twitteren</a> és a <a href="blog.php">db4free.net blogon</a>',
'agm-li8' => 'A db4free.net csak MySQL adatbázist biztosít, nem ad webtárhelyet (nincs lehetőséged itt tárolni a fájljaidat)',
'agm-p2' => 'Továbbiakban:',
'agm-li9' => 'A db4free.net egy tesztelő szolgáltatás, nem "éles" szolgáltatásokhoz készült. Azok az adatbázisok, amelyek 200 MB-nál több adatot tartalmaznak, értesítés nélkül kiürítésre kerülnek.',
'agm-li10' => 'Kérlek <a href="/delete-account.php">távolítsd el</a> azokat az adatokat és/vagy fiókot amikre/amelyre már nincs szükséged. Ez megkönnyíti a ténylegesen használt adatok visszaállítását, ha a szerver "összeomlik"',
'signup-error1' => 'El kell fogadnod a felhasználási feltételeket!',
'signup-error2' => 'Hiba lépett fel a regisztráció során!',
'signup-error3' => 'Hiba lépett fel a megerősítő email küldése közben!',
'signup-success' => 'Köszönjük a regisztrációt! Hamarosan kapsz egy megerősítő emailt!',
);
?>
| Java |
// ==========================================================================
// DG.ScatterPlotModel
//
// Author: William Finzer
//
// Copyright (c) 2014 by The Concord Consortium, Inc. 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.
// ==========================================================================
sc_require('components/graph/plots/plot_model');
sc_require('components/graph/plots/numeric_plot_model_mixin');
/** @class DG.ScatterPlotModel
@extends DG.PlotModel
*/
DG.ScatterPlotModel = DG.PlotModel.extend(DG.NumericPlotModelMixin,
/** @scope DG.ScatterPlotModel.prototype */
{
/**
*
* @param iPlace {DG.GraphTypes.EPlace}
* @return { class }
*/
getDesiredAxisClassFor: function( iPlace) {
if( iPlace === DG.GraphTypes.EPlace.eX || iPlace === DG.GraphTypes.EPlace.eY)
return DG.CellLinearAxisModel;
else if(iPlace === DG.GraphTypes.EPlace.eY2) {
return (this.getPath('dataConfiguration.y2AttributeID') === DG.Analysis.kNullAttribute) ?
DG.AxisModel : DG.CellLinearAxisModel;
}
},
/**
@property { DG.MovablePointModel }
*/
movablePoint: null,
/**
@property { Boolean }
*/
isMovablePointVisible: function () {
return !SC.none(this.movablePoint) && this.movablePoint.get('isVisible');
}.property(),
isMovablePointVisibleDidChange: function() {
this.notifyPropertyChange('isMovablePointVisible');
}.observes('*movablePoint.isVisible'),
/**
@property { DG.MovableLineModel }
*/
movableLine: null,
/**
@property { Boolean, read only }
*/
isMovableLineVisible: function () {
return !SC.none(this.movableLine) && this.movableLine.get('isVisible');
}.property(),
isMovableLineVisibleDidChange: function() {
this.notifyPropertyChange('isMovableLineVisible');
}.observes('*movableLine.isVisible'),
/**
@property { DG.MultipleLSRLsModel }
*/
multipleLSRLs: null,
/**
@property { Boolean, read only }
*/
isLSRLVisible: function () {
return !SC.none(this.multipleLSRLs) && this.multipleLSRLs.get('isVisible');
}.property(),
isLSRLVisibleDidChange: function() {
this.notifyPropertyChange('isLSRLVisible');
}.observes('*multipleLSRLs.isVisible'),
/**
@property { Boolean }
*/
isInterceptLocked: function ( iKey, iValue) {
if( !SC.none( iValue)) {
this.setPath('movableLine.isInterceptLocked', iValue);
this.setPath('multipleLSRLs.isInterceptLocked', iValue);
}
return !SC.none(this.movableLine) && this.movableLine.get('isInterceptLocked') ||
!SC.none(this.multipleLSRLs) && this.multipleLSRLs.get('isInterceptLocked');
}.property(),
isInterceptLockedDidChange: function() {
this.notifyPropertyChange('isInterceptLocked');
}.observes('*movableLine.isInterceptLocked', '*multipleLSRLs.isInterceptLocked'),
/**
@property { Boolean }
*/
areSquaresVisible: false,
/**
* Used for notification
* @property{}
*/
squares: null,
init: function() {
sc_super();
this.addObserver('movableLine.slope',this.lineDidChange);
this.addObserver('movableLine.intercept',this.lineDidChange);
},
destroy: function() {
this.removeObserver('movableLine.slope',this.lineDidChange);
this.removeObserver('movableLine.intercept',this.lineDidChange);
sc_super();
},
dataConfigurationDidChange: function() {
sc_super();
var tDataConfiguration = this.get('dataConfiguration');
if( tDataConfiguration) {
tDataConfiguration.set('sortCasesByLegendCategories', false);
// This is a cheat. The above line _should_ bring this about, but I couldn't make it work properly
tDataConfiguration.invalidateCaches();
}
}.observes('dataConfiguration'),
/**
Returns true if the plot is affected by the specified change such that
a redraw is required, false otherwise.
@param {Object} iChange -- The change request to/from the DataContext
@returns {Boolean} True if the plot must redraw, false if it is unaffected
*/
isAffectedByChange: function (iChange) {
if (!iChange || !iChange.operation) return false;
return sc_super() ||
(this.isAdornmentVisible('connectingLine') &&
(iChange.operation === 'moveAttribute' || iChange.operation === 'moveCases'));
},
/**
* Used for notification
*/
lineDidChange: function () {
SC.run(function() {
this.notifyPropertyChange('squares');
}.bind(this));
},
/**
* Utility function to create a movable line when needed
*/
createMovablePoint: function () {
if (SC.none(this.movablePoint)) {
this.beginPropertyChanges();
this.set('movablePoint', DG.MovablePointModel.create( {
plotModel: this
}));
this.movablePoint.recomputeCoordinates(this.get('xAxis'), this.get('yAxis'));
this.endPropertyChanges();
}
},
/**
* Utility function to create a movable line when needed
*/
createMovableLine: function () {
if (SC.none(this.movableLine)) {
this.beginPropertyChanges();
this.set('movableLine', DG.MovableLineModel.create( {
plotModel: this,
showSumSquares: this.get('areSquaresVisible')
}));
this.movableLine.recomputeSlopeAndIntercept(this.get('xAxis'), this.get('yAxis'));
this.endPropertyChanges();
}
},
squaresVisibilityChanged: function() {
var tMovableLine = this.get('movableLine'),
tMultipleLSRLs = this.get('multipleLSRLs'),
tSquaresVisible = this.get('areSquaresVisible');
if( tMovableLine)
tMovableLine.set('showSumSquares', tSquaresVisible);
if( tMultipleLSRLs)
tMultipleLSRLs.set('showSumSquares', tSquaresVisible);
}.observes('areSquaresVisible'),
enableMeasuresForSelectionDidChange: function(){
sc_super();
this.setPath('multipleLSRLs.enableMeasuresForSelection', this.get('enableMeasuresForSelection'));
}.observes('enableMeasuresForSelection'),
/**
If we need to make a movable line, do so. In any event toggle its visibility.
*/
toggleMovablePoint: function () {
var this_ = this;
function toggle() {
function doToggle( iPlot) {
if (SC.none(iPlot.movablePoint)) {
iPlot.createMovablePoint(); // Default is to be visible
}
else {
iPlot.movablePoint.recomputePositionIfNeeded(iPlot.get('xAxis'), iPlot.get('yAxis'));
iPlot.movablePoint.set('isVisible', !iPlot.movablePoint.get('isVisible'));
}
}
doToggle( this_);
this_.get('siblingPlots').forEach( doToggle);
}
var willShow = !this.movablePoint || !this.movablePoint.get('isVisible');
DG.UndoHistory.execute(DG.Command.create({
name: "graph.toggleMovablePoint",
undoString: (willShow ? 'DG.Undo.graph.showMovablePoint' : 'DG.Undo.graph.hideMovablePoint'),
redoString: (willShow ? 'DG.Redo.graph.showMovablePoint' : 'DG.Redo.graph.hideMovablePoint'),
log: "toggleMovablePoint: %@".fmt(willShow ? "show" : "hide"),
executeNotification: {
action: 'notify',
resource: 'component',
values: {
operation: 'toggle movable point',
type: 'DG.GraphView'
}
},
execute: function () {
toggle();
},
undo: function () {
toggle();
}
}));
},
/**
If we need to make a movable line, do so. In any event toggle its visibility.
*/
toggleMovableLine: function () {
var this_ = this;
function toggle() {
function doToggle(iPlot) {
if (SC.none(iPlot.movableLine)) {
iPlot.createMovableLine(); // Default is to be visible
}
else {
iPlot.movableLine.recomputeSlopeAndInterceptIfNeeded(iPlot.get('xAxis'), iPlot.get('yAxis'));
iPlot.movableLine.set('isVisible', !iPlot.movableLine.get('isVisible'));
}
}
doToggle( this_);
this_.get('siblingPlots').forEach( doToggle);
}
var willShow = !this.movableLine || !this.movableLine.get('isVisible');
DG.UndoHistory.execute(DG.Command.create({
name: "graph.toggleMovableLine",
undoString: (willShow ? 'DG.Undo.graph.showMovableLine' : 'DG.Undo.graph.hideMovableLine'),
redoString: (willShow ? 'DG.Redo.graph.showMovableLine' : 'DG.Redo.graph.hideMovableLine'),
log: "toggleMovableLine: %@".fmt(willShow ? "show" : "hide"),
executeNotification: {
action: 'notify',
resource: 'component',
values: {
operation: 'toggle movable line',
type: 'DG.GraphView'
}
},
execute: function () {
toggle();
},
undo: function () {
toggle();
}
}));
},
/**
* Utility function to create the multipleLSRLs object when needed
*/
createLSRLLines: function () {
if (SC.none(this.multipleLSRLs)) {
this.set('multipleLSRLs', DG.MultipleLSRLsModel.create( {
plotModel: this,
showSumSquares: this.get('areSquaresVisible'),
isInterceptLocked: this.get('isInterceptLocked'),
enableMeasuresForSelection: this.get('enableMeasuresForSelection')
}));
this.setPath('multipleLSRLs.isVisible', true);
}
},
/**
If we need to make a movable line, do so. In any event toggle its visibility.
*/
toggleLSRLLine: function () {
var this_ = this;
function toggle() {
function doToggle( iPlot) {
if (SC.none(iPlot.get('multipleLSRLs'))) {
iPlot.createLSRLLines();
}
else {
iPlot.setPath('multipleLSRLs.isVisible', !iPlot.getPath('multipleLSRLs.isVisible'));
}
}
doToggle( this_);
this_.get('siblingPlots').forEach( doToggle);
}
var willShow = !this.multipleLSRLs || !this.multipleLSRLs.get('isVisible');
DG.UndoHistory.execute(DG.Command.create({
name: "graph.toggleLSRLLine",
undoString: (willShow ? 'DG.Undo.graph.showLSRL' : 'DG.Undo.graph.hideLSRL'),
redoString: (willShow ? 'DG.Redo.graph.showLSRL' : 'DG.Redo.graph.hideLSRL'),
log: "toggleLSRL: %@".fmt(willShow ? "show" : "hide"),
executeNotification: {
action: 'notify',
resource: 'component',
values: {
operation: 'toggle LSRL',
type: 'DG.GraphView'
}
},
execute: function () {
toggle();
},
undo: function () {
toggle();
}
}));
},
/**
If we need to make a movable line, do so. In any event toggle whether its intercept is locked.
*/
toggleInterceptLocked: function () {
var this_ = this;
function toggle() {
function doToggle( iPlot) {
if (!SC.none(iPlot.movableLine)) {
iPlot.movableLine.toggleInterceptLocked();
iPlot.movableLine.recomputeSlopeAndInterceptIfNeeded(iPlot.get('xAxis'), iPlot.get('yAxis'));
}
if (!SC.none(iPlot.multipleLSRLs)) {
iPlot.multipleLSRLs.toggleInterceptLocked();
}
}
doToggle( this_);
this_.get('siblingPlots').forEach( doToggle);
}
function gatherUndoData() {
function doGatherUndoData( iPlot) {
tResult.push( {
movableLine: iPlot.movableLine ? iPlot.movableLine.createStorage() : null,
lsrlStorage: iPlot.multipleLSRLs ? iPlot.multipleLSRLs.createStorage() : null
});
}
var tResult = [];
doGatherUndoData( this_);
this_.get('siblingPlots').forEach( doGatherUndoData);
return tResult;
}
function restoreFromUndoData( iUndoData) {
function doRestoreFromUndoData( iPlot, iIndexMinusOne) {
var tUndoData = iUndoData[ iIndexMinusOne + 1];
if( iPlot.movableLine)
iPlot.movableLine.restoreStorage(tUndoData.movableLine);
if( iPlot.multipleLSRLs)
iPlot.multipleLSRLs.restoreStorage(tUndoData.lsrlStorage);
}
doRestoreFromUndoData( this_, -1);
this_.get('siblingPlots').forEach( doRestoreFromUndoData);
}
var willLock = (this.movableLine && !this.movableLine.get('isInterceptLocked')) ||
(this.multipleLSRLs && !this.multipleLSRLs.get('isInterceptLocked'));
DG.UndoHistory.execute(DG.Command.create({
name: "graph.toggleLockIntercept",
undoString: (willLock ? 'DG.Undo.graph.lockIntercept' : 'DG.Undo.graph.unlockIntercept'),
redoString: (willLock ? 'DG.Redo.graph.lockIntercept' : 'DG.Redo.graph.unlockIntercept'),
log: "lockIntercept: %@".fmt(willLock),
executeNotification: {
action: 'notify',
resource: 'component',
values: {
operation: 'toggle lock intercept',
type: 'DG.GraphView'
}
},
execute: function () {
this._undoData = gatherUndoData();
toggle();
},
undo: function () {
restoreFromUndoData( this._undoData);
this._undoData = null;
}
}));
},
/**
If we need to make a plotted function, do so. In any event toggle its visibility.
*/
togglePlotFunction: function () {
var this_ = this;
function toggle() {
function doToggle( iPlot) {
iPlot.toggleAdornmentVisibility('plottedFunction', 'togglePlotFunction');
}
this_.get('siblingPlots').forEach( doToggle);
doToggle( this_);
}
function connectFunctions() {
var tSiblingPlots = this_.get('siblingPlots'),
tMasterPlottedFunction = this_.getAdornmentModel('plottedFunction');
tMasterPlottedFunction.set('siblingPlottedFunctions',
tSiblingPlots.map( function( iPlot) {
return iPlot.getAdornmentModel( 'plottedFunction');
}));
}
var willShow = !this.isAdornmentVisible('plottedFunction');
DG.UndoHistory.execute(DG.Command.create({
name: "graph.togglePlotFunction",
undoString: (willShow ? 'DG.Undo.graph.showPlotFunction' : 'DG.Undo.graph.hidePlotFunction'),
redoString: (willShow ? 'DG.Redo.graph.showPlotFunction' : 'DG.Redo.graph.hidePlotFunction'),
log: "togglePlotFunction: %@".fmt(willShow ? "show" : "hide"),
executeNotification: {
action: 'notify',
resource: 'component',
values: {
operation: 'toggle plot function',
type: 'DG.GraphView'
}
},
execute: function () {
toggle();
connectFunctions();
},
undo: function () {
toggle();
this_.getAdornmentModel('plottedFunction').set('siblingPlottedFunctions', null);
}
}));
},
/**
If we need to make a connecting line, do so. In any event toggle its visibility.
*/
toggleConnectingLine: function () {
var this_ = this;
function toggle() {
function doToggle( iPlot) {
var tAdornModel = iPlot.toggleAdornmentVisibility('connectingLine', 'toggleConnectingLine');
if (tAdornModel && tAdornModel.get('isVisible'))
tAdornModel.recomputeValue(); // initialize
}
doToggle( this_);
this_.get('siblingPlots').forEach( doToggle);
}
var willShow = !this.isAdornmentVisible('connectingLine');
DG.UndoHistory.execute(DG.Command.create({
name: "graph.toggleConnectingLine",
undoString: (willShow ? 'DG.Undo.graph.showConnectingLine' : 'DG.Undo.graph.hideConnectingLine'),
redoString: (willShow ? 'DG.Redo.graph.showConnectingLine' : 'DG.Redo.graph.hideConnectingLine'),
log: "toggleConnectingLine: %@".fmt(willShow ? "show" : "hide"),
executeNotification: {
action: 'notify',
resource: 'component',
values: {
operation: 'toggle connecting line',
type: 'DG.GraphView'
}
},
execute: function () {
toggle();
},
undo: function () {
toggle();
}
}));
},
/**
* Toggle where the squares drawn from points to lines and functions are being shown
*/
toggleShowSquares: function () {
var this_ = this;
function toggle() {
function doToggle( iPlot) {
iPlot.set('areSquaresVisible', !iPlot.get('areSquaresVisible'));
}
doToggle( this_);
this_.get('siblingPlots').forEach( doToggle);
}
var willShow = !this.get('areSquaresVisible');
DG.UndoHistory.execute(DG.Command.create({
name: "graph.toggleShowSquares",
undoString: (willShow ? 'DG.Undo.graph.showSquares' : 'DG.Undo.graph.hideSquares'),
redoString: (willShow ? 'DG.Redo.graph.showSquares' : 'DG.Redo.graph.hideSquares'),
log: "toggleShowSquares: %@".fmt(willShow ? "show" : "hide"),
executeNotification: {
action: 'notify',
resource: 'component',
values: {
operation: 'toggle show squares',
type: 'DG.GraphView'
}
},
execute: function () {
toggle();
},
undo: function () {
toggle();
}
}));
},
handleDataConfigurationChange: function (iKey) {
sc_super();
this.rescaleAxesFromData(iKey !== 'hiddenCases', /* allow scale shrinkage */
true /* do animation */);
var adornmentModel = this.getAdornmentModel('connectingLine');
if (adornmentModel) {
adornmentModel.setComputingNeeded(); // invalidate if axis model/attribute change
}
},
/**
Each axis should rescale based on the values to be plotted with it.
@param{Boolean} Default is false
@param{Boolean} Default is true
@param{Boolean} Default is false
*/
rescaleAxesFromData: function (iAllowScaleShrinkage, iAnimatePoints, iLogIt, isUserAction) {
if (iAnimatePoints === undefined)
iAnimatePoints = true;
this.doRescaleAxesFromData([DG.GraphTypes.EPlace.eX, DG.GraphTypes.EPlace.eY, DG.GraphTypes.EPlace.eY2],
iAllowScaleShrinkage, iAnimatePoints, isUserAction);
if (iLogIt && !isUserAction)
DG.logUser("rescaleScatterplot");
},
/**
@param{ {x: {Number}, y: {Number} } }
@param{Number}
*/
dilate: function (iFixedPoint, iFactor) {
this.doDilation([DG.GraphTypes.EPlace.eX, DG.GraphTypes.EPlace.eY], iFixedPoint, iFactor);
},
/**
* Return a list of objects { key, class, useAdornmentModelsArray, storage }
* Subclasses should override calling sc_super first.
* @return {[Object]}
*/
getAdornmentSpecs: function() {
var tSpecs = sc_super(),
this_ = this;
['movablePoint', 'movableLine', 'multipleLSRLs'].forEach( function( iKey) {
var tAdorn = this_.get( iKey);
if (tAdorn)
tSpecs.push({
key: iKey,
"class": tAdorn.constructor,
useAdornmentModelsArray: false,
storage: tAdorn.createStorage()
});
});
DG.ObjectMap.forEach( this._adornmentModels, function( iKey, iAdorn) {
tSpecs.push( {
key: iKey,
"class": iAdorn.constructor,
useAdornmentModelsArray: true,
storage: iAdorn.createStorage()
});
});
return tSpecs;
},
/**
* Base class will do most of the work. We just have to finish up setting the axes.
* @param {DG.PlotModel} iSourcePlot
*/
installAdornmentModelsFrom: function( iSourcePlot) {
sc_super();
var tMovablePoint = this.get('movablePoint');
if (tMovablePoint) {
tMovablePoint.set('xAxis', this.get('xAxis'));
tMovablePoint.set('yAxis', this.get('yAxis'));
tMovablePoint.recomputeCoordinates(this.get('xAxis'), this.get('yAxis'));
}
var tMultipleLSRLs = this.get('multipleLSRLs');
if (tMultipleLSRLs) {
tMultipleLSRLs.recomputeSlopeAndInterceptIfNeeded(this.get('xAxis'), this.get('yAxis'));
}
},
checkboxDescriptions: function () {
var this_ = this;
return sc_super().concat([
{
title: 'DG.Inspector.graphConnectingLine',
value: this_.isAdornmentVisible('connectingLine'),
classNames: 'dg-graph-connectingLine-check'.w(),
valueDidChange: function () {
this_.toggleConnectingLine();
}.observes('value')
},
{
title: 'DG.Inspector.graphMovablePoint',
value: this_.get('isMovablePointVisible'),
classNames: 'dg-graph-movablePoint-check'.w(),
valueDidChange: function () {
this_.toggleMovablePoint();
}.observes('value')
},
{
title: 'DG.Inspector.graphMovableLine',
value: this_.get('isMovableLineVisible'),
classNames: 'dg-graph-movableLine-check'.w(),
valueDidChange: function () {
this_.toggleMovableLine();
}.observes('value')
},
{
title: 'DG.Inspector.graphLSRL',
value: this_.get('isLSRLVisible'),
classNames: 'dg-graph-lsrl-check'.w(),
valueDidChange: function () {
this_.toggleLSRLLine();
}.observes('value')
},
{
title: 'DG.Inspector.graphInterceptLocked',
classNames: 'dg-graph-interceptLocked-check'.w(),
_changeInProgress: true,
valueDidChange: function () {
if( !this._changeInProgress)
this_.toggleInterceptLocked();
}.observes('value'),
lineVisibilityChanged: function() {
this._changeInProgress = true;
var tLineIsVisible = this_.get('isMovableLineVisible') || this_.get('isLSRLVisible');
if( !tLineIsVisible)
this_.set('isInterceptLocked', false);
this.set('value', this_.get('isInterceptLocked'));
this.set('isEnabled', tLineIsVisible);
this._changeInProgress = false;
},
init: function() {
sc_super();
this.lineVisibilityChanged();
this_.addObserver('isMovableLineVisible', this, 'lineVisibilityChanged');
this_.addObserver('isLSRLVisible', this, 'lineVisibilityChanged');
this._changeInProgress = false;
},
destroy: function() {
this_.removeObserver('isMovableLineVisible', this, 'lineVisibilityChanged');
this_.removeObserver('isLSRLVisible', this, 'lineVisibilityChanged');
sc_super();
}
},
{
title: 'DG.Inspector.graphPlottedFunction',
value: this_.isAdornmentVisible('plottedFunction'),
classNames: 'dg-graph-plottedFunction-check'.w(),
valueDidChange: function () {
this_.togglePlotFunction();
}.observes('value')
},
{
title: 'DG.Inspector.graphPlottedValue',
value: this_.isAdornmentVisible('plottedValue'),
classNames: 'dg-graph-plottedValue-check'.w(),
valueDidChange: function () {
this_.togglePlotValue();
}.observes('value')
},
{
title: 'DG.Inspector.graphSquares',
value: this_.get('areSquaresVisible'),
classNames: 'dg-graph-squares-check'.w(),
lineVisibilityChanged: function() {
var tLineIsVisible = this_.get('isMovableLineVisible') || this_.get('isLSRLVisible');
this.set('isEnabled', tLineIsVisible);
if( this_.get('areSquaresVisible') && !tLineIsVisible)
this.set('value', false);
},
init: function() {
sc_super();
this.lineVisibilityChanged();
this_.addObserver('isMovableLineVisible', this, 'lineVisibilityChanged');
this_.addObserver('isLSRLVisible', this, 'lineVisibilityChanged');
},
destroy: function() {
this_.removeObserver('isMovableLineVisible', this, 'lineVisibilityChanged');
this_.removeObserver('isLSRLVisible', this, 'lineVisibilityChanged');
},
valueDidChange: function () {
this_.toggleShowSquares();
}.observes('value')
}
]);
}.property(),
/**
* When making a copy of a plot (e.g. for use in split) the returned object
* holds those properties that should be assigned to the copy.
* @return {{}}
*/
getPropsForCopy: function() {
var tResult = sc_super();
return $.extend( tResult, {
areSquaresVisible: this.get('areSquaresVisible')
});
},
/**
* @return { Object } with properties specific to a given subclass
*/
createStorage: function () {
var tStorage = sc_super(),
tMovablePoint = this.get('movablePoint'),
tMovableLine = this.get('movableLine'),
tLSRL = this.get('multipleLSRLs');
if (!SC.none(tMovablePoint))
tStorage.movablePointStorage = tMovablePoint.createStorage();
if (!SC.none(tMovableLine))
tStorage.movableLineStorage = tMovableLine.createStorage();
if (!SC.none(tLSRL) && tLSRL.get('isVisible'))
tStorage.multipleLSRLsStorage = tLSRL.createStorage();
if (this.get('areSquaresVisible'))
tStorage.areSquaresVisible = true;
if (this.get('isLSRLVisible'))
tStorage.isLSRLVisible = true;
return tStorage;
},
/**
* @param { Object } with properties specific to a given subclass
*/
restoreStorage: function (iStorage) {
/* Older documents stored adornments individually in the plot model
* that used them, e.g. movable lines and function plots were stored
* here with the scatter plot model. In newer documents, there is an
* 'adornments' property in the base class (plot model) which stores
* all or most of the adornments. To preserve file format compatibility
* we move the locally stored storage objects into the base class
* 'adornments' property where the base class will process them when
* we call sc_super().
*/
this.moveAdornmentStorage(iStorage, 'movableLine', iStorage.movableLineStorage);
this.moveAdornmentStorage(iStorage, 'multipleLSRLs', iStorage.multipleLSRLsStorage);
this.moveAdornmentStorage(iStorage, 'plottedFunction', iStorage.plottedFunctionStorage);
sc_super();
if (iStorage.movablePointStorage) {
if (SC.none(this.movablePoint))
this.createMovablePoint();
this.get('movablePoint').restoreStorage(iStorage.movablePointStorage);
}
if (iStorage.movableLineStorage) {
if (SC.none(this.movableLine))
this.createMovableLine();
this.get('movableLine').restoreStorage(iStorage.movableLineStorage);
}
this.areSquaresVisible = iStorage.areSquaresVisible;
if (iStorage.multipleLSRLsStorage) {
if (SC.none(this.multipleLSRLs))
this.createLSRLLines();
this.get('multipleLSRLs').restoreStorage(iStorage.multipleLSRLsStorage);
}
// Legacy document support
if (iStorage.plottedFunctionStorage) {
if (SC.none(this.plottedFunction))
this.set('plottedFunction', DG.PlottedFunctionModel.create());
this.get('plottedFunction').restoreStorage(iStorage.plottedFunctionStorage);
}
},
onRescaleIsComplete: function () {
if (!SC.none(this.movableLine))
this.movableLine.recomputeSlopeAndInterceptIfNeeded(this.get('xAxis'), this.get('yAxis'));
if (!SC.none(this.movablePoint))
this.movablePoint.recomputePositionIfNeeded(this.get('xAxis'), this.get('yAxis'));
},
/**
* Get an array of non-missing case counts in each axis cell.
* Also cell index on primary and secondary axis, with primary axis as major axis.
* @return {Array} [{count, primaryCell, secondaryCell},...] (all values are integers 0+).
*/
getCellCaseCounts: function ( iForSelectionOnly) {
var tCases = iForSelectionOnly ? this.get('selection') : this.get('cases'),
tXVarID = this.get('xVarID'),
tYVarID = this.get('yVarID'),
tCount = 0,
tValueArray = [];
if (!( tXVarID && tYVarID )) {
return tValueArray; // too early to recompute, caller must try again later.
}
// compute count and percent cases in each cell, excluding missing values
tCases.forEach(function (iCase, iIndex) {
var tXVal = iCase.getForcedNumericValue(tXVarID),
tYVal = iCase.getForcedNumericValue(tYVarID);
if (isFinite(tXVal) && isFinite(tYVal)) ++tCount;
});
// initialize the values for the single 'cell' of the scatterplot
var tCell = { primaryCell: 0, secondaryCell: 0 };
if( iForSelectionOnly)
tCell.selectedCount = tCount;
else
tCell.count = tCount;
tValueArray.push(tCell);
return tValueArray;
}
});
| Java |
const Koa = require('koa')
const screenshot = require('./screenshot')
const app = new Koa()
app.use(async ctx => {
var url = ctx.query.url
console.log('goto:', url)
if (!/^https?:\/\/.+/.test(url)) {
ctx.body = 'url 不合法'
} else {
if (!isNaN(ctx.query.wait)) {
ctx.query.wait = ~~ctx.query.wait
}
let data = await screenshot(url, ctx.query.wait, ~~ctx.query.width)
if (ctx.query.base64) {
ctx.body = 'data:image/jpeg;base64,' + data
} else {
ctx.body = `<img src="data:image/jpeg;base64,${data}" />`
}
}
})
app.listen(8000)
console.log('server start success at 8000')
// process.on('unCaughtException', function (err) {
// console.log(err)
// })
| Java |
// Test get machiens
var fs = require('fs');
try {
fs.accessSync('testdb.json', fs.F_OK);
fs.unlinkSync('testdb.json');
// Do something
} catch (e) {
// It isn't accessible
console.log(e);
}
var server = require('../server.js').createServer(8000, 'testdb.json');
var addTestMachine = function(name) {
var newMachine = {};
newMachine.name = name;
newMachine.type = 'washer';
newMachine.queue = [];
newMachine.operational = true;
newMachine.problemMessage = "";
newMachine.activeJob = {};
server.db('machines').push(newMachine);
}
describe('ALL THE TESTS LOL', function() {
it('should add a machine', function(done) {
var options = {
method: 'POST',
url: '/machines',
payload: {
name: 'test1',
type: 'washer'
}
}
server.inject(options, function(response) {
expect(response.statusCode).toBe(200);
var p = JSON.parse(response.payload);
expect(p.name).toBe(options.payload.name);
expect(p.type).toBe(options.payload.type);
done();
})
});
it('should get all machines', function(done) {
var name = 'testMachine';
var name2 = 'anotherMachine';
addTestMachine(name);
addTestMachine(name2);
var options = {
method: 'GET',
url: '/machines',
}
server.inject(options, function(res) {
expect(res.statusCode).toBe(200);
var p = JSON.parse(res.payload);
// check p has test and anotherMachine
done();
});
});
it('should get one machine', function(done) {
var name = 'sweetTestMachine';
addTestMachine(name);
var options = {
method: 'GET',
url: '/machines/'+name
};
server.inject(options, function(res) {
expect(res.statusCode).toBe(200);
var p = JSON.parse(res.payload);
expect(p.name).toBe(name);
done();
});
});
it('should add a job the queue then th queue should have the person', function(done) {
addTestMachine('queueTest');
var addOptions = {
method: 'POST',
url: '/machines/queueTest/queue',
payload: {
user: 'test@mail.com',
pin: 1234,
minutes: 50
}
};
server.inject(addOptions, function(res) {
expect(res.statusCode).toBe(200);
var p = JSON.parse(res.payload);
expect(p.name).toBe('queueTest');
var getQueue = {
method: 'GET',
url: '/machines/queueTest/queue'
};
server.inject(getQueue, function(newRes) {
expect(newRes.statusCode).toBe(200);
var q = JSON.parse(newRes.payload);
console.log(q);
expect(q.queue[0].user).toBe('test@mail.com');
expect(q.queue[0].pin).toBe(1234);
done();
})
})
});
it('should delete a job from the queue', function(done) {
addTestMachine('anotherQueue');
var addOptions = {
method: 'POST',
url: '/machines/anotherQueue/queue',
payload: {
user: 'test@mail.com',
pin: 1235,
minutes: 50
}
};
server.inject(addOptions, function(res) {
var deleteOptions = addOptions;
deleteOptions.url = '/machines/anotherQueue/queue/delete';
deleteOptions.payload = {
user: addOptions.payload.user,
pin: addOptions.payload.pin
}
server.inject(deleteOptions, function(r) {
expect(r.statusCode).toBe(200);
console.log(JSON.parse(r.payload));
done();
})
})
})
it('should add a job to the active queue', function(done) {
addTestMachine('activeQueue');
var addOptions = {
method: 'POST',
url: '/machines/activeQueue/queue',
payload: {
user: 'test@mail.com',
pin: 1235,
minutes: 50
}
};
server.inject(addOptions, function(r) {
var runJobOptions = {
method: 'POST',
url: '/machines/activeQueue/queue/start',
payload: {
command: 'next',
pin: 1235,
minutes: 0
}
};
server.inject(runJobOptions, function(res) {
expect(res.statusCode).toBe(200);
done();
})
})
});
}); | Java |
require "administrate/field/base"
class EnumField < Administrate::Field::Base
def to_s
data
end
end
| Java |
require('./loader.jsx');
| Java |
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Public Class PaintToolBar
'¦¹Ãþ§O©w¸qÃö©ó¤u¨ã¦C¥~Æ[¤Î¦æ¬°
Inherits PaintWithRegistry
Protected ToolBarCommand As Integer = 7 '¨Ï¥ÎªÌ¤u¨ã¦C©R¥O¿ï¾Ü
Protected LastCommand As Integer '¤W¤@Ó©R¥O
Protected pnToolbar As Panel '¤u¨ã¦C
Protected radbtnToolbar(15) As NoFocusRadbtn '¤u¨ã¦C¥\¯à
Sub New()
'¤u¨ã¦C«Øºc¤¸
Dim tx, coly, sy As Integer
If bToolbar Then tx = 60 Else tx = 0
If bColorbar Then coly = 50 Else coly = 0
If bStatusbar Then sy = 22 Else sy = 0
pnToolbar = New Panel
With pnToolbar
.Parent = Me
.BorderStyle = BorderStyle.None
.Location = New Point(0, 0)
.Size = New Size(60, ClientSize.Height - coly - sy)
End With
Dim TotTool As New ToolTip
Dim strTotTool() As String = {"¿ï¾Ü¥ô·N½d³ò", "¿ï¾Ü", "¾ó¥ÖÀ¿/±m¦â¾ó¥ÖÀ¿", "¶ñ¤J¦â±m", _
"¬D¿ïÃC¦â", "©ñ¤jÃè", "¹]µ§", "¯»¨ê", "¼Qºj", "¤å¦r", _
"ª½½u", "¦±½u", "¯x§Î", "¦hÃä§Î", "¾ò¶ê§Î", "¶ê¨¤¯x§Î"}
Dim i, cx As Integer
For i = 0 To 15
radbtnToolbar(i) = New NoFocusRadbtn
With radbtnToolbar(i)
.Name = (i + 1).ToString
.Parent = pnToolbar
.Appearance = Appearance.Button
.Size = New Size(26, 26)
.Image = New Bitmap(Me.GetType(), "toolbutton" & (i + 1).ToString & ".bmp")
If (i + 1) Mod 2 <> 0 Then cx = 3 Else cx = 29
.Location = New Point(cx, (i \ 2) * 26)
End With
TotTool.SetToolTip(radbtnToolbar(i), strTotTool(i))
AddHandler radbtnToolbar(i).MouseEnter, AddressOf ToolbarHelp
AddHandler radbtnToolbar(i).MouseLeave, AddressOf ToolbarHelpLeave
AddHandler radbtnToolbar(i).Click, AddressOf ToolbarRadbtnSelect
Next i
radbtnToolbar(6).Checked = True
pnWorkarea.Cursor = New Cursor(Me.GetType(), "Pen.cur")
End Sub
Protected Overrides Sub FormSizeChanged(ByVal obj As Object, ByVal ea As EventArgs)
'©w¸q¦]µøÄ±¤¸¥óÅܧó(¤u¨ã¦C,¦â¶ô°Ï)¤u¨ã¦C®y¼Ð°t¸m
MyBase.FormSizeChanged(obj, ea)
Dim tx, cy, sy As Integer
If bColorbar Then cy = 50 Else cy = 0
If bStatusbar Then sy = 22 Else sy = 0
pnToolbar.Size = New Size(60, ClientSize.Height - cy - sy)
End Sub
Protected Overridable Sub ToolbarHelp(ByVal obj As Object, ByVal ea As EventArgs)
'·í·Æ¹«²¾¦Ü¤u¨ã¦C¤¸¥ó¤W®É,Åã¥Ü¸Ó¤¸¥ó¦bª¬ºA¦Cªº¸ê°T.¥Ñ PaintStatusbar Âмg
End Sub
Protected Overridable Sub ToolbarHelpLeave(ByVal obj As Object, ByVal ea As EventArgs)
'·í·Æ¹«²¾¥X¤u¨ã¦C¤¸¥ó®É,Åã¥Ü¸Ó¤¸¥ó¦bª¬ºA¦Cªº¸ê°T.¥Ñ PaintStatusbar Âмg
End Sub
Protected Overridable Sub ToolbarRadbtnSelect(ByVal obj As Object, ByVal ea As EventArgs)
'©w¸q·í¨Ï¥ÎªÌ¿ï¾Ü¤u¨ã¦C¤¸¥ó®É,©Ò²£¥Íªº¦æ¬°
Dim radbtnSelect As NoFocusRadbtn = DirectCast(obj, NoFocusRadbtn)
LastCommand = ToolBarCommand '¨ú±o¤W¤@Ó¥\¯à
ToolBarCommand = CInt(radbtnSelect.Name) '¨ú±o¨Ï¥ÎªÌ©Ò¿ï¾Üªº¥\¯à
Dim CursorName As String
Select Case ToolBarCommand
Case 1, 2, 10, 11, 12, 13, 14, 15, 16
CursorName = "Cross.cur"
Case 3
CursorName = "Null.cur"
Case 4
CursorName = "FillColor.cur"
Case 5
CursorName = "Color.cur"
Case 6
CursorName = "ZoomSet.cur"
Case 7
CursorName = "Pen.cur"
Case 8
CursorName = "Brush.cur"
Case 9
CursorName = "Spray.cur"
End Select
pnWorkarea.Cursor = New Cursor(Me.GetType(), CursorName)
'³o¨ì¥Ø«e¬°¤î,¶È©w¸q¤F,¹ïÀ³©óø¹Ï¤u§@°Ïªº¹C¼ÐÅã¥Ü,¥Dnªº±±¨î¬yµ{,¥Ñ OverridesÂмg
End Sub
End Class
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.