code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
<?php
declare(strict_types=1);
namespace ShlinkMigrations;
use Doctrine\DBAL\Exception;
use Doctrine\DBAL\Platforms\MySQLPlatform;
use Doctrine\DBAL\Platforms\SqlitePlatform;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\SchemaException;
use Doctrine\Migrations\AbstractMigration;
use function is_subclass_of;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20160819142757 extends AbstractMigration
{
/**
* @throws Exception
* @throws SchemaException
*/
public function up(Schema $schema): void
{
$platformClass = $this->connection->getDatabasePlatform();
$table = $schema->getTable('short_urls');
$column = $table->getColumn('short_code');
match (true) {
is_subclass_of($platformClass, MySQLPlatform::class) => $column
->setPlatformOption('charset', 'utf8mb4')
->setPlatformOption('collation', 'utf8mb4_bin'),
is_subclass_of($platformClass, SqlitePlatform::class) => $column->setPlatformOption('collate', 'BINARY'),
default => null,
};
}
public function down(Schema $schema): void
{
// Nothing to roll back
}
public function isTransactional(): bool
{
return ! ($this->connection->getDatabasePlatform() instanceof MySQLPlatform);
}
}
| Java |
my personal site
| Java |
<?php
namespace RectorPrefix20210615;
if (\class_exists('Tx_Extbase_Property_TypeConverter_AbstractFileFolderConverter')) {
return;
}
class Tx_Extbase_Property_TypeConverter_AbstractFileFolderConverter
{
}
\class_alias('Tx_Extbase_Property_TypeConverter_AbstractFileFolderConverter', 'Tx_Extbase_Property_TypeConverter_AbstractFileFolderConverter', \false);
| Java |
;(function() {
angular.module('app.core')
.config(config);
/* @ngInject */
function config($stateProvider, $locationProvider, $urlRouterProvider) {
$stateProvider
/**
* @name landing
* @type {route}
* @description First page for incoming users, and for default routing
* for all failed routes.
*/
.state('landing', {
url: '/',
templateUrl: '/html/modules/landing/landing.html',
controller: 'LandingController',
controllerAs: 'vm'
})
/**
* @name home
* @type {route}
* @description User landing page, the main display.
*/
.state('home', {
url: '',
abstract: true,
views: {
'': {
templateUrl: 'html/modules/home/template.html'
},
'current-routes@home': {
templateUrl: 'html/modules/layout/current-routes.html',
controller: 'CurrentRoutesController',
controllerAs: 'vm'
},
'add-routes@home': {
templateUrl: 'html/modules/layout/add-routes.html',
controller: 'AddRoutesController',
controllerAs: 'vm'
}
}
})
.state('home.home', {
url: '/home',
authenticate: true,
views: {
'container@home': {
templateUrl: 'html/modules/home/welcome.html'
}
}
})
.state('home.new-route', {
url: '/new-route/:route',
authenticate: true,
views: {
'container@home': {
templateUrl: 'html/modules/routes/new-route.html',
controller: 'NewRouteController',
controllerAs: 'vm'
}
}
})
/**
* @name editRoute
* @type {route}
* @description View for editing a specific route. Provides options
* to edit or delete the route.
*/
.state('home.edit-route', {
url: '/routes/{route:.*}',
authenticate: true,
views: {
'container@home': {
templateUrl: '/html/modules/routes/edit-routes.html',
controller: 'EditRoutesController',
controllerAs: 'vm',
}
}
})
/**
* @name Docs
* @type {route}
* @description View for the project documentation
*
*/
.state('docs',{
url:'',
abstract: true,
views: {
'': {
templateUrl: '/html/modules/docs/docs.html'
},
'doc-list@docs': {
templateUrl: '/html/modules/docs/docs-list.html',
controller: 'DocsController',
controllerAs: 'vm'
}
}
})
.state('docs.docs', {
url: '/docs',
views: {
'container@docs': {
templateUrl: '/html/modules/docs/current-doc.html'
}
}
})
.state('docs.current-doc', {
url: '/docs/:doc',
views: {
'container@docs': {
templateUrl: function($stateParams) {
return '/html/modules/docs/pages/' + $stateParams.doc + '.html';
}
}
}
})
.state('home.analytics', {
url: '/analytics/{route:.*}',
authenticate: true,
views: {
'container@home': {
templateUrl: '/html/modules/analytics/analytics.html',
controller: 'AnalyticsController',
controllerAs: 'vm'
}
}
});
// default uncaught routes to landing page
$urlRouterProvider.otherwise('/');
// enable HTML5 mode
$locationProvider.html5Mode(true);
}
}).call(this);
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
namespace CommonTypes
{
/// <summary>
/// BrokerSite hides the replication in a site making the calls transparent.
/// </summary>
[Serializable]
public class BrokerSiteFrontEnd : IBroker
{
private string siteName;
private List<BrokerPairDTO> brokersAlive;
public BrokerSiteFrontEnd(ICollection<BrokerPairDTO> brokers,string siteName)
{
this.brokersAlive = brokers.ToList();
this.siteName = siteName;
}
private void RemoveCrashedBrokers(string brokerName)
{
lock (this)
{
foreach (BrokerPairDTO pair in brokersAlive)
{
if (pair.LogicName.Equals(brokerName))
{
brokersAlive.Remove(pair);
break;
}
}
}
}
private BrokerPairDTO[] GetCopy()
{
lock (this)
{
return brokersAlive.ToArray();
}
}
public void Diffuse(Event e)
{
BrokerPairDTO[] brokers = GetCopy();
foreach (BrokerPairDTO pair in brokers)
{
try
{
(Activator.GetObject(typeof(IBroker), pair.Url) as IBroker).Diffuse(e);
}
catch (Exception)
{
RemoveCrashedBrokers(pair.LogicName);
}
}
}
public void AddRoute(Route route)
{
BrokerPairDTO[] brokers = GetCopy();
foreach (BrokerPairDTO pair in brokers)
{
try
{
(Activator.GetObject(typeof(IBroker), pair.Url) as IBroker).AddRoute(route);
}
catch (Exception e)
{
RemoveCrashedBrokers(pair.LogicName);
Console.WriteLine(e);
}
}
}
public void RemoveRoute(Route route)
{
BrokerPairDTO[] brokers = GetCopy();
foreach (BrokerPairDTO pair in brokers)
{
try
{
(Activator.GetObject(typeof(IBroker), pair.Url) as IBroker).RemoveRoute(route);
}
catch (Exception)
{
RemoveCrashedBrokers(pair.LogicName);
}
}
}
public void Subscribe(Subscription subscription)
{
BrokerPairDTO[] brokers = GetCopy();
foreach (BrokerPairDTO pair in brokers)
{
try
{
(Activator.GetObject(typeof(IBroker), pair.Url) as IBroker).Subscribe(subscription);
}
catch (Exception)
{
RemoveCrashedBrokers(pair.LogicName);
}
}
}
public void Unsubscribe(Subscription subscription)
{
BrokerPairDTO[] brokers = GetCopy();
foreach (BrokerPairDTO pair in brokers)
{
try
{
(Activator.GetObject(typeof(IBroker), pair.Url) as IBroker).Unsubscribe(subscription);
}
catch (Exception)
{
RemoveCrashedBrokers(pair.LogicName);
}
}
}
public void Sequence(Bludger bludger)
{
BrokerPairDTO[] brokers = GetCopy();
foreach (BrokerPairDTO pair in brokers)
{
try
{
(Activator.GetObject(typeof(IBroker), pair.Url) as IBroker).Sequence(bludger);
}
catch (Exception)
{
RemoveCrashedBrokers(pair.LogicName);
}
}
}
public void Bludger(Bludger bludger)
{
BrokerPairDTO[] brokers = GetCopy();
foreach (BrokerPairDTO pair in brokers)
{
try
{
(Activator.GetObject(typeof(IBroker), pair.Url) as IBroker).Bludger(bludger);
}
catch (Exception)
{
RemoveCrashedBrokers(pair.LogicName);
}
}
}
public override string ToString()
{
lock (this)
{
string res = siteName + " :" + Environment.NewLine;
foreach (BrokerPairDTO dto in brokersAlive)
{
res += dto.ToString() + Environment.NewLine;
}
return res;
}
}
}
}
| Java |
import Route from '@ember/routing/route';
import { A } from '@ember/array';
import { hash } from 'rsvp';
import EmberObject from '@ember/object'
export default Route.extend({
model: function() {
return hash({
exampleModel: EmberObject.create(),
disableSubmit: false,
selectedLanguage: null,
selectOptions: A([
{label: 'French', value: 'fr'},
{label: 'English', value: 'en'},
{label: 'German', value: 'gr'}
]),
radioOptions: A([
{label: 'Ruby', value: 'ruby'},
{label: 'Javascript', value: 'js'},
{label: 'Cold Fusion', value: 'cf'}
])
});
},
actions: {
submit: function() {
window.alert('You triggered a form submit!');
},
toggleErrors: function() {
var model = this.get('currentModel').exampleModel;
if(model.get('errors')) {
model.set('errors', null);
}else{
var errors = {
first_name: A(['That first name is wrong']),
last_name: A(['That last name is silly']),
language: A(['Please choose a better language']),
isAwesome: A(['You must be awesome to submit this form']),
bestLanguage: A(['Wrong, Cold Fusion is the best language']),
essay: A(['This essay is not very good'])
};
model.set('errors', errors);
}
},
toggleSelectValue: function() {
if(this.get('currentModel.exampleModel.language')) {
this.set('currentModel.exampleModel.language', null);
}else{
this.set('currentModel.exampleModel.language', 'fr');
}
},
toggleSubmit: function() {
if(this.get('currentModel.disableSubmit')) {
this.set('currentModel.disableSubmit', false);
}else{
this.set('currentModel.disableSubmit', true);
}
},
toggleCheckbox: function() {
if(this.get('currentModel.exampleModel.isAwesome')) {
this.set('currentModel.exampleModel.isAwesome', false);
} else {
this.set('currentModel.exampleModel.isAwesome', true);
}
},
toggleRadio: function() {
if(this.get('currentModel.exampleModel.bestLanguage')) {
this.set('currentModel.exampleModel.bestLanguage', null);
}else{
this.set('currentModel.exampleModel.bestLanguage', 'js');
}
}
}
});
| Java |
import lowerCaseFirst from 'lower-case-first';
import {handles} from 'marty';
import Override from 'override-decorator';
function addHandlers(ResourceStore) {
const {constantMappings} = this;
return class ResourceStoreWithHandlers extends ResourceStore {
@Override
@handles(constantMappings.getMany.done)
getManyDone(payload) {
super.getManyDone(payload);
this.hasChanged();
}
@Override
@handles(constantMappings.getSingle.done)
getSingleDone(payload) {
super.getSingleDone(payload);
this.hasChanged();
}
@handles(
constantMappings.postSingle.done,
constantMappings.putSingle.done,
constantMappings.patchSingle.done
)
changeSingleDone(args) {
// These change actions may return the inserted or modified object, so
// update that object if possible.
if (args.result) {
this.getSingleDone(args);
}
}
};
}
function addFetch(
ResourceStore,
{
actionsKey = `${lowerCaseFirst(this.name)}Actions`
}
) {
const {methodNames, name, plural} = this;
const {getMany, getSingle} = methodNames;
const refreshMany = `refresh${plural}`;
const refreshSingle = `refresh${name}`;
return class ResourceStoreWithFetch extends ResourceStore {
getActions() {
return this.app[actionsKey];
}
[getMany](options, {refresh} = {}) {
return this.fetch({
id: `c${this.collectionKey(options)}`,
locally: () => this.localGetMany(options),
remotely: () => this.remoteGetMany(options),
refresh
});
}
[refreshMany](options) {
return this[getMany](options, {refresh: true});
}
localGetMany(options) {
return super[getMany](options);
}
remoteGetMany(options) {
return this.getActions()[getMany](options);
}
[getSingle](id, options, {refresh} = {}) {
return this.fetch({
id: `i${this.itemKey(id, options)}`,
locally: () => this.localGetSingle(id, options),
remotely: () => this.remoteGetSingle(id, options),
refresh
});
}
[refreshSingle](id, options) {
return this[getSingle](id, options, {refresh: true});
}
localGetSingle(id, options) {
return super[getSingle](id, options);
}
remoteGetSingle(id, options) {
return this.getActions()[getSingle](id, options);
}
fetch({refresh, ...options}) {
if (refresh) {
const baseLocally = options.locally;
options.locally = function refreshLocally() {
if (refresh) {
refresh = false;
return undefined;
} else {
return this::baseLocally();
}
};
}
return super.fetch(options);
}
};
}
export default function extendStore(
ResourceStore,
{
useFetch = true,
...options
}
) {
ResourceStore = this::addHandlers(ResourceStore, options);
if (useFetch) {
ResourceStore = this::addFetch(ResourceStore, options);
}
return ResourceStore;
}
| Java |
<?php
namespace proyecto\backendBundle\Entity;
/**
* Entidad Respuesta
* @author Javier Burguillo Sánchez
*/
class Respuesta
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $respuesta;
/**
* @var \proyecto\backendBundle\Entity\Subpregunta
*/
private $idSubpregunta;
/**
* @var \proyecto\backendBundle\Entity\Participante
*/
private $idParticipante;
/**
* Obtener id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Establecer respuesta
*
* @param string
* @return Respuesta
*/
public function setRespuesta($respuesta)
{
$this->respuesta = $respuesta;
return $this;
}
/**
* Obtener respuesta
*
* @return string
*/
public function getRespuesta()
{
return $this->respuesta;
}
/**
* Establecer idSubpregunta
*
* @param \proyecto\backendBundle\Entity\Subpregunta
* @return Respuesta
*/
public function setIdSubpregunta(\proyecto\backendBundle\Entity\Subpregunta $idSubpregunta = null)
{
$this->idSubpregunta = $idSubpregunta;
return $this;
}
/**
* Obtener idSubpregunta
*
* @return \proyecto\backendBundle\Entity\Subpregunta
*/
public function getIdSubpregunta()
{
return $this->idSubpregunta;
}
/**
* Establecer idParticipante
*
* @param \proyecto\backendBundle\Entity\Participante
* @return Respuesta
*/
public function setIdParticipante(\proyecto\backendBundle\Entity\Participante $idParticipante = null)
{
$this->idParticipante = $idParticipante;
return $this;
}
/**
* Obtener idParticipante
*
* @return \proyecto\backendBundle\Entity\Participante
*/
public function getIdParticipante()
{
return $this->idParticipante;
}
} | Java |
$('.js-toggle-menu').click(function(e){
e.preventDefault();
$(this).siblings().toggle();
});
$('.nav--primary li').click(function(){
$(this).find('ul').toggleClass('active');
});
| Java |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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 org.spongepowered.common.mixin.core.network;
import io.netty.channel.Channel;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.local.LocalAddress;
import net.minecraft.network.NetworkManager;
import org.spongepowered.api.MinecraftVersion;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.common.SpongeMinecraftVersion;
import org.spongepowered.common.bridge.network.NetworkManagerBridge;
import org.spongepowered.common.util.Constants;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import javax.annotation.Nullable;
@SuppressWarnings("rawtypes")
@Mixin(NetworkManager.class)
public abstract class NetworkManagerMixin extends SimpleChannelInboundHandler implements NetworkManagerBridge {
@Shadow private Channel channel;
@Shadow public abstract SocketAddress getRemoteAddress();
@Nullable private InetSocketAddress impl$virtualHost;
@Nullable private MinecraftVersion impl$version;
@Override
public InetSocketAddress bridge$getAddress() {
final SocketAddress remoteAddress = getRemoteAddress();
if (remoteAddress instanceof LocalAddress) { // Single player
return Constants.Networking.LOCALHOST;
}
return (InetSocketAddress) remoteAddress;
}
@Override
public InetSocketAddress bridge$getVirtualHost() {
if (this.impl$virtualHost != null) {
return this.impl$virtualHost;
}
final SocketAddress local = this.channel.localAddress();
if (local instanceof LocalAddress) {
return Constants.Networking.LOCALHOST;
}
return (InetSocketAddress) local;
}
@Override
public void bridge$setVirtualHost(final String host, final int port) {
try {
this.impl$virtualHost = new InetSocketAddress(InetAddress.getByAddress(host,
((InetSocketAddress) this.channel.localAddress()).getAddress().getAddress()), port);
} catch (UnknownHostException e) {
this.impl$virtualHost = InetSocketAddress.createUnresolved(host, port);
}
}
@Override
public MinecraftVersion bridge$getVersion() {
return this.impl$version;
}
@Override
public void bridge$setVersion(final int version) {
this.impl$version = new SpongeMinecraftVersion(String.valueOf(version), version);
}
}
| Java |
function solve(message) {
let tagValidator = /^<message((?:\s+[a-z]+="[A-Za-z0-9 .]+"\s*?)*)>((?:.|\n)+?)<\/message>$/;
let tokens = tagValidator.exec(message);
if (!tokens) {
console.log("Invalid message format");
return;
}
let [match, attributes, body] = tokens;
let attributeValidator = /\s+([a-z]+)="([A-Za-z0-9 .]+)"\s*?/g;
let sender = '';
let recipient = '';
let attributeTokens = attributeValidator.exec(attributes);
while (attributeTokens) {
if (attributeTokens[1] === 'to') {
recipient = attributeTokens[2];
} else if (attributeTokens[1] === 'from') {
sender = attributeTokens[2];
}
attributeTokens = attributeValidator.exec(attributes);
}
if (sender === '' || recipient === '') {
console.log("Missing attributes");
return;
}
body = body.replace(/\n/g, '</p>\n <p>');
let html = `<article>\n <div>From: <span class="sender">${sender}</span></div>\n`;
html += ` <div>To: <span class="recipient">${recipient}</span></div>\n`;
html += ` <div>\n <p>${body}</p>\n </div>\n</article>`;
console.log(html);
}
solve(`<message from="John Doe" to="Alice">Not much, just chillin. How about you?</message>`);
/*
solve( `<message to="Bob" from="Alice" timestamp="1497254092">Hey man, what's up?</message>`,
`<message from="Ivan Ivanov" to="Grace">Not much, just chillin. How about you?</message>`
);
*/ | Java |
"""
Tests for a door card.
"""
import pytest
from onirim import card
from onirim import component
from onirim import core
from onirim import agent
class DoorActor(agent.Actor):
"""
"""
def __init__(self, do_open):
self._do_open = do_open
def open_door(self, content, door_card):
return self._do_open
DRAWN_CAN_NOT_OPEN = (
card.Color.red,
False,
component.Content(
undrawn_cards=[],
hand=[card.key(card.Color.blue)]),
component.Content(
undrawn_cards=[],
hand=[card.key(card.Color.blue)],
limbo=[card.door(card.Color.red)]),
)
DRAWN_DO_NOT_OPEN = (
card.Color.red,
False,
component.Content(
undrawn_cards=[],
hand=[card.key(card.Color.red)]),
component.Content(
undrawn_cards=[],
hand=[card.key(card.Color.red)],
limbo=[card.door(card.Color.red)]),
)
DRAWN_DO_OPEN = (
card.Color.red,
True,
component.Content(
undrawn_cards=[],
hand=[
card.key(card.Color.red),
card.key(card.Color.red),
card.key(card.Color.red),
]),
component.Content(
undrawn_cards=[],
discarded=[card.key(card.Color.red)],
hand=[card.key(card.Color.red), card.key(card.Color.red)],
opened=[card.door(card.Color.red)]),
)
DRAWN_DO_OPEN_2 = (
card.Color.red,
True,
component.Content(
undrawn_cards=[],
hand=[
card.key(card.Color.blue),
card.key(card.Color.red),
]),
component.Content(
undrawn_cards=[],
discarded=[card.key(card.Color.red)],
hand=[card.key(card.Color.blue)],
opened=[card.door(card.Color.red)]),
)
DRAWN_CASES = [
DRAWN_CAN_NOT_OPEN,
DRAWN_DO_NOT_OPEN,
DRAWN_DO_OPEN,
DRAWN_DO_OPEN_2,
]
@pytest.mark.parametrize(
"color, do_open, content, content_after",
DRAWN_CASES)
def test_drawn(color, do_open, content, content_after):
door_card = card.door(color)
door_card.drawn(core.Core(DoorActor(do_open), agent.Observer(), content))
assert content == content_after
| Java |
/*
**==============================================================================
**
** Copyright (c) 2003, 2004, 2005, 2006, Michael Brasher, Karl Schopmeyer
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and associated documentation files (the "Software"),
** to deal in the Software without restriction, including without limitation
** the rights to use, copy, modify, merge, publish, distribute, sublicense,
** and/or sell copies of the Software, and to permit persons to whom the
** Software is furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in
** all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE.
**
**==============================================================================
*/
#include "OS.h"
int OS::close(Sock sock)
{
int result;
SF_RESTART(::close(sock), result);
return result;
}
| Java |
'use strict';
const test = require('ava');
const hashSet = require('../index');
const MySet = hashSet(x => x);
test('should not change empty set', t => {
const set = new MySet();
set.clear();
t.is(set.size, 0);
});
test('should clear set', t => {
const set = new MySet();
set.add(1);
set.clear();
t.is(set.size, 0);
});
| Java |
Unframed XHR
===
Extends the `Unframed` prototype with five methods.
One to send any XHR request to a url that is not yet busy for this application, eventually set a tieout and a callback or emit an application event on response.
~~~
xhrSend(method, url, headers, body, timeout, callback)
~~~
And four conveniences for the most common form of HTTP request:
~~~
xhrGetText(url, query, headers, timeout, callback)
xhrPostForm(url, form, timeout, callback)
xhrGetJson(url, query, timeout, callback)
xhrPostJson(url, request, timeout, callback)
~~~
These methods provide an API to send GET and POST requests to all type of web resources, with a minimum of conveniences for JSON, HTML and XML.
And by failing if the `url` requested is already busy, these methods force their applications to avoid concurrent requests to the same network resource.
Synopsis
---
If the URL requested is not busy for `myapp`, send a GET request for a JSON resource.
~~~javascript
myapp.xhrGetJson('hello.php');
~~~
Or send a query along, as a map of arguments.
~~~javascript
myapp.xhrGetJson('hello.php', {'n': 'World'});
~~~
Since `callback(status, message)` was left undefined an application event will be emitted on response.
For instance, on success.
~~~
200 GET hello.php {"who": "World"}
~~~
To POST a JSON body instead, do.
~~~javascript
myapp.xhrPostJson('greetings.php', {'who': 'World'});
~~~
Note that `xhrSend`, `xhrGetText`, `xhrPostForm`, `xhrGetJSON` and `xhrPostJson` methods maintain a table of busy URLs and prevent concurrent requests to the same resource. | Java |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2019_08_01
module Models
#
# Response for ListBastionHosts API service call.
#
class BastionHostListResult
include MsRestAzure
include MsRest::JSONable
# @return [Array<BastionHost>] List of Bastion Hosts in a resource group.
attr_accessor :value
# @return [String] URL to get the next set of results.
attr_accessor :next_link
# return [Proc] with next page method call.
attr_accessor :next_method
#
# Gets the rest of the items for the request, enabling auto-pagination.
#
# @return [Array<BastionHost>] operation results.
#
def get_all_items
items = @value
page = self
while page.next_link != nil && !page.next_link.strip.empty? do
page = page.get_next_page
items.concat(page.value)
end
items
end
#
# Gets the next page of results.
#
# @return [BastionHostListResult] with next page content.
#
def get_next_page
response = @next_method.call(@next_link).value! unless @next_method.nil?
unless response.nil?
@next_link = response.body.next_link
@value = response.body.value
self
end
end
#
# Mapper for BastionHostListResult class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'BastionHostListResult',
type: {
name: 'Composite',
class_name: 'BastionHostListResult',
model_properties: {
value: {
client_side_validation: true,
required: false,
serialized_name: 'value',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'BastionHostElementType',
type: {
name: 'Composite',
class_name: 'BastionHost'
}
}
}
},
next_link: {
client_side_validation: true,
required: false,
serialized_name: 'nextLink',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| Java |
### This script fetches level-1 PACS imaging data, using a list generated by the
### archive (in the CSV format), attaches sky coordinates and masks to them
### (by calling the convertL1ToScanam task) and save them to disk in the correct
### format for later use by Scanamorphos.
### See important instructions below.
#######################################################
### This script is part of the Scanamorphos package.
### HCSS is free software: you can redistribute it and/or modify
### it under the terms of the GNU Lesser General Public License as
### published by the Free Software Foundation, either version 3 of
### the License, or (at your option) any later version.
#######################################################
## Import classes and definitions:
import os
from herschel.pacs.spg.phot import ConvertL1ToScanamTask
#######################################################
## local settings:
dir_root = "/pcdisk/stark/aribas/Desktop/modeling_TDs/remaps_Cha/PACS/scanamorphos/"
path = dir_root +"L1/"
### number of observations:
n_obs = 2
#######################################################
## Do a multiple target search in the archive and use the "save all results as CSV" option.
## --> ascii table 'results.csv' where lines can be edited
## (suppress unwanted observations and correct target names)
## Create the directories contained in the dir_out variables (l. 57)
## before running this script.
#######################################################
## observations:
table_obs = asciiTableReader(file=dir_root+'results_fast.csv', tableType='CSV', skipRows=1)
list_obsids = table_obs[0].data
list_names = table_obs[1].data
for i_obs in range(n_obs):
##
num_obsid = list_obsids[i_obs]
source = list_names[i_obs]
source = str.lower(str(source))
dir_out = path+source+"_processed_obsids"
# create directory if it does not exist
if not(os.path.exists(dir_out)):
os.system('mkdir '+dir_out)
##
print ""
print "Downloading obsid " + `num_obsid`
obs = getObservation(num_obsid, useHsa=True, instrument="PACS", verbose=True)
###
frames = obs.level1.refs["HPPAVGR"].product.refs[0].product
convertL1ToScanam(frames, cancelGlitch=1, assignRaDec=1, outDir=dir_out)
###
frames = obs.level1.refs["HPPAVGB"].product.refs[0].product
convertL1ToScanam(frames, cancelGlitch=1, assignRaDec=1, outDir=dir_out)
### END OF SCRIPT
#######################################################
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sim908Connect.Lib.Constants
{
internal class CommandFormats
{
internal const string AT_CGSNBASE = "AT+CGSN";
internal const string ATE = "ATE";
internal const string AT_CFUN = "AT_CFUN";
}
}
| Java |
/**
@file std_streambuf.h
@brief suppresses warnings in streambuf.
@author HRYKY
@version $Id: std_streambuf.h 337 2014-03-23 14:12:33Z hryky.private@gmail.com $
*/
#ifndef STD_STREAMBUF_H_20140323003904693
#define STD_STREAMBUF_H_20140323003904693
#include "hryky/pragma.h"
#pragma hryky_pragma_push_warning
# include <streambuf>
#pragma hryky_pragma_pop_warning
//------------------------------------------------------------------------------
// defines macros
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// declares types
//------------------------------------------------------------------------------
namespace hryky
{
} // namespace hryky
//------------------------------------------------------------------------------
// declares classes
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// declares global functions
//------------------------------------------------------------------------------
namespace hryky
{
} // namespace hryky
//------------------------------------------------------------------------------
// defines global functions
//------------------------------------------------------------------------------
#endif // STD_STREAMBUF_H_20140323003904693
// end of file
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<title>SendMessage</title>
<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="SendMessage";
}
//-->
</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="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../nxt/http/PlaceBidOrder.html" title="class in nxt.http"><span class="strong">Prev Class</span></a></li>
<li><a href="../../nxt/http/SendMoney.html" title="class in nxt.http"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?nxt/http/SendMessage.html" target="_top">Frames</a></li>
<li><a href="SendMessage.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">nxt.http</div>
<h2 title="Class SendMessage" class="title">Class SendMessage</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>nxt.http.SendMessage</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public final class <span class="strong">SendMessage</span>
extends java.lang.Object</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= 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="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../nxt/http/PlaceBidOrder.html" title="class in nxt.http"><span class="strong">Prev Class</span></a></li>
<li><a href="../../nxt/http/SendMoney.html" title="class in nxt.http"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?nxt/http/SendMessage.html" target="_top">Frames</a></li>
<li><a href="SendMessage.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Java |
'use strict';
const path = require('path');
const jwt = require('jsonwebtoken');
const AuthConfig = require(path.resolve('./config')).Auth;
const jwtSecret = AuthConfig.jwt.secret;
const tokenExpirePeriod = AuthConfig.jwt.tokenExpirePeriod;
function generateToken(payLoad) {
const isObject = (typeof payLoad === 'object');
if (payLoad) {
if (isObject) {
return new Promise((resolve, reject) => {
jwt.sign(payLoad, jwtSecret, { expiresIn: tokenExpirePeriod }, (error, token) => {
if (error) {
reject(error);
} else {
resolve(token);
}
});
})
} else {
const error = new TypeError('Token Payload Must Be An Object');
return Promise.reject(error);
}
} else {
const error = new Error('Token Payload Should Not Be Empty');
return Promise.reject(error);
}
}
function verifyToken(token) {
if (token) {
return new Promise((resolve, reject) => {
jwt.verify(token, jwtSecret, (error, decodedToken) => {
if (error) {
reject(error);
} else {
resolve(decodedToken);
}
});
})
} else {
const error = new Error('Token Should Not Be Empty');
return Promise.reject(error);
}
}
module.exports = {
generate: generateToken,
verify: verifyToken
};
| Java |
html {
background-color: white;
}
ul{
display: inline-block;
}
.listone{
margin-left: 75px;
}
.listtwo{
margin-left: 50px;
}
li{
margin-bottom: 10px;
}
p{
font-size: 10px;
margin:0px;
}
h1 p{
text-align: center;
font-weight: bold;
}
h1{
border-bottom: 1px solid black;
padding-bottom: 10px;
}
div{
border-bottom: 1px solid black;
padding-bottom: 20px;
padding-top: 20px;
text-align: center;
}
/*
Reflect
What is important to know when linking an external file (like a stylesheet) to an HTML file?
What tricks did you use to help you with positioning? How hard was it to get the site as you wanted it?
What CSS did you use to modify the element style (like size, color, etc.)
Did you modify the HTML to include classes or ids? If so, which did you choose and why? If you didn't, how would you know which one to add to your HTML?
When you compared your site to the actual code base, which do you think had cleaner code that followed best practices and why?
*/ | Java |
//
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: android/libcore/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Enumerated.java
//
#ifndef _OrgApacheHarmonySecurityAsn1ASN1Enumerated_H_
#define _OrgApacheHarmonySecurityAsn1ASN1Enumerated_H_
#include "J2ObjC_header.h"
#include "org/apache/harmony/security/asn1/ASN1Primitive.h"
@class OrgApacheHarmonySecurityAsn1BerInputStream;
@class OrgApacheHarmonySecurityAsn1BerOutputStream;
/*!
@author Stepan M. Mishura
@version $Revision$
*/
/*!
@brief This class represents ASN.1 Enumerated type.
*/
@interface OrgApacheHarmonySecurityAsn1ASN1Enumerated : OrgApacheHarmonySecurityAsn1ASN1Primitive
#pragma mark Public
/*!
@brief Constructs ASN.1 Enumerated type
The constructor is provided for inheritance purposes
when there is a need to create a custom ASN.1 Enumerated type.
To get a default implementation it is recommended to use
getInstance() method.
*/
- (instancetype)init;
- (id)decodeWithOrgApacheHarmonySecurityAsn1BerInputStream:(OrgApacheHarmonySecurityAsn1BerInputStream *)inArg;
- (void)encodeContentWithOrgApacheHarmonySecurityAsn1BerOutputStream:(OrgApacheHarmonySecurityAsn1BerOutputStream *)outArg;
/*!
@brief Extracts array of bytes from BER input stream.
@return array of bytes
*/
- (id)getDecodedObjectWithOrgApacheHarmonySecurityAsn1BerInputStream:(OrgApacheHarmonySecurityAsn1BerInputStream *)inArg;
/*!
@brief Returns ASN.1 Enumerated type default implementation
The default implementation works with encoding
that is represented as byte array.
@return ASN.1 Enumerated type default implementation
*/
+ (OrgApacheHarmonySecurityAsn1ASN1Enumerated *)getInstance;
- (void)setEncodingContentWithOrgApacheHarmonySecurityAsn1BerOutputStream:(OrgApacheHarmonySecurityAsn1BerOutputStream *)outArg;
@end
J2OBJC_STATIC_INIT(OrgApacheHarmonySecurityAsn1ASN1Enumerated)
FOUNDATION_EXPORT void OrgApacheHarmonySecurityAsn1ASN1Enumerated_init(OrgApacheHarmonySecurityAsn1ASN1Enumerated *self);
FOUNDATION_EXPORT OrgApacheHarmonySecurityAsn1ASN1Enumerated *new_OrgApacheHarmonySecurityAsn1ASN1Enumerated_init() NS_RETURNS_RETAINED;
FOUNDATION_EXPORT OrgApacheHarmonySecurityAsn1ASN1Enumerated *OrgApacheHarmonySecurityAsn1ASN1Enumerated_getInstance();
J2OBJC_TYPE_LITERAL_HEADER(OrgApacheHarmonySecurityAsn1ASN1Enumerated)
#endif // _OrgApacheHarmonySecurityAsn1ASN1Enumerated_H_
| Java |
<!-- START REVOLUTION SLIDER 5.0 -->
<div id="slider_container" class="rev_slider_wrapper">
<div id="rev-slider" class="rev_slider" data-version="5.0">
<ul>
<li data-transition="slideremovedown">
<!-- MAIN IMAGE -->
<img src="<?php echo $this->common->theme_link(); ?>img/slider/revolution/slider01.jpg" alt="" width="1920" height="600">
<!-- LAYER NR. 1 -->
<div class="tp-caption captionHeadline3 text-shadow"
id="slide-51-layer-1"
data-x="['left','left','left','left']" data-hoffset="['80','80','80','80']"
data-y="['top','top','top','top']" data-voffset="['180','180','180','180']"
data-width="504"
data-height="133"
data-whitespace="normal"
data-transform_idle="o:1;"
data-transform_in="y:[100%];z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;s:1500;e:Power3.easeInOut;"
data-transform_out="y:[100%];s:1000;s:1000;"
data-mask_in="x:0px;y:0px;s:inherit;e:inherit;"
data-mask_out="x:inherit;y:inherit;s:inherit;e:inherit;"
data-start="500"
data-splitin="none"
data-splitout="none"
data-responsive_offset="on"
style="z-index: 5; white-space: normal;">
Lulusan dijamin Kerja
</div>
<!-- LAYER NR. 2 -->
<div class="tp-caption captionButtonlink"
id="slide-400-layer-3"
data-x="['left','left','left','left']" data-hoffset="['85','85','85','85']"
data-y="['top','top','top','top']" data-voffset="['355','355','355','355']"
data-width="['auto','auto','auto','auto']"
data-height="['auto','auto','auto','auto']"
data-transform_idle="o:1;"
data-transform_in="x:right;s:2000;e:Power4.easeInOut;"
data-transform_out="s:1000;e:Power2.easeInOut;s:1000;e:Power2.easeInOut;"
data-start="700"
data-splitin="none"
data-splitout="none"
data-responsive_offset="on"
style="z-index: 6; white-space: nowrap;"><a href="#" class="btn btn-primary btn-icon">Learn more <i class="fa fa-link"></i></a>
</div>
<!-- <div class="tp-caption"
id="slide-400-layer-4"
data-x="['right','right','right','right']" data-hoffset="['200','200','150','200']"
data-y="['bottom','bottom','bottom','bottom']" data-voffset="['0','0','0','0']"
data-transform_idle="o:1;"
data-transform_in="y:[100%];z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;s:1500;e:Power3.easeInOut;"
data-transform_out="y:[100%];s:1000;s:1000;"
data-start="2500"
data-splitin="none"
data-splitout="none"
data-responsive_offset="on"
style="z-index: 6; white-space: nowrap;">
<img src="<?php echo $this->common->theme_link(); ?>img/slider/revolution/workerno1.png" class="img-Construction" width="400" alt="">
</div> -->
</li>
<li data-transition="slideremovedown">
<!-- MAIN IMAGE -->
<img src="<?php echo $this->common->theme_link(); ?>img/slider/revolution/slider02.jpg" alt="" width="1920" height="600">
<!-- LAYER NR. 1 -->
<div class="tp-caption captionHeadline3 text-shadow"
id="slide-51-layer-1"
data-x="['left','left','left','left']" data-hoffset="['80','80','80','80']"
data-y="['top','top','top','top']" data-voffset="['180','180','180','180']"
data-width="700"
data-height="133"
data-whitespace="normal"
data-transform_idle="o:1;"
data-transform_in="y:[100%];z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;s:1500;e:Power3.easeInOut;"
data-transform_out="y:[100%];s:1000;s:1000;"
data-mask_in="x:0px;y:0px;s:inherit;e:inherit;"
data-mask_out="x:inherit;y:inherit;s:inherit;e:inherit;"
data-start="500"
data-splitin="none"
data-splitout="none"
data-responsive_offset="on"
style="z-index: 5; white-space: normal;">
Fasilitas belajar lengkap
</div>
<!-- LAYER NR. 2 -->
<div class="tp-caption captionButtonlink"
id="slide-400-layer-3"
data-x="['left','left','left','left']" data-hoffset="['85','85','85','85']"
data-y="['top','top','top','top']" data-voffset="['355','355','355','355']"
data-width="['auto','auto','auto','auto']"
data-height="['auto','auto','auto','auto']"
data-transform_idle="o:1;"
data-transform_in="x:right;s:2000;e:Power4.easeInOut;"
data-transform_out="s:1000;e:Power2.easeInOut;s:1000;e:Power2.easeInOut;"
data-start="700"
data-splitin="none"
data-splitout="none"
data-responsive_offset="on"
style="z-index: 6; white-space: nowrap;"><a href="#" class="btn btn-primary btn-icon">Learn more <i class="fa fa-link"></i></a>
</div>
<div class="tp-caption"
id="slide-400-layer-4"
data-x="['right','right','right','right']" data-hoffset="['200','200','150','200']"
data-y="['bottom','bottom','bottom','bottom']" data-voffset="['0','0','0','0']"
data-transform_idle="o:1;"
data-transform_in="y:[100%];z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;s:1500;e:Power3.easeInOut;"
data-transform_out="y:[100%];s:1000;s:1000;"
data-start="2500"
data-splitin="none"
data-splitout="none"
data-responsive_offset="on"
style="z-index: 6; white-space: nowrap;">
<img src="<?php echo $this->common->theme_link(); ?>img/slider/revolution/fitur01.png" class="img-Construction" width="400" alt="">
</div>
</li>
<li data-transition="slideremovedown">
<!-- MAIN IMAGE -->
<img src="<?php echo $this->common->theme_link(); ?>img/slider/revolution/slider03.jpg" alt="" width="1920" height="600">
<!-- LAYER NR. 1 -->
<div class="tp-caption captionHeadline3 text-shadow"
id="slide-51-layer-1"
data-x="['left','left','left','left']" data-hoffset="['80','80','80','80']"
data-y="['top','top','top','top']" data-voffset="['180','180','180','180']"
data-width="700"
data-height="133"
data-whitespace="normal"
data-transform_idle="o:1;"
data-transform_in="y:[100%];z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;s:1500;e:Power3.easeInOut;"
data-transform_out="y:[100%];s:1000;s:1000;"
data-mask_in="x:0px;y:0px;s:inherit;e:inherit;"
data-mask_out="x:inherit;y:inherit;s:inherit;e:inherit;"
data-start="500"
data-splitin="none"
data-splitout="none"
data-responsive_offset="on"
style="z-index: 5; white-space: normal;">
Agen Langsung Cruiseline
</div>
<!-- LAYER NR. 2 -->
<div class="tp-caption captionButtonlink"
id="slide-400-layer-3"
data-x="['left','left','left','left']" data-hoffset="['85','85','85','85']"
data-y="['top','top','top','top']" data-voffset="['355','355','355','355']"
data-width="['auto','auto','auto','auto']"
data-height="['auto','auto','auto','auto']"
data-transform_idle="o:1;"
data-transform_in="x:right;s:2000;e:Power4.easeInOut;"
data-transform_out="s:1000;e:Power2.easeInOut;s:1000;e:Power2.easeInOut;"
data-start="700"
data-splitin="none"
data-splitout="none"
data-responsive_offset="on"
style="z-index: 6; white-space: nowrap;"><a href="#" class="btn btn-primary btn-icon">Learn more <i class="fa fa-link"></i></a>
</div>
<div class="tp-caption"
id="slide-400-layer-4"
data-x="['right','right','right','right']" data-hoffset="['200','200','150','200']"
data-y="['bottom','bottom','bottom','bottom']" data-voffset="['0','0','0','0']"
data-transform_idle="o:1;"
data-transform_in="y:[100%];z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;s:1500;e:Power3.easeInOut;"
data-transform_out="y:[100%];s:1000;s:1000;"
data-start="2500"
data-splitin="none"
data-splitout="none"
data-responsive_offset="on"
style="z-index: 6; white-space: nowrap;">
<img src="<?php echo $this->common->theme_link(); ?>img/slider/revolution/fitur02.png" class="img-Construction" width="400" alt="">
</div>
</li>
</ul>
</div><!-- END REVOLUTION SLIDER -->
</div>
<!-- END OF SLIDER WRAPPER -->
<!-- Start contain wrapp -->
<div class="contain-wrapp gray-container padding-clear margin-mintop85 feature-Construction">
<div class="container">
<div class="icon-wrapp">
<div class="icon-boxline">
<i class="fa fa-home fa-3x fa-primary"></i>
<h5>Lulusan Dijamin Siap Kerja</h5>
<p>
Dengan dididik dan dilatih oleh instruktur berpengalaman luas di dalam dan luar negeri serta didukung oleh sarana yang lengkap serya kurikulum yang up to date dalam menjamin lulusan bosssignalfx siap kerja.
</p>
</div>
<div class="icon-boxline">
<i class="fa fa-wrench fa-3x fa-primary"></i>
<h5>Recruitmen Supporting Cruiseline</h5>
<p>
Poltenkas Denpasar adalah salah satu kampus yang ditunjuk sebagai Rekruitmen Supporting Partner untuk Royal Carribean Cruiseline, Carnival Cruiseline, dan MSC Cruiseline.
</p>
</div>
<div class="icon-boxline">
<i class="fa fa-group fa-3x fa-primary"></i>
<h5>Pendidikan Berkualitas dengan Harga Terjangkau</h5>
<p>
Dengan biaya kuliah yang terjangkau dan transparan. bosssignalfx mampu memberikan pendidikan bermutu tinggi dan tambahan keahlian seperti Fruit Carving, Bar Flair, Barista, Winecology, Banquet Service, Pastry Bakery, Event Organizer, E-Commerce.
</p>
</div>
</div>
</div>
</div>
<!-- End contain wrapp -->
<div class="clearfix"></div>
<!-- Start contain wrapp -->
<div class="contain-wrapp gray-container padding-bot40">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="section-heading">
<h3>Build Your Future with Us!</h3>
<p>Doctus salutatus est ea, postea doming veritus in nec, sanctus fierent antiopam no pro</p>
<i class="fa fa-rocket"></i>
</div>
</div>
</div>
<div class="row marginbot30">
<div class="col-md-8 col-md-offset-2 text-center">
<p>
Quod assum persecuti ne eum. Et eam paulo menandri dissentiet. Mei eu altera offendit accusamus. Mel te sint verear deseruisse, cu graece disputando quo. Zril putent mel et, eam quot accusam ea. Quo voluptatibus signiferumque te, in partem argumentum honestatis duo.
</p>
<p><a href="#" class="btn btn-default">View our profile</a> <a href="#" class="btn btn-primary">View our services</a></p>
</div>
</div>
<div class="row">
<div class="col-md-10 col-md-offset-1 text-center">
<img src="<?php echo $this->common->theme_link(); ?>img/group.png" class="img-responsive" alt="" />
<div class="divider margintop-clear"></div>
</div>
</div>
<div class="row">
<div class="col-md-3 col-sm-6">
<div class="col-icon centered">
<i class="fa fa-tablet fa-2x icon-circle icon-bordered"></i>
<h5>Responsive</h5>
<p>
Cu nec salutandi voluptat teros definitionem ad ius, ut eam unumiunanios.
</p>
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="col-icon centered">
<i class="fa fa-magic fa-2x icon-circle icon-bordered"></i>
<h5>Clean</h5>
<p>
Cu nec salutandi voluptat teros definitionem ad ius, ut eam unumiunanios.
</p>
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="col-icon centered">
<i class="fa fa-flask fa-2x icon-circle icon-bordered"></i>
<h5>Bootstrap3</h5>
<p>
Cu nec salutandi voluptat teros definitionem ad ius, ut eam unumiunanios.
</p>
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="col-icon centered">
<i class="fa fa-code fa-2x icon-circle icon-bordered"></i>
<h5>Valid code</h5>
<p>
Cu nec salutandi voluptat teros definitionem ad ius, ut eam unumiunanios.
</p>
</div>
</div>
</div>
</div>
</div>
<!-- End contain wrapp -->
<div class="clearfix"></div>
<!-- Start contain wrapp -->
<div id="portfolio" class="contain-wrapp paddingbot-clear">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="section-heading">
<h3>Galeri Kami</h3>
<p>Adhuc doming placerat sea ut, graeci perfecto scriptorem nam</p>
<i class="fa fa-image"></i>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<!-- Start gallery filter -->
<ul class="filter-items">
<li><a href="#" data-filter="" class="active">All</a></li>
<li><a href="#" data-filter="web">Kampus Activity</a></li>
<li><a href="#" data-filter="graphic">Fasilitas</a></li>
<li><a href="#" data-filter="logo">Belajar Mengajar</a></li>
</ul>
<!-- End gallery filter -->
</div>
</div>
</div>
<!-- Start Images Gallery -->
<div class="fullwidth">
<div id="gallery" class="masonry gallery">
<div class="grid-sizer col-md-3 col-sm-6 col-xs-6"></div>
<!-- Start Gallery 01 -->
<div data-filter="web" class="grid-item col-md-3 col-sm-6 col-xs-6">
<div class="img-wrapper">
<div class="img-caption capZoomIn">
<a href="img/gallery/zoom980x980.jpg" data-pretty="prettyPhoto" class="zoomer"><i class="fa fa-search"></i></a>
<h5><a href="portfolio-detail.html">Vituperatoribus</a></h5>
<a href="#" class="img-categorie">Web design</a>
</div>
<img src="<?php echo $this->common->theme_link(); ?>img/gallery/380x380/img13.jpg" class="img-fullwidth" alt="" />
</div>
</div>
<!-- End Gallery 01 -->
<!-- Star Gallery 02 -->
<div data-filter="graphic" class="grid-item col-md-3 col-sm-6 col-xs-6">
<div class="img-wrapper">
<div class="img-caption capZoomIn">
<a href="img/gallery/zoom980x980.jpg" data-pretty="prettyPhoto" class="zoomer"><i class="fa fa-search"></i></a>
<h5><a href="portfolio-detail.html">Vituperatoribus</a></h5>
<a href="#" class="img-categorie">Web design</a>
</div>
<img src="<?php echo $this->common->theme_link(); ?>img/gallery/380x380/img14.jpg" class="img-fullwidth" alt="" />
</div>
</div>
<!-- End Gallery 02 -->
<!-- Start Gallery 03 -->
<div data-filter="app" class="grid-item col-md-3 col-sm-6 col-xs-6">
<div class="img-wrapper">
<div class="img-caption capZoomIn">
<a href="img/gallery/zoom980x980.jpg" data-pretty="prettyPhoto" class="zoomer"><i class="fa fa-search"></i></a>
<h5><a href="portfolio-detail.html">Persequeris</a></h5>
<a href="#" class="img-categorie">App design</a>
</div>
<img src="<?php echo $this->common->theme_link(); ?>img/gallery/380x380/img15.jpg" class="img-fullwidth" alt="" />
</div>
</div>
<!-- End Gallery 03 -->
<!-- Start Gallery 04 -->
<div data-filter="logo" class="grid-item col-md-3 col-sm-6 col-xs-6">
<div class="img-wrapper">
<div class="img-caption capZoomIn">
<a href="img/gallery/zoom980x980.jpg" data-pretty="prettyPhoto" class="zoomer"><i class="fa fa-search"></i></a>
<h5><a href="portfolio-detail.html">An ancillae</a></h5>
<a href="#" class="img-categorie">logo design</a>
</div>
<img src="<?php echo $this->common->theme_link(); ?>img/gallery/380x380/img16.jpg" class="img-fullwidth" alt="" />
</div>
</div>
<!-- End Gallery 04 -->
<!-- Start Gallery 05 -->
<div data-filter="logo" class="grid-item col-md-3 col-sm-6 col-xs-6">
<div class="img-wrapper">
<div class="img-caption capZoomIn">
<a href="img/gallery/zoom980x980.jpg" data-pretty="prettyPhoto" class="zoomer"><i class="fa fa-search"></i></a>
<h5><a href="portfolio-detail.html">Viris copiosae</a></h5>
<a href="#" class="img-categorie">logo design</a>
</div>
<img src="<?php echo $this->common->theme_link(); ?>img/gallery/380x380/img17.jpg" class="img-fullwidth" alt="" />
</div>
</div>
<!-- End Gallery 05 -->
<!-- Start Gallery 06 -->
<div data-filter="web" class="grid-item col-md-3 col-sm-6 col-xs-6">
<div class="img-wrapper">
<div class="img-caption capZoomIn">
<a href="img/gallery/zoom980x980.jpg" data-pretty="prettyPhoto" class="zoomer"><i class="fa fa-search"></i></a>
<h5><a href="portfolio-detail.html">Reprimique</a></h5>
<a href="#" class="img-categorie">Web design</a>
</div>
<img src="<?php echo $this->common->theme_link(); ?>img/gallery/380x380/img18.jpg" class="img-fullwidth" alt="" />
</div>
</div>
<!-- End Gallery 06 -->
<!-- Start Gallery 07 -->
<div data-filter="graphic" class="grid-item col-md-3 col-sm-6 col-xs-6">
<div class="img-wrapper">
<div class="img-caption capZoomIn">
<a href="img/gallery/zoom980x980.jpg" data-pretty="prettyPhoto" class="zoomer"><i class="fa fa-search"></i></a>
<h5><a href="portfolio-detail.html">Simul labitur</a></h5>
<a href="#" class="img-categorie">Graphic design</a>
</div>
<img src="<?php echo $this->common->theme_link(); ?>img/gallery/380x380/img19.jpg" class="img-fullwidth" alt="" />
</div>
</div>
<!-- End Gallery 07 -->
<!-- Start Gallery 08 -->
<div data-filter="app" class="grid-item col-md-3 col-sm-6 col-xs-6">
<div class="img-wrapper">
<div class="img-caption capZoomIn">
<a href="img/gallery/zoom980x980.jpg" data-pretty="prettyPhoto" class="zoomer"><i class="fa fa-search"></i></a>
<h5><a href="portfolio-detail.html">Consetetur</a></h5>
<a href="#" class="img-categorie">App design</a>
</div>
<img src="<?php echo $this->common->theme_link(); ?>img/gallery/380x380/img20.jpg" class="img-fullwidth" alt="" />
</div>
</div>
<!-- End Gallery 08 -->
</div>
<div class="row">
<div class="col-md-12">
<a href="portfolio-alt1.html" class="btn btn-primary btn-lg btn-block">View more Gallery</a>
</div>
</div>
</div>
<!-- End Images Gallery -->
<!-- End contain wrapp -->
<div class="clearfix"></div>
<!-- Start parallax -->
<div class="parallax parallax-two bg3">
<div class="parallax-container padding-bot30">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2 owl-column-wrapp">
<div id="testimoni" class="owl-carousel">
<div class="item">
<div class="testimoni-single">
<blockquote class="centered">
Kemampuan Alumni bosssignalfx Dalam Bekerja Tidak Perlu Diragukan Lagi Karena Selain Cekatan Juga Fast Learner, Saya Mencari Staf Yang Seperti Itu Dan Itulah Yang Dibutuhkan Industri Saat Ini.
</blockquote>
<span class="block"><a href="#">Tusan Aryasa</a> - Housekeeper Estate Como Shambhala Executive </span>
<img src="<?php echo $this->common->theme_link(); ?>img/testimoni/tusan.jpg" class="img-circle testimoni-avatar" alt="" />
</div>
</div>
<div class="item">
<div class="testimoni-single">
<blockquote class="centered">
Saya Merekomendasi bosssignalfx Sebagai Tempat Anda Kuliah Perhotelan Karena Terbukti Dari Mahasiswa Yang On The Job Training Di Tempat Kami Menunjukkan Sikap Yang Loyal & Hardworker.
</blockquote>
<span class="block"><a href="#">Sukarmajaya</a> - Executive Chef The Villas, Seminyak </span>
<img src="<?php echo $this->common->theme_link(); ?>img/testimoni/sukarmajaya.jpg" class="img-circle testimoni-avatar" alt="" />
</div>
</div>
<div class="item">
<div class="testimoni-single">
<blockquote class="centered">
Dari Berbagai Kampus Yang Mahasiswanya On The Job Trainng Di Tempat Kami bosssignalfx Selalu Memberikan Mahasiswa Yang Terbaik Dalam Hal Disiplin & Teamwork. Thank’s bosssignalfx.
</blockquote>
<span class="block"><a href="#">Ni Made Restiti</a> - Personnel Manager UN'S Hotel & Restaurant, Legian - Kuta</span>
<img src="<?php echo $this->common->theme_link(); ?>img/testimoni/restiti.jpg" class="img-circle testimoni-avatar" alt="" />
</div>
</div>
<div class="item">
<div class="testimoni-single">
<blockquote class="centered">
Saya Ucapkan Terima Kasih Yang Banyak Kepada bosssignalfx Yang Telah Memberikan Tenaga Training Handal Dan Cepat Beradaptasi Dengan Pola Kerja High Speed Di Beach Club Kami. </blockquote>
<span class="block"><a href="#"> I Made Dwi Artha Pradnya</a> - Asst. Restaurant Manager Potato Head Beach Club Seminyak- Kuta</span>
<img src="<?php echo $this->common->theme_link(); ?>img/testimoni/dwi.jpg" class="img-circle testimoni-avatar" alt="" />
</div>
</div>
<div class="item">
<div class="testimoni-single">
<blockquote class="centered">
bosssignalfx Selalu Mensupport Untuk Tenaga Training Di Hotel Kami, Kami Pilih bosssignalfx Karena Tenaganya Siap Pakai, Disiplin & Memiliki Positive Attitude. </blockquote>
<span class="block"><a href="#">I Made Wirta</a> - Executive Housekeeper Amarterra Villas Bali By Accor, Nusa Dua</span>
<img src="<?php echo $this->common->theme_link(); ?>img/testimoni/wirta.jpg" class="img-circle testimoni-avatar" alt="" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- End parallax -->
<div class="clearfix"></div>
<!-- Start cta primary -->
<div class="cta-wrapper cta-primary">
<div class="container">
<div class="row">
<div class="col-md-12">
<h4>Ayo Daftar Sekarang</h4>
<p>Mari bergabung dengan ratusan alumni lain.</p>
<a class="btn" href="#">Daftar Sekarang!</a>
</div>
</div>
</div>
</div>
<!-- End cta primary -->
<div class="clearfix"></div>
| Java |
<?php
namespace AppBundle\Form;
use AppBundle\AppBundle;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ProductType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('price')
->add('productType')
;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Product'
));
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_product';
}
}
| Java |
---
layout: post
date: 2016-10-16
title: "Sherri Hill Prom Dresses Style 32176 Sleeveless Sweep/Brush Train Aline/Princess"
category: Sherri Hill
tags: [Sherri Hill ,Sherri Hill,Aline/Princess ,Strapless,Sweep/Brush Train,Sleeveless]
---
### Sherri Hill Prom Dresses Style 32176
Just **$399.99**
### Sleeveless Sweep/Brush Train Aline/Princess
<table><tr><td>BRANDS</td><td>Sherri Hill</td></tr><tr><td>Silhouette</td><td>Aline/Princess </td></tr><tr><td>Neckline</td><td>Strapless</td></tr><tr><td>Hemline/Train</td><td>Sweep/Brush Train</td></tr><tr><td>Sleeve</td><td>Sleeveless</td></tr></table>
<a href="https://www.readybrides.com/en/sherri-hill-/50396-sherri-hill-prom-dresses-style-32176.html"><img src="//img.readybrides.com/116196/sherri-hill-prom-dresses-style-32176.jpg" alt="Sherri Hill Prom Dresses Style 32176" style="width:100%;" /></a>
<!-- break --><a href="https://www.readybrides.com/en/sherri-hill-/50396-sherri-hill-prom-dresses-style-32176.html"><img src="//img.readybrides.com/116195/sherri-hill-prom-dresses-style-32176.jpg" alt="Sherri Hill Prom Dresses Style 32176" style="width:100%;" /></a>
Buy it: [https://www.readybrides.com/en/sherri-hill-/50396-sherri-hill-prom-dresses-style-32176.html](https://www.readybrides.com/en/sherri-hill-/50396-sherri-hill-prom-dresses-style-32176.html)
| Java |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from conans.model import Generator
from conans.client.generators import VisualStudioGenerator
from xml.dom import minidom
from conans.util.files import load
class VisualStudioMultiGenerator(Generator):
template = """<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets" >
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<ItemDefinitionGroup />
<ItemGroup />
</Project>
"""
@property
def filename(self):
pass
@property
def content(self):
configuration = str(self.conanfile.settings.build_type)
platform = {'x86': 'Win32', 'x86_64': 'x64'}.get(str(self.conanfile.settings.arch))
vsversion = str(self.settings.compiler.version)
# there is also ClCompile.RuntimeLibrary, but it's handling is a bit complicated, so skipping for now
condition = " '$(Configuration)' == '%s' And '$(Platform)' == '%s' And '$(VisualStudioVersion)' == '%s' "\
% (configuration, platform, vsversion + '.0')
name_multi = 'conanbuildinfo_multi.props'
name_current = ('conanbuildinfo_%s_%s_%s.props' % (configuration, platform, vsversion)).lower()
multi_path = os.path.join(self.output_path, name_multi)
if os.path.isfile(multi_path):
content_multi = load(multi_path)
else:
content_multi = self.template
dom = minidom.parseString(content_multi)
import_node = dom.createElement('Import')
import_node.setAttribute('Condition', condition)
import_node.setAttribute('Project', name_current)
import_group = dom.getElementsByTagName('ImportGroup')[0]
children = import_group.getElementsByTagName("Import")
for node in children:
if name_current == node.getAttribute("Project") and condition == node.getAttribute("Condition"):
break
else:
import_group.appendChild(import_node)
content_multi = dom.toprettyxml()
content_multi = "\n".join(line for line in content_multi.splitlines() if line.strip())
vs_generator = VisualStudioGenerator(self.conanfile)
content_current = vs_generator.content
return {name_multi: content_multi, name_current: content_current}
| Java |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class M_slider extends Main_model {
function __construct() {
parent::__construct();
$this->table = array(
'name' => 'tbl_slider',
'coloumn' => array(
'slider_id' => array('id'=>'slider_id', 'label'=>'ID', 'idkey'=>true, 'visible'=>false, 'field_visible'=>true, 'format'=>'HIDDEN'),
'slider_name' => array('id'=>'slider_name', 'label'=>'Slider Name', 'idkey'=>false, 'visible'=>true, 'field_visible'=>true, 'format'=>'TEXT'),
'slider_publish' => array('id'=>'slider_publish', 'label'=>'Date Publish', 'idkey'=>false, 'visible'=>true, 'field_visible'=>true, 'format'=>'TEXT'),
'slider_expire' => array('id'=>'slider_expire', 'label'=>'Date Expired', 'idkey'=>false, 'visible'=>true, 'field_visible'=>true, 'format'=>'TEXT'),
'slider_images' => array('id'=>'slider_images', 'label'=>'Image', 'idkey'=>false, 'visible'=>false, 'field_visible'=>true, 'format'=>'FILE'),
),
'join' =>array(
),
'where' => array(),
'keys' => 'slider_id',
'option_name' => ''
);
}
function fields()
{
$data = array();
return $data;
}
function getlist($params)
{
$list = $this->getListData($params);
$nomor = $params['start'];
$data['records'] = array();
foreach($list['records']->result() as $row):
$actions = '';
$actions .= '<a data-id="'.$row->slider_id.'" data-target="form_modal_slider" data-toggle="modal" class="btn btn-xs btn-success btn-editable"><i class="glyphicon glyphicon-edit"></i>Ubah</a>';
$actions .= '<a data-id="'.$row->slider_id.'" class="btn btn-xs btn-danger btn-removable"><i class="glyphicon glyphicon-trash"></i>Hapus</a>';
$data['records'][] = array(
$nomor+1,
$row->slider_name,
$row->slider_publish,
$row->slider_expire,
$actions
);
$nomor++;
endforeach;
$data['total'] = $list['total'];
$data['total_filter'] = $list['total_filter'];
return $data;
}
} | Java |
# Digits
- [Data source](https://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits)
- Train dataset: Samples: 3823 Attributes: 65
- Test dataset: Samples: 1,797 Attributes: 65
- Dont use first column
- Target column: last column (class 0-9)
- Additional preprocessing needed: feature scaling
| Java |
package org.katlas.JavaKh.rows;
import org.katlas.JavaKh.utils.RedBlackIntegerTree;
public class RedBlackIntegerMap<F> extends RedBlackIntegerTree<F> implements MatrixRow<F> {
/**
*
*/
private static final long serialVersionUID = 5885667469881867107L;
public void compact() {
}
public void putLast(int key, F f) {
put(key, f);
}
@Override
public void put(int key, F value) {
if(value == null) {
remove(key);
} else {
super.put(key, value);
}
}
}
| Java |
---
title: DataCite Member Mailing List Subscription
layout: service
---
# Thank you for subscribing to the DataCite Member Mailing List
This confirms that you have succesfully subscribed to the DataCite Member Mailing List. Please contact info@datacite.org should you have any queries. For further information about our privacy practices please review our Privacy Policy.
| 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.mediaservices.v2018_07_01;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The ListEdgePoliciesInput model.
*/
public class ListEdgePoliciesInput {
/**
* Unique identifier of the edge device.
*/
@JsonProperty(value = "deviceId")
private String deviceId;
/**
* Get unique identifier of the edge device.
*
* @return the deviceId value
*/
public String deviceId() {
return this.deviceId;
}
/**
* Set unique identifier of the edge device.
*
* @param deviceId the deviceId value to set
* @return the ListEdgePoliciesInput object itself.
*/
public ListEdgePoliciesInput withDeviceId(String deviceId) {
this.deviceId = deviceId;
return this;
}
}
| 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.
* jkl
*/
package com.microsoft.azure.management.apimanagement.v2019_12_01.implementation;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.apimanagement.v2019_12_01.Loggers;
import rx.Completable;
import rx.functions.Func1;
import rx.Observable;
import com.microsoft.azure.Page;
import com.microsoft.azure.management.apimanagement.v2019_12_01.LoggerContract;
class LoggersImpl extends WrapperImpl<LoggersInner> implements Loggers {
private final ApiManagementManager manager;
LoggersImpl(ApiManagementManager manager) {
super(manager.inner().loggers());
this.manager = manager;
}
public ApiManagementManager manager() {
return this.manager;
}
@Override
public LoggerContractImpl define(String name) {
return wrapModel(name);
}
private LoggerContractImpl wrapModel(LoggerContractInner inner) {
return new LoggerContractImpl(inner, manager());
}
private LoggerContractImpl wrapModel(String name) {
return new LoggerContractImpl(name, this.manager());
}
@Override
public Observable<LoggerContract> listByServiceAsync(final String resourceGroupName, final String serviceName) {
LoggersInner client = this.inner();
return client.listByServiceAsync(resourceGroupName, serviceName)
.flatMapIterable(new Func1<Page<LoggerContractInner>, Iterable<LoggerContractInner>>() {
@Override
public Iterable<LoggerContractInner> call(Page<LoggerContractInner> page) {
return page.items();
}
})
.map(new Func1<LoggerContractInner, LoggerContract>() {
@Override
public LoggerContract call(LoggerContractInner inner) {
return new LoggerContractImpl(inner, manager());
}
});
}
@Override
public Completable getEntityTagAsync(String resourceGroupName, String serviceName, String loggerId) {
LoggersInner client = this.inner();
return client.getEntityTagAsync(resourceGroupName, serviceName, loggerId).toCompletable();
}
@Override
public Observable<LoggerContract> getAsync(String resourceGroupName, String serviceName, String loggerId) {
LoggersInner client = this.inner();
return client.getAsync(resourceGroupName, serviceName, loggerId)
.map(new Func1<LoggerContractInner, LoggerContract>() {
@Override
public LoggerContract call(LoggerContractInner inner) {
return new LoggerContractImpl(inner, manager());
}
});
}
@Override
public Completable deleteAsync(String resourceGroupName, String serviceName, String loggerId, String ifMatch) {
LoggersInner client = this.inner();
return client.deleteAsync(resourceGroupName, serviceName, loggerId, ifMatch).toCompletable();
}
}
| Java |
<?php
/**
* Created by PhpStorm.
* User: jmannion
* Date: 04/08/14
* Time: 22:17
*/
namespace JamesMannion\ForumBundle\Form\User;
use Symfony\Component\Form\FormBuilderInterface;
use JamesMannion\ForumBundle\Constants\Label;
use JamesMannion\ForumBundle\Constants\Button;
use JamesMannion\ForumBundle\Constants\Validation;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
class UserCreateForm extends AbstractType {
private $name = 'userCreateForm';
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add(
'username',
'text',
array(
'mapped' => true,
'required' => true,
'label' => Label::REGISTRATION_USERNAME,
'max_length' => 100,
)
)
->add(
'email',
'repeated',
array(
'type' => 'email',
'mapped' => true,
'required' => true,
'max_length' => 100,
'invalid_message' => Validation::REGISTRATION_EMAIL_MATCH,
'first_options' => array(
'label' => Label::REGISTRATION_EMAIL,
),
'second_options' => array(
'label' => Label::REGISTRATION_REPEAT_EMAIL),
)
)
->add(
'password',
'repeated',
array(
'mapped' => true,
'type' => 'password',
'required' => true,
'max_length' => 100,
'invalid_message' => Validation::REGISTRATION_PASSWORD_MATCH,
'first_options' => array('label' => Label::REGISTRATION_PASSWORD),
'second_options' => array('label' => Label::REGISTRATION_REPEAT_PASSWORD)
)
)
->add(
'memorableQuestion',
'entity',
array(
'mapped' => true,
'required' => true,
'label' => Label::REGISTRATION_MEMORABLE_QUESTION,
'class' => 'JamesMannionForumBundle:MemorableQuestion',
'query_builder' =>
function(EntityRepository $er) {
return $er->createQueryBuilder('q')
->orderBy('q.question', 'ASC');
}
)
)
->add(
'memorableAnswer',
'text',
array(
'mapped' => true,
'required' => true,
'label' => Label::REGISTRATION_MEMORABLE_ANSWER,
'max_length' => 100,
)
)
->add(
'save',
'submit',
array(
'label' => Button::REGISTRATION_SUBMIT
)
);
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
} | Java |
/**
* @file main.c
* @brief Main routine
*
* @section License
*
* Copyright (C) 2010-2015 Oryx Embedded SARL. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @author Oryx Embedded SARL (www.oryx-embedded.com)
* @version 1.6.4
**/
//Dependencies
#include <stdlib.h>
#include "stm32f4xx.h"
#include "stm32f4_discovery.h"
#include "stm32f4_discovery_lcd.h"
#include "os_port.h"
#include "core/net.h"
#include "drivers/stm32f4x7_eth.h"
#include "drivers/lan8720.h"
#include "dhcp/dhcp_client.h"
#include "ipv6/slaac.h"
#include "smtp/smtp_client.h"
#include "yarrow.h"
#include "error.h"
#include "debug.h"
//Application configuration
#define APP_MAC_ADDR "00-AB-CD-EF-04-07"
#define APP_USE_DHCP ENABLED
#define APP_IPV4_HOST_ADDR "192.168.0.20"
#define APP_IPV4_SUBNET_MASK "255.255.255.0"
#define APP_IPV4_DEFAULT_GATEWAY "192.168.0.254"
#define APP_IPV4_PRIMARY_DNS "8.8.8.8"
#define APP_IPV4_SECONDARY_DNS "8.8.4.4"
#define APP_USE_SLAAC ENABLED
#define APP_IPV6_LINK_LOCAL_ADDR "fe80::407"
#define APP_IPV6_PREFIX "2001:db8::"
#define APP_IPV6_PREFIX_LENGTH 64
#define APP_IPV6_GLOBAL_ADDR "2001:db8::407"
#define APP_IPV6_ROUTER "fe80::1"
#define APP_IPV6_PRIMARY_DNS "2001:4860:4860::8888"
#define APP_IPV6_SECONDARY_DNS "2001:4860:4860::8844"
//Global variables
uint_t lcdLine = 0;
uint_t lcdColumn = 0;
DhcpClientSettings dhcpClientSettings;
DhcpClientCtx dhcpClientContext;
SlaacSettings slaacSettings;
SlaacContext slaacContext;
YarrowContext yarrowContext;
uint8_t seed[32];
/**
* @brief Set cursor location
* @param[in] line Line number
* @param[in] column Column number
**/
void lcdSetCursor(uint_t line, uint_t column)
{
lcdLine = MIN(line, 10);
lcdColumn = MIN(column, 20);
}
/**
* @brief Write a character to the LCD display
* @param[in] c Character to be written
**/
void lcdPutChar(char_t c)
{
if(c == '\r')
{
lcdColumn = 0;
}
else if(c == '\n')
{
lcdColumn = 0;
lcdLine++;
}
else if(lcdLine < 10 && lcdColumn < 20)
{
//Display current character
LCD_DisplayChar(lcdLine * 24, lcdColumn * 16, c);
//Advance the cursor position
if(++lcdColumn >= 20)
{
lcdColumn = 0;
lcdLine++;
}
}
}
/**
* @brief I/O initialization
**/
void ioInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
//LED configuration
STM_EVAL_LEDInit(LED3);
STM_EVAL_LEDInit(LED4);
STM_EVAL_LEDInit(LED5);
STM_EVAL_LEDInit(LED6);
//Clear LEDs
STM_EVAL_LEDOff(LED3);
STM_EVAL_LEDOff(LED4);
STM_EVAL_LEDOff(LED5);
STM_EVAL_LEDOff(LED6);
//Initialize user button
STM_EVAL_PBInit(BUTTON_USER, BUTTON_MODE_GPIO);
//Enable GPIOE clock
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE, ENABLE);
//Configure PE2 (PHY_RST) pin as an output
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOE, &GPIO_InitStructure);
//Reset PHY transceiver (hard reset)
GPIO_ResetBits(GPIOE, GPIO_Pin_2);
sleep(10);
GPIO_SetBits(GPIOE, GPIO_Pin_2);
sleep(10);
}
/**
* @brief SMTP client test routine
* @return Error code
**/
error_t smtpClientTest(void)
{
error_t error;
//Authentication information
static SmtpAuthInfo authInfo =
{
NULL, //Network interface
"smtp.gmail.com", //SMTP server name
25, //SMTP server port
"username", //User name
"password", //Password
FALSE, //Use STARTTLS rather than implicit TLS
YARROW_PRNG_ALGO, //PRNG algorithm
&yarrowContext //PRNG context
};
//Recipients
static SmtpMailAddr recipients[2] =
{
{"Alice", "alice@example.com", SMTP_RCPT_TYPE_TO}, //First recipient
{"Bob", "bob@example.com", SMTP_RCPT_TYPE_CC} //Second recipient
};
//Mail contents
static SmtpMail mail =
{
{"Charlie", "charlie@gmail.com"}, //From
recipients, //Recipients
2, //Recipient count
"", //Date
"SMTP Client Demo", //Subject
"Hello World!" //Body
};
//Send mail
error = smtpSendMail(&authInfo, &mail);
//Return status code
return error;
}
/**
* @brief User task
**/
void userTask(void *param)
{
char_t buffer[40];
//Point to the network interface
NetInterface *interface = &netInterface[0];
//Initialize LCD display
lcdSetCursor(2, 0);
printf("IPv4 Addr\r\n");
lcdSetCursor(5, 0);
printf("Press user button\r\nto run test\r\n");
//Endless loop
while(1)
{
//Display IPv4 host address
lcdSetCursor(3, 0);
printf("%-16s\r\n", ipv4AddrToString(interface->ipv4Config.addr, buffer));
//User button pressed?
if(STM_EVAL_PBGetState(BUTTON_USER))
{
//SMTP client test routine
smtpClientTest();
//Wait for the user button to be released
while(STM_EVAL_PBGetState(BUTTON_USER));
}
//Loop delay
osDelayTask(100);
}
}
/**
* @brief LED blinking task
**/
void blinkTask(void *parameters)
{
//Endless loop
while(1)
{
STM_EVAL_LEDOn(LED4);
osDelayTask(100);
STM_EVAL_LEDOff(LED4);
osDelayTask(900);
}
}
/**
* @brief Main entry point
* @return Unused value
**/
int_t main(void)
{
error_t error;
uint_t i;
uint32_t value;
NetInterface *interface;
OsTask *task;
MacAddr macAddr;
#if (APP_USE_DHCP == DISABLED)
Ipv4Addr ipv4Addr;
#endif
#if (APP_USE_SLAAC == DISABLED)
Ipv6Addr ipv6Addr;
#endif
//Initialize kernel
osInitKernel();
//Configure debug UART
debugInit(115200);
//Start-up message
TRACE_INFO("\r\n");
TRACE_INFO("***********************************\r\n");
TRACE_INFO("*** CycloneTCP SMTP Client Demo ***\r\n");
TRACE_INFO("***********************************\r\n");
TRACE_INFO("Copyright: 2010-2015 Oryx Embedded SARL\r\n");
TRACE_INFO("Compiled: %s %s\r\n", __DATE__, __TIME__);
TRACE_INFO("Target: STM32F407\r\n");
TRACE_INFO("\r\n");
//Configure I/Os
ioInit();
//Initialize LCD display
STM32f4_Discovery_LCD_Init();
LCD_SetBackColor(Blue);
LCD_SetTextColor(White);
LCD_SetFont(&Font16x24);
LCD_Clear(Blue);
//Welcome message
lcdSetCursor(0, 0);
printf("SMTP Client Demo\r\n");
//Enable RNG peripheral clock
RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_RNG, ENABLE);
//Enable RNG
RNG_Cmd(ENABLE);
//Generate a random seed
for(i = 0; i < 32; i += 4)
{
//Wait for the RNG to contain a valid data
while(RNG_GetFlagStatus(RNG_FLAG_DRDY) == RESET);
//Get 32-bit random value
value = RNG_GetRandomNumber();
//Copy random value
seed[i] = value & 0xFF;
seed[i + 1] = (value >> 8) & 0xFF;
seed[i + 2] = (value >> 16) & 0xFF;
seed[i + 3] = (value >> 24) & 0xFF;
}
//PRNG initialization
error = yarrowInit(&yarrowContext);
//Any error to report?
if(error)
{
//Debug message
TRACE_ERROR("Failed to initialize PRNG!\r\n");
}
//Properly seed the PRNG
error = yarrowSeed(&yarrowContext, seed, sizeof(seed));
//Any error to report?
if(error)
{
//Debug message
TRACE_ERROR("Failed to seed PRNG!\r\n");
}
//TCP/IP stack initialization
error = netInit();
//Any error to report?
if(error)
{
//Debug message
TRACE_ERROR("Failed to initialize TCP/IP stack!\r\n");
}
//Configure the first Ethernet interface
interface = &netInterface[0];
//Set interface name
netSetInterfaceName(interface, "eth0");
//Set host name
netSetHostname(interface, "SMTPClientDemo");
//Select the relevant network adapter
netSetDriver(interface, &stm32f4x7EthDriver);
netSetPhyDriver(interface, &lan8720PhyDriver);
//Set host MAC address
macStringToAddr(APP_MAC_ADDR, &macAddr);
netSetMacAddr(interface, &macAddr);
//Initialize network interface
error = netConfigInterface(interface);
//Any error to report?
if(error)
{
//Debug message
TRACE_ERROR("Failed to configure interface %s!\r\n", interface->name);
}
#if (IPV4_SUPPORT == ENABLED)
#if (APP_USE_DHCP == ENABLED)
//Get default settings
dhcpClientGetDefaultSettings(&dhcpClientSettings);
//Set the network interface to be configured by DHCP
dhcpClientSettings.interface = interface;
//Disable rapid commit option
dhcpClientSettings.rapidCommit = FALSE;
//DHCP client initialization
error = dhcpClientInit(&dhcpClientContext, &dhcpClientSettings);
//Failed to initialize DHCP client?
if(error)
{
//Debug message
TRACE_ERROR("Failed to initialize DHCP client!\r\n");
}
//Start DHCP client
error = dhcpClientStart(&dhcpClientContext);
//Failed to start DHCP client?
if(error)
{
//Debug message
TRACE_ERROR("Failed to start DHCP client!\r\n");
}
#else
//Set IPv4 host address
ipv4StringToAddr(APP_IPV4_HOST_ADDR, &ipv4Addr);
ipv4SetHostAddr(interface, ipv4Addr);
//Set subnet mask
ipv4StringToAddr(APP_IPV4_SUBNET_MASK, &ipv4Addr);
ipv4SetSubnetMask(interface, ipv4Addr);
//Set default gateway
ipv4StringToAddr(APP_IPV4_DEFAULT_GATEWAY, &ipv4Addr);
ipv4SetDefaultGateway(interface, ipv4Addr);
//Set primary and secondary DNS servers
ipv4StringToAddr(APP_IPV4_PRIMARY_DNS, &ipv4Addr);
ipv4SetDnsServer(interface, 0, ipv4Addr);
ipv4StringToAddr(APP_IPV4_SECONDARY_DNS, &ipv4Addr);
ipv4SetDnsServer(interface, 1, ipv4Addr);
#endif
#endif
#if (IPV6_SUPPORT == ENABLED)
#if (APP_USE_SLAAC == ENABLED)
//Get default settings
slaacGetDefaultSettings(&slaacSettings);
//Set the network interface to be configured
slaacSettings.interface = interface;
//SLAAC initialization
error = slaacInit(&slaacContext, &slaacSettings);
//Failed to initialize SLAAC?
if(error)
{
//Debug message
TRACE_ERROR("Failed to initialize SLAAC!\r\n");
}
//Start IPv6 address autoconfiguration process
error = slaacStart(&slaacContext);
//Failed to start SLAAC process?
if(error)
{
//Debug message
TRACE_ERROR("Failed to start SLAAC!\r\n");
}
#else
//Set link-local address
ipv6StringToAddr(APP_IPV6_LINK_LOCAL_ADDR, &ipv6Addr);
ipv6SetLinkLocalAddr(interface, &ipv6Addr);
//Set IPv6 prefix
ipv6StringToAddr(APP_IPV6_PREFIX, &ipv6Addr);
ipv6SetPrefix(interface, &ipv6Addr, APP_IPV6_PREFIX_LENGTH);
//Set global address
ipv6StringToAddr(APP_IPV6_GLOBAL_ADDR, &ipv6Addr);
ipv6SetGlobalAddr(interface, &ipv6Addr);
//Set router
ipv6StringToAddr(APP_IPV6_ROUTER, &ipv6Addr);
ipv6SetRouter(interface, &ipv6Addr);
//Set primary and secondary DNS servers
ipv6StringToAddr(APP_IPV6_PRIMARY_DNS, &ipv6Addr);
ipv6SetDnsServer(interface, 0, &ipv6Addr);
ipv6StringToAddr(APP_IPV6_SECONDARY_DNS, &ipv6Addr);
ipv6SetDnsServer(interface, 1, &ipv6Addr);
#endif
#endif
//Create user task
task = osCreateTask("User Task", userTask, NULL, 800, 1);
//Failed to create the task?
if(task == OS_INVALID_HANDLE)
{
//Debug message
TRACE_ERROR("Failed to create task!\r\n");
}
//Create a task to blink the LED
task = osCreateTask("Blink", blinkTask, NULL, 500, 1);
//Failed to create the task?
if(task == OS_INVALID_HANDLE)
{
//Debug message
TRACE_ERROR("Failed to create task!\r\n");
}
//Start the execution of tasks
osStartKernel();
//This function should never return
return 0;
}
| Java |
### Standalone SearchBox
```jsx
const { compose, withProps, lifecycle } = require("recompose");
const {
withScriptjs,
} = require("react-google-maps");
const { StandaloneSearchBox } = require("react-google-maps/lib/components/places/StandaloneSearchBox");
const PlacesWithStandaloneSearchBox = compose(
withProps({
googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg&v=3.exp&libraries=geometry,drawing,places",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `400px` }} />,
}),
lifecycle({
componentWillMount() {
const refs = {}
this.setState({
places: [],
onSearchBoxMounted: ref => {
refs.searchBox = ref;
},
onPlacesChanged: () => {
const places = refs.searchBox.getPlaces();
this.setState({
places,
});
},
})
},
}),
withScriptjs
)(props =>
<div data-standalone-searchbox="">
<StandaloneSearchBox
ref={props.onSearchBoxMounted}
bounds={props.bounds}
onPlacesChanged={props.onPlacesChanged}
>
<input
type="text"
placeholder="Customized your placeholder"
style={{
boxSizing: `border-box`,
border: `1px solid transparent`,
width: `240px`,
height: `32px`,
padding: `0 12px`,
borderRadius: `3px`,
boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
fontSize: `14px`,
outline: `none`,
textOverflow: `ellipses`,
}}
/>
</StandaloneSearchBox>
<ol>
{props.places.map(({ place_id, formatted_address, geometry: { location } }) =>
<li key={place_id}>
{formatted_address}
{" at "}
({location.lat()}, {location.lng()})
</li>
)}
</ol>
</div>
);
<PlacesWithStandaloneSearchBox />
```
| Java |
/*! Slidebox.JS - v1.0 - 2013-11-30
* http://github.com/trevanhetzel/slidebox
*
* Copyright (c) 2013 Trevan Hetzel <trevan.co>;
* Licensed under the MIT license */
slidebox = function (params) {
// Carousel
carousel = function () {
var $carousel = $(params.container).children(".carousel"),
$carouselItem = $(".carousel li"),
$triggerLeft = $(params.leftTrigger),
$triggerRight = $(params.rightTrigger),
total = $carouselItem.length,
current = 0;
var moveLeft = function () {
if ( current > 0 ) {
$carousel.animate({ "left": "+=" + params.length + "px" }, params.speed );
current--;
}
};
var moveRight = function () {
if ( current < total - 2 ) {
$carousel.animate({ "left": "-=" + params.length + "px" }, params.speed );
current++;
}
};
// Initiliaze moveLeft on trigger click
$triggerLeft.on("click", function () {
moveLeft();
});
// Initiliaze moveRight on trigger click
$triggerRight.on("click", function () {
moveRight();
});
// Initiliaze moveLeft on left keypress
$(document).keydown(function (e){
if (e.keyCode == 37) {
moveLeft();
}
});
// Initiliaze moveRight on right keypress
$(document).keydown(function (e){
if (e.keyCode == 39) {
moveRight();
}
});
},
// Lightbox
lightbox = function () {
var trigger = ".carousel li a";
// Close lightbox when pressing esc key
$(document).keydown(function (e){
if (e.keyCode == 27) {
closeLightbox();
}
});
$(document)
// Close lightbox on any click
.on("click", function () {
closeLightbox();
})
// If clicked on a thumbnail trigger, proceed
.on("click", trigger, function (e) {
var $this = $(this);
// Prevent from clicking through
e.preventDefault();
e.stopPropagation();
// Grab the image URL
dest = $this.attr("href");
// Grab the caption from data attribute
capt = $this.children("img").data("caption");
enlarge(dest, capt);
/* If clicked on an enlarged image, stop propagation
so it doesn't get the close function */
$(document).on("click", ".lightbox img", function (e) {
e.stopPropagation();
});
});
closeLightbox = function () {
$(".lightbox-cont").remove();
$(".lightbox").remove();
},
enlarge = function (dest, capt) {
// Create new DOM elements
$("body").append("<div class='lightbox-cont'></div><div class='lightbox'></div>");
$(".lightbox").html(function () {
return "<img src='" + dest + "'><div class='lightbox-caption'>" + capt + "</div>";
});
}
}
// Initialize functions
carousel();
lightbox();
}; | Java |
<?php
// =============================================================================
// VIEWS/ETHOS/_POST-CAROUSEL.PHP
// -----------------------------------------------------------------------------
// Outputs the post carousel that appears at the top of the masthead.
// =============================================================================
GLOBAL $post_carousel_entry_id;
$post_carousel_entry_id = get_the_ID();
$is_enabled = x_get_option( 'x_ethos_post_carousel_enable', '' ) == '1';
$count = x_get_option( 'x_ethos_post_carousel_count' );
$display = x_get_option( 'x_ethos_post_carousel_display' );
switch ( $display ) {
case 'most-commented' :
$args = array(
'post_type' => 'post',
'posts_per_page' => $count,
'orderby' => 'comment_count',
'order' => 'DESC'
);
break;
case 'random' :
$args = array(
'post_type' => 'post',
'posts_per_page' => $count,
'orderby' => 'rand'
);
break;
case 'featured' :
$args = array(
'post_type' => 'post',
'posts_per_page' => $count,
'orderby' => 'date',
'meta_key' => '_x_ethos_post_carousel_display',
'meta_value' => 'on'
);
break;
}
?>
<?php if ( $is_enabled ) : ?>
<ul class="x-post-carousel unstyled">
<?php $wp_query = new WP_Query( $args ); ?>
<?php if ( $wp_query->have_posts() ) : ?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
<li class="x-post-carousel-item">
<?php x_ethos_entry_cover( 'post-carousel' ); ?>
</li>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query(); ?>
<script>
jQuery(document).ready(function() {
jQuery('.x-post-carousel').slick({
speed : 500,
slide : 'li',
slidesToShow : <?php echo x_get_option( 'x_ethos_post_carousel_display_count_extra_large' ); ?>,
slidesToScroll : 1,
responsive : [
{ breakpoint : 1500, settings : { speed : 500, slide : 'li', slidesToShow : <?php echo x_get_option( 'x_ethos_post_carousel_display_count_large' ); ?> } },
{ breakpoint : 1200, settings : { speed : 500, slide : 'li', slidesToShow : <?php echo x_get_option( 'x_ethos_post_carousel_display_count_medium' ); ?> } },
{ breakpoint : 979, settings : { speed : 500, slide : 'li', slidesToShow : <?php echo x_get_option( 'x_ethos_post_carousel_display_count_small' ); ?> } },
{ breakpoint : 550, settings : { speed : 500, slide : 'li', slidesToShow : <?php echo x_get_option( 'x_ethos_post_carousel_display_count_extra_small' ); ?> } }
]
});
});
</script>
</ul>
<?php endif; ?> | Java |
import test from 'ava';
import Server from '../../src/server';
import IO from '../../src/socket-io';
test.cb('mock socket invokes each handler with unique reference', t => {
const socketUrl = 'ws://roomy';
const server = new Server(socketUrl);
const socket = new IO(socketUrl);
let handlerInvoked = 0;
const handler3 = function handlerFunc() {
t.true(true);
handlerInvoked += 1;
};
// Same functions but different scopes/contexts
socket.on('custom-event', handler3.bind(Object.create(null)));
socket.on('custom-event', handler3.bind(Object.create(null)));
// Same functions with same scope/context (only one should be added)
socket.on('custom-event', handler3);
socket.on('custom-event', handler3); // not expected
socket.on('connect', () => {
socket.join('room');
server.to('room').emit('custom-event');
});
setTimeout(() => {
t.is(handlerInvoked, 3, 'handler invoked too many times');
server.close();
t.end();
}, 500);
});
test.cb('mock socket invokes each handler per socket', t => {
const socketUrl = 'ws://roomy';
const server = new Server(socketUrl);
const socketA = new IO(socketUrl);
const socketB = new IO(socketUrl);
let handlerInvoked = 0;
const handler3 = function handlerFunc() {
t.true(true);
handlerInvoked += 1;
};
// Same functions but different scopes/contexts
socketA.on('custom-event', handler3.bind(socketA));
socketB.on('custom-event', handler3.bind(socketB));
// Same functions with same scope/context (only one should be added)
socketA.on('custom-event', handler3);
socketA.on('custom-event', handler3); // not expected
socketB.on('custom-event', handler3.bind(socketB)); // expected because bind creates a new method
socketA.on('connect', () => {
socketA.join('room');
socketB.join('room');
server.to('room').emit('custom-event');
});
setTimeout(() => {
t.is(handlerInvoked, 4, 'handler invoked too many times');
server.close();
t.end();
}, 500);
});
| Java |
import React from 'react'
import PropTypes from 'prop-types'
import VelocityTrimControls from './VelocityTrimControls'
import Instrument from '../../images/Instrument'
import styles from '../../styles/velocityTrim'
import { trimShape } from '../../reducers/velocityTrim'
const handleKeyDown = (event, item, bank, userChangedTrimEnd) => {
let delta = 0
event.nativeEvent.preventDefault()
switch (event.key) {
case 'ArrowUp':
delta = 1
break
case 'ArrowDown':
delta = -1
break
case 'PageUp':
delta = 5
break
case 'PageDown':
delta = -5
break
case 'Enter':
delta = 100
break
case 'Escape':
delta = -100
break
default:
break
}
if (delta !== 0) {
delta += item.trim
if (delta < 0) delta = 0
if (delta > 100) delta = 100
userChangedTrimEnd(item.note, delta, bank)
}
}
const VelocityTrim = (props) => {
const { item, bank, selected, playNote, selectTrim, userChangedTrimEnd } = props
const { note, trim, group, name } = item
return (
<section
tabIndex={note}
onKeyDown={e => handleKeyDown(e, item, bank, userChangedTrimEnd)}
onMouseUp={() => (selected ? null : selectTrim(note))}
className={selected ? styles.selected : ''}
role="presentation"
>
<div
className={styles.header}
onMouseUp={() => playNote(note, Math.round(127 * (trim / 100)), bank)}
role="button"
tabIndex={note}
>
<div>{note}</div>
<div>{group}</div>
<div>{Instrument(group)}</div>
</div>
<div
className={styles.noteName}
title={name}
>
{name}
</div>
<VelocityTrimControls {...props} />
</section>
)
}
VelocityTrim.propTypes = {
item: trimShape.isRequired,
selected: PropTypes.bool.isRequired,
playNote: PropTypes.func.isRequired,
selectTrim: PropTypes.func.isRequired,
userChangedTrimEnd: PropTypes.func.isRequired,
bank: PropTypes.number.isRequired,
}
export default VelocityTrim
| Java |
class CreateTips < ActiveRecord::Migration[5.0]
def change
create_table :tips do |t|
t.text :body
t.timestamps
end
end
end
| Java |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('url');
}
}
class Admin_Controller extends MY_Controller {
public function __construct() {
parent::__construct();
$this->is_logged_in();
}
public function is_logged_in() {
}
}
| Java |
# chrome-launcher-cli [](https://travis-ci.org/ragingwind/chrome-launcher-cli)
> Chrome Launcher for CLI, which is a CLI tool extended from [chrome-launcher](https://www.npmjs.com/package/chrome-launcher). Please visit to [chrome-launcher](https://www.npmjs.com/package/chrome-launcher) page for more information.
## Install
```
$ npm install -g chrome-launcher-cli
```
## Usage
```js
chrome --help
```
## Receipts
### Test with Chrome Extension
```
chrome --app=file://test/index.html --system-developer-mode --load-extension=/test/extension --enable-extensions
```
## License
MIT © [Jimmy Moon](http://ragingwind.me)
| Java |
/*
* Copyright (c) 2014-2016, Santili Y-HRAH KRONG
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sqlcreatetable.hpp>
namespace cppsqlx
{
SQLCreateTable::SQLCreateTable(std::string tablename)
{
_objectname = tablename;
_objecttype = "TABLE";
}
std::string SQLCreateTable::toString()
{
std::string query;
query = "CREATE ";
query += _objecttype + " " + _objectname;
if(_ds)
{
query += "(\n";
for(auto i = 1; i <= _ds->rowSize() ; i++)
{
query += _ds->at(i).name() + " " + _ds->at(i).type();
if(i != _ds->rowSize())
query += ",\n";
}
query += "\n)";
}
else
{
query += " AS\n";
query += _select;
}
switch(sqldialect_)
{
case DBPROVIDER::GREENPLUM :
{
query+= "\nDISTRIBUTED RANDOMLY";
break;
}
default:
break;
}
return query;
};
SQLCreateTable& SQLCreateTable::as(std::string select)
{
_select = select;
return *this;
}
SQLCreateTable& SQLCreateTable::sameAs(std::shared_ptr<Dataset> ds)
{
_ds = ds;
return *this;
}
};/*namespace cppsqlx*/
| Java |
<?php
/**
* Link posts
*
* @package Start Here
* @since Start Here 1.0.0
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="post-header">
<div class="header-metas">
<?php sh_post_format(); ?>
<?php if( is_singular() ) { edit_post_link( __( 'Edit', 'textdomain' ), '<span class="edit-link">', '</span>' ); } ?>
<span class="post-date">
<time class="published" datetime="<?php echo get_the_time('c'); ?>"><a title="<?php _e( 'Permalink to: ', 'textdomain' ); echo the_title(); ?>" href="<?php the_permalink(); ?>"><?php echo get_the_date(); ?></a></time>
</span>
<span class="post-author">
<?php _e( '- By ', 'textdomain' ); ?><a title="<?php _e('See other posts by ', 'textdomain'); the_author_meta( 'display_name' ); ?>" href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) ); ?>"><?php the_author_meta( 'display_name' ); ?></a>
</span>
</div>
</header>
<div class="<?php if( is_single() ) { echo 'post-content'; } else { echo 'link-content'; } ?>">
<?php the_content(''); ?>
</div>
<?php if( !is_single() && has_excerpt() ) : ?>
<?php the_excerpt(); ?>
<a class="read-more" href="<?php the_permalink(); ?>" title="<?php echo _e( 'Read more', 'textdomain' ); ?>"><i class="g"></i><?php echo _e( 'Read more', 'textdomain' ); ?></a>
<?php endif; ?>
<?php if( is_single() ) : ?>
<footer class="post-footer">
<ul class="taxo-metas">
<?php if( get_the_category() ) { ?><li class="category"><i class="gicn gicn-category"></i><?php the_category(' • '); ?></li><?php } ?>
<li class="tag-links"><i class="gicn gicn-tag"></i><?php
$tags_list = get_the_tag_list( '', __( ' ', 'textdomain' ) );
if ( $tags_list ) :
printf( __( '%1$s', 'textdomain' ), $tags_list );
else :
_e( 'No tags', 'textdomain' );
endif; ?>
</li>
</ul>
</footer>
<?php endif; ?>
</article> | Java |
/*! HTML5 Boilerplate v5.2.0 | MIT License | https://html5boilerplate.com/ */
/*
* What follows is the result of much research on cross-browser styling.
* Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
* Kroc Camen, and the H5BP dev community and team.
*/
/* ==========================================================================
Base styles: opinionated defaults
========================================================================== */
html {
color: #222;
font-size: 1em;
line-height: 1.4;
}
/*
* Remove text-shadow in selection highlight:
* https://twitter.com/miketaylr/status/12228805301
*
* These selection rule sets have to be separate.
* Customize the background color to match your design.
*/
::-moz-selection {
background: #b3d4fc;
text-shadow: none;
}
::selection {
background: #b3d4fc;
text-shadow: none;
}
/*
* A better looking default horizontal rule
*/
hr {
display: block;
height: 1px;
border: 0;
border-top: 1px solid #ccc;
margin: 1em 0;
padding: 0;
}
/*
* Remove the gap between audio, canvas, iframes,
* images, videos and the bottom of their containers:
* https://github.com/h5bp/html5-boilerplate/issues/440
*/
audio,
canvas,
iframe,
img,
svg,
video {
vertical-align: middle;
}
/*
* Remove default fieldset styles.
*/
fieldset {
border: 0;
margin: 0;
padding: 0;
}
/*
* Allow only vertical resizing of textareas.
*/
textarea {
resize: vertical;
}
/* ==========================================================================
Browser Upgrade Prompt
========================================================================== */
.browserupgrade {
margin: 0.2em 0;
background: #ccc;
color: #000;
padding: 0.2em 0;
}
/* ==========================================================================
GENERAL!!!
========================================================================== */
body {
font-family: 'Oswald', sans-serif;
background-image: url("../img/fond.jpg") !important;
background-position: center;
width: 100%;
height: 500px;
background-size: cover;
}
.fondecran{
height: 100%;
}
/* ==========================================================================
NAVBAR!!!
========================================================================== */
#mainmenu {
padding-bottom: 2%;
}
#mainmenu li a {
padding-top: 6px;
padding-bottom: 0px;
margin-top: 7px;
height: 34px;
}
.container {
width: 83%;
}
#likefb {
width: 70px;
margin-top: -6%;
}
.border-nav {
border-left: 1px dotted grey;
}
#logo1 {
margin-top: -13px;
width: 60%;
}
/*//////-- NAVBAR --//////*/
/*/////-- Content --//////*/
#slogan1 {
background-color: rgba(0,120,215,0.2);
}
/* footer */
#footer {
color: grey;
height: 63px;
background-color: #608A0C;
}
#footer h1 {
font-size: 1em;
padding-left: 20px;
}
#footer3 {
padding-top: 11px;
}
#footer2 {
font-size: 1.5em;
color: white;
background-color: #87C316;
height : 60px;
background-image: url(../img/shadow.png);
background-size: cover;
}
.border-nav2 {
border-left: 1px dotted grey;
}
.joueur{
position: absolute;
width: 10%;
}
.vide {
position: absolute;
width: 10%;
}
/* ==========================================================================
Helper classes
========================================================================== */
/*
* Hide visually and from screen readers:
*/
.hidden {
display: none !important;
}
/*
* Hide only visually, but have it available for screen readers:
* http://snook.ca/archives/html_and_css/hiding-content-for-accessibility
*/
.visuallyhidden {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
/*
* Extends the .visuallyhidden class to allow the element
* to be focusable when navigated to via the keyboard:
* https://www.drupal.org/node/897638
*/
.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
clip: auto;
height: auto;
margin: 0;
overflow: visible;
position: static;
width: auto;
}
/*
* Hide visually and from screen readers, but maintain layout
*/
.invisible {
visibility: hidden;
}
/*
* Clearfix: contain floats
*
* For modern browsers
* 1. The space content is one way to avoid an Opera bug when the
* `contenteditable` attribute is included anywhere else in the document.
* Otherwise it causes space to appear at the top and bottom of elements
* that receive the `clearfix` class.
* 2. The use of `table` rather than `block` is only necessary if using
* `:before` to contain the top-margins of child elements.
*/
.clearfix:before,
.clearfix:after {
content: " "; /* 1 */
display: table; /* 2 */
}
.clearfix:after {
clear: both;
}
/* ==========================================================================
EXAMPLE Media Queries for Responsive Design.
These examples override the primary ('mobile first') styles.
Modify as content requires.
========================================================================== */
@media only screen and (min-width: 35em) {
/* Style adjustments for viewports that meet the condition */
}
@media print,
(-webkit-min-device-pixel-ratio: 1.25),
(min-resolution: 1.25dppx),
(min-resolution: 120dpi) {
/* Style adjustments for high resolution devices */
}
/* ==========================================================================
Print styles.
Inlined to avoid the additional HTTP request:
http://www.phpied.com/delay-loading-your-print-css/
========================================================================== */
@media print {
*,
*:before,
*:after {
background: transparent !important;
color: #000 !important; /* Black prints faster:
http://www.sanbeiji.com/archives/953 */
box-shadow: none !important;
text-shadow: none !important;
}
a,
a:visited {
text-decoration: underline;
}
a[href]:after {
content: " (" attr(href) ")";
}
abbr[title]:after {
content: " (" attr(title) ")";
}
/*
* Don't show links that are fragment identifiers,
* or use the `javascript:` pseudo protocol
*/
a[href^="#"]:after,
a[href^="javascript:"]:after {
content: "";
}
pre,
blockquote {
border: 1px solid #999;
page-break-inside: avoid;
}
/*
* Printing Tables:
* http://css-discuss.incutio.com/wiki/Printing_Tables
*/
thead {
display: table-header-group;
}
tr,
img {
page-break-inside: avoid;
}
img {
max-width: 100% !important;
}
p,
h2,
h3 {
orphans: 3;
widows: 3;
}
h2,
h3 {
page-break-after: avoid;
}
}
| Java |
#!/bin/bash
SCRIPT_PATH="${BASH_SOURCE[0]}";
if ([ -h "${SCRIPT_PATH}" ]) then
while([ -h "${SCRIPT_PATH}" ]) do SCRIPT_PATH=`readlink "${SCRIPT_PATH}"`; done
fi
pushd . > /dev/null
cd `dirname ${SCRIPT_PATH}` > /dev/null
SCRIPT_PATH=`pwd`;
popd > /dev/null
if ! [ -f $SCRIPT_PATH/.nuget/nuget.exe ]
then
wget "https://www.nuget.org/nuget.exe" -P $SCRIPT_PATH/.nuget/
fi
mono $SCRIPT_PATH/.nuget/nuget.exe update -self
SCRIPT_PATH="${BASH_SOURCE[0]}";
if ([ -h "${SCRIPT_PATH}" ]) then
while([ -h "${SCRIPT_PATH}" ]) do SCRIPT_PATH=`readlink "${SCRIPT_PATH}"`; done
fi
pushd . > /dev/null
cd `dirname ${SCRIPT_PATH}` > /dev/null
SCRIPT_PATH=`pwd`;
popd > /dev/null
mono $SCRIPT_PATH/.nuget/NuGet.exe update -self
mono $SCRIPT_PATH/.nuget/NuGet.exe install FAKE -OutputDirectory $SCRIPT_PATH/packages -ExcludeVersion -Version 4.16.1
mono $SCRIPT_PATH/.nuget/NuGet.exe install xunit.runner.console -OutputDirectory $SCRIPT_PATH/packages/FAKE -ExcludeVersion -Version 2.0.0
mono $SCRIPT_PATH/.nuget/NuGet.exe install NUnit.Console -OutputDirectory $SCRIPT_PATH/packages/FAKE -ExcludeVersion -Version 3.2.1
mono $SCRIPT_PATH/.nuget/NuGet.exe install NBench.Runner -OutputDirectory $SCRIPT_PATH/packages -ExcludeVersion -Version 0.3.1
if ! [ -e $SCRIPT_PATH/packages/SourceLink.Fake/tools/SourceLink.fsx ] ; then
mono $SCRIPT_PATH/.nuget/NuGet.exe install SourceLink.Fake -OutputDirectory $SCRIPT_PATH/packages -ExcludeVersion
fi
export encoding=utf-8
mono $SCRIPT_PATH/packages/FAKE/tools/FAKE.exe build.fsx "$@"
| Java |
#include <assert.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <video/gl.h>
#include <xxhash.h>
#include <memtrack.h>
#include "base/stack.h"
#include "core/common.h"
#include "base/math_ext.h"
#include "core/asset.h"
#include "core/configs.h"
#include "core/frame.h"
#include "core/logerr.h"
#include <core/application.h>
#include "core/video.h"
#include "video/resources_detail.h"
#include <core/audio.h>
static int running = 1;
static STACK *states_stack;
static APP_STATE *allstates;
static size_t states_num;
NEON_API void
application_next_state(unsigned int state) {
if (state > states_num) {
LOG_ERROR("State(%d) out of range", state);
exit(EXIT_FAILURE);
}
push_stack(states_stack, &allstates[state]);
((APP_STATE*)top_stack(states_stack))->on_init();
frame_flush();
}
NEON_API void
application_back_state(void) {
((APP_STATE*)pop_stack(states_stack))->on_cleanup();
frame_flush();
}
static void
application_cleanup(void) {
configs_cleanup();
asset_close();
audio_cleanup();
video_cleanup();
while (!is_stack_empty(states_stack))
application_back_state();
delete_stack(states_stack);
}
#ifdef OPENAL_BACKEND
#define SDL_INIT_FLAGS (SDL_INIT_VIDEO | SDL_INIT_TIMER)
#else
#define SDL_INIT_FLAGS (SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)
#endif
NEON_API int
application_exec(const char *title, APP_STATE *states, size_t states_n) {
allstates = states;
states_num = states_n;
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
LOG_ERROR("%s\n", SDL_GetError());
return EXIT_FAILURE;
}
atexit(SDL_Quit);
if (TTF_Init() < 0) {
LOG_ERROR("%s\n", TTF_GetError());
return EXIT_FAILURE;
}
atexit(TTF_Quit);
if ((states_stack = new_stack(sizeof(APP_STATE), states_n + 1)) == NULL) {
LOG_ERROR("%s\n", "Can\'t create game states stack");
return EXIT_FAILURE;
}
LOG("%s launched...\n", title);
LOG("Platform: %s\n", SDL_GetPlatform());
video_init(title);
audio_init();
atexit(application_cleanup);
application_next_state(0);
if (is_stack_empty(states_stack)) {
LOG_CRITICAL("%s\n", "No game states");
exit(EXIT_FAILURE);
}
SDL_Event event;
Uint64 current = 0;
Uint64 last = 0;
float accumulator = 0.0f;
while(running) {
frame_begin();
while(SDL_PollEvent(&event)) {
((APP_STATE*)top_stack(states_stack))->on_event(&event);
}
asset_process();
resources_process();
last = current;
current = SDL_GetPerformanceCounter();
Uint64 freq = SDL_GetPerformanceFrequency();
float delta = (double)(current - last) / (double)freq;
accumulator += CLAMP(delta, 0.f, 0.2f);
while(accumulator >= TIMESTEP) {
accumulator -= TIMESTEP;
((APP_STATE*)top_stack(states_stack))->on_update(TIMESTEP);
}
((APP_STATE*)top_stack(states_stack))->on_present(screen.width, screen.height, accumulator / TIMESTEP);
video_swap_buffers();
frame_end();
SDL_Delay(1);
}
return EXIT_SUCCESS;
}
NEON_API void
application_quit(void) {
running = 0;
}
| Java |
# Scrapy settings for helloscrapy project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'helloscrapy'
SPIDER_MODULES = ['helloscrapy.spiders']
NEWSPIDER_MODULE = 'helloscrapy.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'helloscrapy (+http://www.yourdomain.com)'
DOWNLOAD_DELAY = 3
ROBOTSTXT_OBEY = True
| Java |
"""
Django settings for djangoApp project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'r&j)3lay4i$rm44n%h)bsv_q(9ysqhl@7@aibjm2b=1)0fag9n'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'djangoApp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'djangoApp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
| Java |
---
layout: page
title: Sub Aerospace Executive Retreat
date: 2016-05-24
author: Matthew Cole
tags: weekly links, java
status: published
summary: Class aptent taciti sociosqu ad.
banner: images/banner/leisure-03.jpg
booking:
startDate: 06/25/2018
endDate: 06/29/2018
ctyhocn: TOIALHX
groupCode: SAER
published: true
---
Nulla suscipit arcu id laoreet facilisis. Maecenas elementum finibus turpis, nec consectetur est fermentum et. Nullam eu ipsum eget justo lobortis molestie. Nulla facilisi. Morbi pulvinar nisi non sapien gravida, at auctor est hendrerit. Nam posuere eros eget arcu elementum tincidunt. Maecenas dignissim ex venenatis quam molestie efficitur at hendrerit augue. Suspendisse feugiat in ligula sit amet elementum. Duis et consectetur est. Duis hendrerit, nunc a feugiat elementum, nisl purus hendrerit mauris, ac venenatis est enim aliquet ex. Aliquam in massa tempus, tincidunt velit at, varius lorem. Mauris ligula augue, dapibus non egestas a, tristique in ipsum. Nullam vel orci non eros dictum laoreet lacinia nec velit. In hac habitasse platea dictumst. Maecenas ornare est enim.
Proin porttitor lacus ut dui vehicula, at maximus mauris eleifend. Aenean faucibus viverra mi, sed pharetra turpis sagittis sit amet. Curabitur luctus ultrices risus nec mattis. Aenean accumsan purus et fringilla suscipit. Mauris hendrerit lobortis urna, eget porta velit ultricies a. Donec vestibulum sagittis est ac bibendum. Suspendisse potenti. Maecenas porttitor, odio eu maximus tempus, nibh sapien lobortis eros, quis interdum felis purus in nisi. Donec quis quam hendrerit, eleifend magna sed, euismod est. Nulla luctus dignissim diam id aliquam. Sed sagittis eu libero ullamcorper molestie.
* In nec mi ut eros cursus volutpat
* Aenean nec nibh venenatis, dignissim nisl eget, auctor ipsum
* Etiam faucibus elit eu leo egestas porta
* Duis ac mi vel lectus gravida vulputate.
Nunc dapibus est eget justo mollis sagittis nec at augue. Nulla ultricies mattis orci maximus tristique. Praesent hendrerit scelerisque ligula quis commodo. Fusce porta arcu vel lacus elementum, pharetra finibus eros tempus. Etiam aliquet mauris sed posuere sodales. Curabitur elit sapien, consequat tempus elementum ac, ultrices ac massa. Fusce tincidunt nibh nec tempor tempus. Suspendisse convallis, quam at malesuada vulputate, enim elit tempus urna, sit amet laoreet arcu nisl id neque. Cras gravida et dolor non faucibus. Proin risus lorem, facilisis non ligula sollicitudin, finibus accumsan erat. Vivamus nec rutrum turpis.
Nam justo eros, bibendum quis semper vitae, euismod eget mi. Donec porta euismod dolor ac porttitor. Maecenas consequat mauris convallis interdum vestibulum. Vestibulum congue ipsum est, eget cursus sapien varius id. Aliquam ut arcu justo. Quisque eu sodales leo. Suspendisse mattis enim vitae fermentum tempus. Etiam eu ex viverra, euismod mi id, facilisis massa. Praesent a quam sit amet odio vestibulum lobortis sit amet et ligula. Etiam nec diam et ante eleifend tincidunt. Sed rutrum luctus diam, et hendrerit diam elementum sed. Fusce quis sapien ex. Vivamus scelerisque fringilla libero. Praesent dapibus tempor tempor. Nam quis dui sit amet nunc rhoncus congue.
| Java |
---
layout: page
title: Pearl Group Dinner
date: 2016-05-24
author: Margaret Norris
tags: weekly links, java
status: published
summary: Pellentesque in hendrerit tortor. Quisque sollicitudin urna id.
banner: images/banner/leisure-04.jpg
booking:
startDate: 08/14/2018
endDate: 08/18/2018
ctyhocn: NYCEMHX
groupCode: PGD
published: true
---
Nam fermentum enim a dui venenatis accumsan. Vestibulum nec ultricies nisl, nec viverra quam. Donec et massa eget libero lobortis posuere. Vestibulum lobortis odio sed lorem laoreet suscipit. Duis nibh ligula, viverra vitae pulvinar et, tristique eget dui. Fusce fermentum mi eget vehicula tincidunt. Nulla non commodo nulla. Morbi id tincidunt ex. Ut ornare eget enim a efficitur.
In ullamcorper lacus eu faucibus mollis. Proin a sollicitudin elit, ut ultricies risus. Praesent ut ornare nulla. Pellentesque porta augue ex, vitae facilisis elit iaculis vel. Aliquam facilisis egestas urna vitae varius. Mauris metus enim, molestie non facilisis a, varius non nibh. Aliquam tristique odio interdum elit posuere commodo eu nec metus. Fusce maximus luctus tortor a congue. Nunc volutpat tempor lacus, dignissim rhoncus risus vehicula in. Cras viverra rutrum convallis. Aliquam quis neque vel lectus ultrices tempor quis vitae ligula. In nec suscipit lacus. Quisque iaculis pulvinar cursus.
* Donec fringilla magna a neque bibendum efficitur
* Vestibulum porttitor nulla eget turpis malesuada porttitor
* Curabitur ac risus at orci vestibulum feugiat et laoreet nulla.
Quisque nec cursus nisl, vel sodales turpis. Maecenas vel tristique erat, in sollicitudin turpis. Ut suscipit ipsum ac lectus posuere scelerisque. Integer risus diam, ultrices ac elit sed, luctus tempus magna. Nam et maximus est. Etiam vulputate, dolor et luctus accumsan, nunc nulla pulvinar mauris, ut convallis orci est nec libero. Praesent egestas ac sem laoreet vulputate. Vivamus eleifend ante a neque viverra fermentum. Proin pharetra mollis faucibus. Nunc non volutpat arcu. Etiam luctus neque lectus, a vulputate magna interdum non. Nam ac hendrerit sem. Pellentesque elementum in mauris vulputate tincidunt.
| Java |
---
layout: page
title: Warren Guardian Company Conference
date: 2016-05-24
author: Emily Harmon
tags: weekly links, java
status: published
summary: Pellentesque porttitor arcu velit, in facilisis tellus volutpat non. Nulla.
banner: images/banner/leisure-02.jpg
booking:
startDate: 12/20/2018
endDate: 12/23/2018
ctyhocn: NBFELHX
groupCode: WGCC
published: true
---
Maecenas ultrices enim id sapien semper, non auctor sapien varius. Nulla a commodo sem. Interdum et malesuada fames ac ante ipsum primis in faucibus. Cras laoreet, dolor consectetur convallis aliquet, ipsum risus feugiat justo, vitae laoreet tellus diam at quam. Quisque ut lectus in sapien consectetur posuere. Sed rutrum ultricies odio, non porttitor lectus cursus quis. Etiam auctor ullamcorper dolor, non semper sapien feugiat ac.
* Ut nec nulla molestie, pretium erat vitae, feugiat turpis
* Mauris vitae enim ut magna malesuada lobortis
* Sed id felis vestibulum, elementum turpis id, luctus mauris
* Sed eu augue at mi congue viverra
* Integer elementum lectus quis scelerisque mollis.
Morbi ullamcorper diam nec urna sodales egestas. Nam commodo tellus ut convallis feugiat. Fusce aliquam nisl ut libero pharetra, a convallis felis dapibus. Sed ut mi fermentum, laoreet nulla quis, sollicitudin orci. Praesent id tempus quam. Maecenas elementum varius iaculis. Suspendisse in leo sit amet tellus finibus luctus sit amet sed ipsum. Quisque faucibus, ante non consectetur porttitor, mauris velit volutpat massa, quis hendrerit odio dolor eu massa. Nam mattis malesuada egestas. Sed auctor lobortis orci vel iaculis. Aenean non ligula ultricies, cursus purus in, pharetra quam. Maecenas egestas efficitur nisi, nec iaculis erat rutrum efficitur. Aenean in congue neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec nec purus quis lectus facilisis malesuada. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
| Java |
namespace Engine.Contracts
{
public interface IAct
{
/// <summary>
/// Makes an act (or try) and returns how much time it takes
/// </summary>
/// <param name="scene">Scene on which act plays</param>
/// <returns>Time passed</returns>
ActResult Do(IScene scene);
string Name { get; set; }
bool CanDo(IActor actor, IScene scene);
}
public class ActResult
{
public int TimePassed;
public string Message;
}
}
| Java |
---
uid: SolidEdgeFramework.Properties.Name
summary:
remarks: All objects have names that are unique within the scope of their parent.
---
| Java |
#pragma once
#include <QtCore/QPointer>
#include <QtWidgets/QTabWidget>
#include "backend/backend_requests_interface.h"
class BreakpointModel;
class PDIBackendRequests;
class DisassemblyView;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class CodeViews : public QTabWidget {
public:
CodeViews(BreakpointModel* breakpoints, QWidget* parent = 0);
virtual ~CodeViews();
void set_breakpoint_model(BreakpointModel* breakpoints);
void reload_current_file();
void toggle_breakpoint();
void set_backend_interface(PDIBackendRequests* iface);
Q_SLOT void open_file(const QString& filename, bool setActive);
Q_SLOT void program_counter_changed(const PDIBackendRequests::ProgramCounterChange& pc);
Q_SLOT void session_ended();
private:
Q_SLOT void closeTab(int index);
enum Mode {
SourceView,
Disassembly,
};
void read_settings();
void write_settings();
Mode m_mode = SourceView;
int m_oldIndex = 0;
// DisassemblyView* m_disassemblyView = nullptr;
BreakpointModel* m_breakpoints = nullptr;
QPointer<PDIBackendRequests> m_interface;
QVector<QString> m_files;
bool m_was_in_source_view = true;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline void CodeViews::set_breakpoint_model(BreakpointModel* breakpoints) {
m_breakpoints = breakpoints;
}
| Java |
---
layout: post
title: "8퍼센트 플랫폼개발 인턴 후기-마지막"
author: selee
description: 그동안 감사했습니다!
---
<p align="center">
<img src="/images/internship-4-인터뷰.jpg" alt="인턴 동기랑" width="500">
</p>
## <span style="color:#6741d9">이벤트 케러셀</span>
남은 기간에는 저번 인턴기에 쓴 이벤트 케러셀/배너 스태프 페이지 만들기 작업을 이어서 계속했다. 관리자 페이지에서 케러셀과 배너를 저장하면 관련 정보를 DB에 저장하는 API와 DB에 저장된 정보를 바탕으로 홈페이지에 케러셀과 배너를 자동으로 띄우는 API를 만들었다. 100% 완성한 게 아니라서 인수인계를 하고 가야 한다는 점이 좀 아쉽다.
<p align="center">
<img src="/images/internship-4-캐러셀.png" alt="케러셀" width="300">
<img src="/images/internship-4-배너.png" alt="배너" width="300">
</p>
## <span style="color:#6741d9">9주가 호로록</span>
처음 인턴기 쓰던 순간이 생각난다. 그때는 2주도 이렇게 안 지나가는데 9주는 어떻게 버티지? 라는 생각을 했다. **근데 놀랍게도 9주가 호로로록 하고 지나가 버렸다 .** 그만큼 에잇퍼센트에서 보낸 인턴 기간이 즐거웠다는 것이고 앞으로도 이 경험은 오랫동안 기억에 남을 거 같다.
### 에잇퍼센트에게 받은 <span style="color:#6741d9">가장 큰 선물</span>
인턴으로 오기 전, 학교 시험과 과제로 개발에 신물이 났었다. 그래서 개발 공부를 거의 하지 않았고 그랬기에 초반에 업무를 하면서 꽤 고생했다. 그래도 계속 질문하고 공부하면서 일을 한, 두 개 끝내니 할만하다고 생각했다.
특히, 알림톡을 대량 발송할 수 있는 관리자 페이지를 직접 만들고 바로 마케팅팀분들이 바로 쓰시는 걸 봤을 때는 엄청 뿌듯했다. 내가 개발한 기능이 다른 누군가에게 엄청 도움이 된다는 걸 알 때마다 개발에 대한 재미를 조금씩 되찾았다. 어느새 어떻게 하면 내가 맡은 기능을 구현할 수 있을까를 고민하고 있었고 어느새 출퇴근 길 모르는 부분을 검색하고 공부하고 있었다.
인턴 기간 동안 Django, Vue, 개발 프로세스 등 많은 것을 배웠다. 하지만 무엇보다도 에잇퍼센트에서 가장 크게 얻어가는 것은 개발에 대한 흥미이다. 인턴 끝나고 어떤 내용을 공부하고 어떤 걸 만들어볼지 고민하는 나 자신이 너무 신기하다.
<p align="center">
<img src="/images/internship-4-칭찬.jpg" alt="익명의 칭찬" width="500">
</p>
### <span style="color:#6741d9">님과 함께</span>
처음에 사회생활 신생아로서 눈치를 많이 볼 때 빠르게 적응할 수 있었던 가장 큰 이유는 정말 좋은 에잇퍼센트 사람들 덕분이었다. **특히, 온종일 같이 있는 플랫폼개발 팀원분들 만세**
다들 업무로 바쁘실 텐데 물어볼 때마다 친절하게 알려주시고 코드 리뷰도 정성껏 해주시고 먼저 와서 알려주시고 말 걸어주셔서 금방 적응할 수 있었다. 점심시간이나 업무 중간에 나누는 잡담 타임도 너무 재밌었다. 그래서 사실 많은 분이 재택 해서 사무실이 좀 비면 심심했다. 그 정도로 정이 많이 든 거 같다.
<p align="center">
<img src="/images/internship-4-호성님과.jpg" alt="호성님과 마지막" width="500">
</p>
<br>
## <span style="color:#6741d9">마지막 에피소드</span>
### 첫 재택근무
인턴 첫 2주를 제외하고 재택근무를 할 수 있었으나, 더 많이 배우고 팀원분들이랑 친해지고 싶어서 항상 사무실로 출근했다. 하지만 한 번도 재택근무 안 하고 가면 아쉬울 거 같아서 처음으로 재택근무를 했다. 잠을 두 시간 더 잘 수 있고, 퇴근하면 바로 집이라는 점은 생각보다 더 많이 행복했다.
### 당 충전하세요
<p align="center">
<img src="/images/internship-4-사탕.png" alt="사탕" width="500">
</p>
같은 인턴 동기인 미연님의 제안으로 밥도 많이 사주시고 잘 챙겨주신 에잇퍼센트 사람들에게 작은 선물을 드리기로 했다. 밸런타인데이를 기념으로 초콜릿이랑 사탕을 준비해서 사무실 테이블에 두었다. 올리자마자 나랑 미연님 사진 이모티콘이 달리는 게 재밌었다.
<br>
**<span style="color:#6741d9">마지막 인턴기 끝!</span>** 그동안 감사했습니다. | Java |
.sample2 .sea {
height: 300px;
width: 480px;
position: relative;
background-image: url(media/fishing.png), url(media/mermaid.png), url(media/sea.png);
background-position: top right 10px, bottom left, top left;
background-repeat: no-repeat, repeat-x, repeat-x;
}
.sample2 .fish {
background: url(media/fish.png) no-repeat;
height: 70px;
width: 100px;
left: 30px;
top: 90px;
position: absolute;
} | Java |
/**
* @fileoverview Rule to flag use of implied eval via setTimeout and setInterval
* @author James Allardice
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
const { getStaticValue } = require("eslint-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "disallow the use of `eval()`-like methods",
category: "Best Practices",
recommended: false,
url: "https://eslint.org/docs/rules/no-implied-eval"
},
schema: [],
messages: {
impliedEval: "Implied eval. Consider passing a function instead of a string."
}
},
create(context) {
const EVAL_LIKE_FUNCS = Object.freeze(["setTimeout", "execScript", "setInterval"]);
const GLOBAL_CANDIDATES = Object.freeze(["global", "window", "globalThis"]);
/**
* Checks whether a node is evaluated as a string or not.
* @param {ASTNode} node A node to check.
* @returns {boolean} True if the node is evaluated as a string.
*/
function isEvaluatedString(node) {
if (
(node.type === "Literal" && typeof node.value === "string") ||
node.type === "TemplateLiteral"
) {
return true;
}
if (node.type === "BinaryExpression" && node.operator === "+") {
return isEvaluatedString(node.left) || isEvaluatedString(node.right);
}
return false;
}
/**
* Checks whether a node is an Identifier node named one of the specified names.
* @param {ASTNode} node A node to check.
* @param {string[]} specifiers Array of specified name.
* @returns {boolean} True if the node is a Identifier node which has specified name.
*/
function isSpecifiedIdentifier(node, specifiers) {
return node.type === "Identifier" && specifiers.includes(node.name);
}
/**
* Checks a given node is a MemberExpression node which has the specified name's
* property.
* @param {ASTNode} node A node to check.
* @param {string[]} specifiers Array of specified name.
* @returns {boolean} `true` if the node is a MemberExpression node which has
* the specified name's property
*/
function isSpecifiedMember(node, specifiers) {
return node.type === "MemberExpression" && specifiers.includes(astUtils.getStaticPropertyName(node));
}
/**
* Reports if the `CallExpression` node has evaluated argument.
* @param {ASTNode} node A CallExpression to check.
* @returns {void}
*/
function reportImpliedEvalCallExpression(node) {
const [firstArgument] = node.arguments;
if (firstArgument) {
const staticValue = getStaticValue(firstArgument, context.getScope());
const isStaticString = staticValue && typeof staticValue.value === "string";
const isString = isStaticString || isEvaluatedString(firstArgument);
if (isString) {
context.report({
node,
messageId: "impliedEval"
});
}
}
}
/**
* Reports calls of `implied eval` via the global references.
* @param {Variable} globalVar A global variable to check.
* @returns {void}
*/
function reportImpliedEvalViaGlobal(globalVar) {
const { references, name } = globalVar;
references.forEach(ref => {
const identifier = ref.identifier;
let node = identifier.parent;
while (isSpecifiedMember(node, [name])) {
node = node.parent;
}
if (isSpecifiedMember(node, EVAL_LIKE_FUNCS)) {
const parent = node.parent;
if (parent.type === "CallExpression" && parent.callee === node) {
reportImpliedEvalCallExpression(parent);
}
}
});
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
return {
CallExpression(node) {
if (isSpecifiedIdentifier(node.callee, EVAL_LIKE_FUNCS)) {
reportImpliedEvalCallExpression(node);
}
},
"Program:exit"() {
const globalScope = context.getScope();
GLOBAL_CANDIDATES
.map(candidate => astUtils.getVariableByName(globalScope, candidate))
.filter(globalVar => !!globalVar && globalVar.defs.length === 0)
.forEach(reportImpliedEvalViaGlobal);
}
};
}
};
| Java |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace EthereumSamuraiApiCaller.Models
{
using Newtonsoft.Json;
using System.Linq;
public partial class BlockResponse
{
/// <summary>
/// Initializes a new instance of the BlockResponse class.
/// </summary>
public BlockResponse()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the BlockResponse class.
/// </summary>
public BlockResponse(long number, string blockHash = default(string), string gasUsed = default(string), string gasLimit = default(string), string parentHash = default(string))
{
BlockHash = blockHash;
GasUsed = gasUsed;
GasLimit = gasLimit;
ParentHash = parentHash;
Number = number;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "blockHash")]
public string BlockHash { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "gasUsed")]
public string GasUsed { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "gasLimit")]
public string GasLimit { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "parentHash")]
public string ParentHash { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "number")]
public long Number { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
//Nothing to validate
}
}
}
| Java |
//
// BPPopToast.h
// BPKITsDemo
//
// Created by mikeooye on 15-3-28.
// Copyright (c) 2015年 ihojin. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface BPPopToast : UIView
@property (copy, nonatomic) NSString *text;
- (void)popToastAtRect:(CGRect)rect inView:(UIView *)view;
@end
@interface NSString (BPPopToast)
- (void)popToastAtRect:(CGRect)rect inView:(UIView *)view;
@end | Java |
/*
---------------------------------------------------------------------------
Open Asset Import Library (ASSIMP)
---------------------------------------------------------------------------
Copyright (c) 2006-2010, ASSIMP Development Team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the ASSIMP team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the ASSIMP Development Team.
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.
---------------------------------------------------------------------------
*/
#include "stdafx.h"
#include "assimp_view.h"
#include "RichEdit.h"
namespace AssimpView {
/* extern */ CLogWindow CLogWindow::s_cInstance;
extern HKEY g_hRegistry;
// header for the RTF log file
static const char* AI_VIEW_RTF_LOG_HEADER =
"{\\rtf1"
"\\ansi"
"\\deff0"
"{"
"\\fonttbl{\\f0 Courier New;}"
"}"
"{\\colortbl;"
"\\red255\\green0\\blue0;" // red for errors
"\\red255\\green120\\blue0;" // orange for warnings
"\\red0\\green150\\blue0;" // green for infos
"\\red0\\green0\\blue180;" // blue for debug messages
"\\red0\\green0\\blue0;" // black for everything else
"}}";
//-------------------------------------------------------------------------------
// Message procedure for the log window
//-------------------------------------------------------------------------------
INT_PTR CALLBACK LogDialogProc(HWND hwndDlg,UINT uMsg,
WPARAM wParam,LPARAM lParam)
{
lParam;
switch (uMsg)
{
case WM_INITDIALOG:
{
return TRUE;
}
case WM_SIZE:
{
int x = LOWORD(lParam);
int y = HIWORD(lParam);
SetWindowPos(GetDlgItem(hwndDlg,IDC_EDIT1),NULL,0,0,
x-10,y-12,SWP_NOMOVE|SWP_NOZORDER);
return TRUE;
}
case WM_CLOSE:
EndDialog(hwndDlg,0);
CLogWindow::Instance().bIsVisible = false;
return TRUE;
};
return FALSE;
}
//-------------------------------------------------------------------------------
void CLogWindow::Init ()
{
this->hwnd = ::CreateDialog(g_hInstance,MAKEINTRESOURCE(IDD_LOGVIEW),
NULL,&LogDialogProc);
if (!this->hwnd)
{
CLogDisplay::Instance().AddEntry("[ERROR] Unable to create logger window",
D3DCOLOR_ARGB(0xFF,0,0xFF,0));
}
// setup the log text
this->szText = AI_VIEW_RTF_LOG_HEADER;;
this->szPlainText = "";
}
//-------------------------------------------------------------------------------
void CLogWindow::Show()
{
if (this->hwnd)
{
ShowWindow(this->hwnd,SW_SHOW);
this->bIsVisible = true;
// contents aren't updated while the logger isn't displayed
this->Update();
}
}
//-------------------------------------------------------------------------------
void CMyLogStream::write(const char* message)
{
CLogWindow::Instance().WriteLine(message);
}
//-------------------------------------------------------------------------------
void CLogWindow::Clear()
{
this->szText = AI_VIEW_RTF_LOG_HEADER;;
this->szPlainText = "";
this->Update();
}
//-------------------------------------------------------------------------------
void CLogWindow::Update()
{
if (this->bIsVisible)
{
SETTEXTEX sInfo;
sInfo.flags = ST_DEFAULT;
sInfo.codepage = CP_ACP;
SendDlgItemMessage(this->hwnd,IDC_EDIT1,
EM_SETTEXTEX,(WPARAM)&sInfo,( LPARAM)this->szText.c_str());
}
}
//-------------------------------------------------------------------------------
void CLogWindow::Save()
{
char szFileName[MAX_PATH];
DWORD dwTemp = MAX_PATH;
if(ERROR_SUCCESS != RegQueryValueEx(g_hRegistry,"LogDestination",NULL,NULL,
(BYTE*)szFileName,&dwTemp))
{
// Key was not found. Use C:
strcpy(szFileName,"");
}
else
{
// need to remove the file name
char* sz = strrchr(szFileName,'\\');
if (!sz)sz = strrchr(szFileName,'/');
if (!sz)*sz = 0;
}
OPENFILENAME sFilename1 = {
sizeof(OPENFILENAME),
g_hDlg,GetModuleHandle(NULL),
"Log files\0*.txt", NULL, 0, 1,
szFileName, MAX_PATH, NULL, 0, NULL,
"Save log to file",
OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY | OFN_NOCHANGEDIR,
0, 1, ".txt", 0, NULL, NULL
};
if(GetSaveFileName(&sFilename1) == 0) return;
// Now store the file in the registry
RegSetValueExA(g_hRegistry,"LogDestination",0,REG_SZ,(const BYTE*)szFileName,MAX_PATH);
FILE* pFile = fopen(szFileName,"wt");
fprintf(pFile,this->szPlainText.c_str());
fclose(pFile);
CLogDisplay::Instance().AddEntry("[INFO] The log file has been saved",
D3DCOLOR_ARGB(0xFF,0xFF,0xFF,0));
}
//-------------------------------------------------------------------------------
void CLogWindow::WriteLine(const char* message)
{
this->szPlainText.append(message);
this->szPlainText.append("\r\n");
if (0 != this->szText.length())
{
this->szText.resize(this->szText.length()-1);
}
switch (message[0])
{
case 'e':
case 'E':
this->szText.append("{\\pard \\cf1 \\b \\fs18 ");
break;
case 'w':
case 'W':
this->szText.append("{\\pard \\cf2 \\b \\fs18 ");
break;
case 'i':
case 'I':
this->szText.append("{\\pard \\cf3 \\b \\fs18 ");
break;
case 'd':
case 'D':
this->szText.append("{\\pard \\cf4 \\b \\fs18 ");
break;
default:
this->szText.append("{\\pard \\cf5 \\b \\fs18 ");
break;
}
std::string _message = message;
for (unsigned int i = 0; i < _message.length();++i)
{
if ('\\' == _message[i] ||
'}' == _message[i] ||
'{' == _message[i])
{
_message.insert(i++,"\\");
}
}
this->szText.append(_message);
this->szText.append("\\par}}");
if (this->bIsVisible && this->bUpdate)
{
SETTEXTEX sInfo;
sInfo.flags = ST_DEFAULT;
sInfo.codepage = CP_ACP;
SendDlgItemMessage(this->hwnd,IDC_EDIT1,
EM_SETTEXTEX,(WPARAM)&sInfo,( LPARAM)this->szText.c_str());
}
return;
}
}; //! AssimpView | Java |
module Tasklist
end
| Java |
---
title: "Exploring UIAlertController"
date: 2014-09-07 00:00
link_to: swift
---
This morning, I was working on the [sample app](https://github.com/AshFurrow/Moya/issues/39) for [Moya](https://github.com/AshFurrow/Moya), a network abstraction framework that I’ve built on top of [Alamofire](https://github.com/Alamofire/Alamofire). I needed a way to grab some user text input, so I turned to `UIAlertView`. Turns out that that’s deprecated in favour of `UIAlertController`. Hmm.
<!-- more -->
Looking around the internet, there weren’t very many examples of how to use this cool new class, and the [documentation](https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIAlertController_class/) was sparse at best. Let’s take a look at the high-level API and then get into some of the nitty-gritty. (I’m going to write this in Swift because I am not a [dinosaur](http://t.co/Q2hvacChLu).)
`UIAlertController` is a `UIViewController` subclass. This contrasts with `UIAlertView`, a `UIView` subclass. View controllers are (or at least, should be) the main unit of composition when writing iOS applications. It makes a lot of sense that Apple would replace alert views with alert view _controllers_. That’s cool.
Creating an alert view controller is pretty simple. Just use the initializer to create one and then present it to the user as you would present any other view controller.
```swift let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert) presentViewController(alertController, animated: true, completion: nil) ```
Pretty straightforward. I’m using the `.Alert` preferred style, but you can use the `.ActionSheet` instead. I’m using this as a replacement for `UIAlertView`, so I’ll just discuss the alert style.
If you ran this code, you’d be presented with something like the following (on beta 7).

Weird. The title is there, but the message is not present. There are also no buttons, so you can’t dismiss the controller. It’s there until you relaunch your app. Sucky.
Turns out if you want buttons, you’ve got to explicitly add them to the controller before presenting it.
```swift let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in }) let cancel = UIAlertAction(title: "Cancel", style: .Cancel) { (action) -> Void in } alertController.addAction(ok) alertController.addAction(cancel) ```
This is _worlds_ better than `UIAlertView`, despite being much more verbose. First of all, you can have multiple cancel or destructive buttons. You also specify individual closures to be executed when a button is pressed instead of some shitty delegate callback telling you which button _index_ was pressed. (If anyone out there makes a `UIAlertController+Blocks` category, I will find you, and I _will_ kill you.)

If we added the above configuration to our code, we’d get the following.

Way better. Weird that the message is now showing up. Maybe it’s a bug, or maybe it’s intended behaviour. Apple, you so cray cray. Anyway, you should also notice that the “OK” and “Cancel” buttons have been styled and positioned according to iOS conventions. Neato.
What _I_ needed, however, was user input. This was possible with `UIAlertView`, so it should be possible with `UIAlertController`, right? Well, kinda. There’s an encouraging instance method named `addTextFieldWithConfigurationHandler()`, but using it is not so straightforward. Let me show you what I mean.
```swift alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in // Here you can configure the text field (eg: make it secure, add a placeholder, etc) } ```
Straightforward. Run the code, get the following.

The question now is this: how do you, in the closure for the “OK” button, access the contents of the text field?

There is no way for you to directly access the text field from the closure invoked when a button is pressed. [This](http://stackoverflow.com/questions/24172593/access-input-from-uialertcontroller) StackOverflow question has two possible answers. You can access the `textFields` array on the controller (assuming that the order of that array is the same as the order which you added the text fields), but this causes a reference cycle (the alert action has a strong reference to the alert view controller, which has a strong reference to the alert action). This _does_ cause a memory leak for each controller that you present.

The other answer suggests storing the text field that’s passed into the configuration closure in a property on the presenting controller, which can later be accessed. That’s a _very_ Objective-C way of solving this problem.
So what do we do? Well, I’ve been writing Swift lately, and whenever I come across a problem like this, I think “if I had [five years of Swift experience](http://instagram.com/p/rWyQdUDBhH), what would _I_ do?” My answer was the following.
Let’s create a local variable, a `UITextField?` optional. In the configuration closure for the text field, assign the local variable to the text field that we’re passed in. Then we can access that local variable in our alert action closure. Sweet. The full implementation looks like this.
```swift var inputTextField: UITextField? let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert) let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in // Do whatever you want with inputTextField?.text println("\(inputTextField?.text)") }) let cancel = UIAlertAction(title: "Cancel", style: .Cancel) { (action) -> Void in } alertController.addAction(ok) alertController.addAction(cancel) alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in inputTextField = textField } presentViewController(alertController, animated: true, completion: nil) ```
I like this a lot. It avoids polluting our object with unnecessary properties, avoids memory leaks, and seems pretty “Swift”. I’ve created a [GitHub repo](https://github.com/AshFurrow/UIAlertController-Example) that I’ll keep up to date with future betas, etc.

So yeah. The new `UIAlertController` has some great benefits:
- It’s explicit
- It conforms to iOS composability conventions
- It’s got a clear API
- It’s reusable in different contexts (iWatch vs iWatch mini)
The drawbacks are:
- It’s unfamiliar
As we march forward into this brave new world of Swift, we need to reevaluate our approaches to familiar problems. Just because a solution that worked well in Objective-C might work OK in Swift doesn’t make it a solution _well_ suited for use in Swift. As developers, we should keep an open mind about new ideas and experiment. The way I look at it is like this: right now, the community is pretty new at Swift. We’re racing in all different directions because [no one](http://robnapier.net/i-dont-know-swift) really knows what the best practices are, yet. We need this expansion in all directions, even if a lot of those directions are going to turn out to be bad ideas. If we don’t throw it all against the wall, we won’t figure out what sticks.
So next time you try and do something and get confused because Swift is unfamiliar, try all kinds of things. Could be you end up creating a brand new convention that’s adopted by the whole iOS community for years to come.
| Java |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Library to generate items for Sortable.js
*/
class Sortable {
protected $CI;
protected $mItems;
protected $mPostName = 'sortable_ids';
public function __construct()
{
$this->CI =& get_instance();
$this->CI->load->library('parser');
$this->CI->load->library('system_message');
}
// Get items to be sorted
public function init($model, $order_field = 'pos')
{
$this->CI->load->model($model, 'm');
$ids = $this->CI->input->post($this->mPostName);
// save to database
if ( !empty($ids) )
{
for ($i=0; $i<count($ids); $i++)
{
$updated = $this->CI->m->update($ids[$i], array($order_field => $i+1));
}
// refresh page (interrupt other logic)
$this->CI->system_message->set_success('Successfully updated sort order.');
refresh();
}
// return all records in sorted order
$this->CI->db->order_by($order_field, 'ASC');
$items = $this->CI->m->get_all();
$this->mItems = $items;
return $this;
}
// Render template
public function render($label_template = '{title}', $back_url = NULL)
{
if ( empty($this->mItems) )
{
return '<p>No records are found.</p>';
}
else
{
$html = box_open('Sort Order', 'primary');
// Render form with alert message
$html.= '<form action="'.current_url().'" method="POST">';
$html.= $this->CI->system_message->render();
$html.= '<p>Drag and drop below items to sort them in ascending order:</p>';
// Generate item list by CodeIgniter Template Parser
$template = '<ul class="sortable list-group">
{items}
<li class="list-group-item">
<strong>'.$label_template.'</strong>
<input type="hidden" name="'.$this->mPostName.'[]" value="{id}" />
</li>
{/items}
</ul>';
$data = array('items' => $this->mItems);
$html.= $this->CI->parser->parse_string($template, $data, TRUE);
if ($back_url!=NULL)
$html.= btn('Back', $back_url, 'reply', 'bg-purple').' ';
$html.= btn_submit('Save');
$html.= '</form>';
$html.= box_close();
return $html;
}
}
} | Java |
import NodeFunction from '../core/NodeFunction.js';
import NodeFunctionInput from '../core/NodeFunctionInput.js';
const declarationRegexp = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
const propertiesRegexp = /[a-z_0-9]+/ig;
const pragmaMain = '#pragma main';
const parse = ( source ) => {
const pragmaMainIndex = source.indexOf( pragmaMain );
const mainCode = pragmaMainIndex !== - 1 ? source.substr( pragmaMainIndex + pragmaMain.length ) : source;
const declaration = mainCode.match( declarationRegexp );
if ( declaration !== null && declaration.length === 5 ) {
// tokenizer
const inputsCode = declaration[ 4 ];
const propsMatches = [];
let nameMatch = null;
while ( ( nameMatch = propertiesRegexp.exec( inputsCode ) ) !== null ) {
propsMatches.push( nameMatch );
}
// parser
const inputs = [];
let i = 0;
while ( i < propsMatches.length ) {
const isConst = propsMatches[ i ][ 0 ] === 'const';
if ( isConst === true ) {
i ++;
}
let qualifier = propsMatches[ i ][ 0 ];
if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
i ++;
} else {
qualifier = '';
}
const type = propsMatches[ i ++ ][ 0 ];
let count = Number.parseInt( propsMatches[ i ][ 0 ] );
if ( Number.isNaN( count ) === false ) i ++;
else count = null;
const name = propsMatches[ i ++ ][ 0 ];
inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
}
//
const blockCode = mainCode.substring( declaration[ 0 ].length );
const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
const type = declaration[ 2 ];
const presicion = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
const headerCode = pragmaMainIndex !== - 1 ? source.substr( 0, pragmaMainIndex ) : '';
return {
type,
inputs,
name,
presicion,
inputsCode,
blockCode,
headerCode
};
} else {
throw new Error( 'FunctionNode: Function is not a GLSL code.' );
}
};
class GLSLNodeFunction extends NodeFunction {
constructor( source ) {
const { type, inputs, name, presicion, inputsCode, blockCode, headerCode } = parse( source );
super( type, inputs, name, presicion );
this.inputsCode = inputsCode;
this.blockCode = blockCode;
this.headerCode = headerCode;
}
getCode( name = this.name ) {
const headerCode = this.headerCode;
const presicion = this.presicion;
let declarationCode = `${ this.type } ${ name } ( ${ this.inputsCode.trim() } )`;
if ( presicion !== '' ) {
declarationCode = `${ presicion } ${ declarationCode }`;
}
return headerCode + declarationCode + this.blockCode;
}
}
export default GLSLNodeFunction;
| Java |
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var router_1 = require('@angular/router');
var app_service_1 = require("./app-service");
var AppComponent = (function () {
function AppComponent(breadCrumbSvc, _router) {
this.breadCrumbSvc = breadCrumbSvc;
this._router = _router;
this.breadCrumbSvc.setBreadCrumb('Project Dashboard');
}
AppComponent.prototype.navigateHome = function () {
this._router.navigate(['home']);
;
};
AppComponent = __decorate([
core_1.Component({
selector: 'ts-app',
templateUrl: '/app/app-component.html'
}),
__metadata('design:paramtypes', [app_service_1.BreadcrumbService, router_1.Router])
], AppComponent);
return AppComponent;
}());
exports.AppComponent = AppComponent;
| Java |
using Feria_Desktop.View.Usuario;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Feria_Desktop.View.Mantenedor
{
/// <summary>
/// Lógica de interacción para Bodega.xaml
/// </summary>
public partial class Bodega : Page
{
private vEditarBodega modEditarBodega;
public Bodega()
{
InitializeComponent();
}
private void btnNuevo_Click(object sender, RoutedEventArgs e)
{
modEditarBodega = new vEditarBodega();
modEditarBodega.ShowDialog();
}
}
}
| Java |
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function arrayCopy(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++i < length) {
array[i] = source[i];
}
return array;
}
module.exports = arrayCopy;
| Java |
//
// SNPGetStreamOperation.h
// Snapper
//
// Created by Paul Schifferer on 12/23/12.
// Copyright (c) 2012 Pilgrimage Software. All rights reserved.
//
#import "SNPBaseAppTokenOperation.h"
@interface SNPGetStreamOperation : SNPBaseAppTokenOperation
// -- Properties --
@property (nonatomic, assign) NSInteger streamId;
// -- Initializers --
- (nonnull instancetype)initWithStreamId:(NSUInteger)streamId
appToken:(nonnull NSString*)appToken
finishBlock:(nonnull void (^)(SNPResponse* _Nonnull response))finishBlock;
@end
| Java |
package de.uni.bremen.stummk.psp.calculation;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import de.uni.bremen.stummk.psp.control.BarChart;
import de.uni.bremen.stummk.psp.control.LineChart;
import de.uni.bremen.stummk.psp.control.PieChart;
import de.uni.bremen.stummk.psp.data.PSPProject;
import de.uni.bremen.stummk.psp.data.ScheduleEntry;
import de.uni.bremen.stummk.psp.utility.CheckOperation;
import de.uni.bremen.stummk.psp.utility.Constants;
import de.uni.bremen.stummk.psp.utility.DataIO;
import de.uni.bremen.stummk.psp.utility.FileHash;
/**
* Class represents an action of the toolbar in the editor
*
* @author Konstantin
*
*/
public class EditorToolbarAction extends Action implements IWorkbenchAction {
private EditorToolbarController etc;
/**
* Constructor
*
* @param id the Id of the Action
* @param editorToolbarController the {@link EditorToolbarController} of the
* {@link EditorToolbarAction}
*/
public EditorToolbarAction(String id, EditorToolbarController editorToolbarController) {
setId(id);
this.etc = editorToolbarController;
}
@Override
public void run() {
handleAction(getId());
}
private void handleAction(String id) {
// execute action depending on id
switch (id) {
case Constants.COMMAND_SYNC:
exportData();
break;
case Constants.COMMAND_PLAN_ACTUAL_DIAGRAM:
new BarChart(etc.getProjectPlanSummary(),
"Plan vs. Actual Values - " + etc.getProjectPlanSummary().getProject().getProjectName());
break;
case Constants.COMMAND_TIME_IN_PHASE_PERCENTAGE:
new PieChart(etc.getProjectPlanSummary(), Constants.KEY_TIME_IN_PHASE_IDX,
"Distribution of time in phase - " + etc.getProjectPlanSummary().getProject().getProjectName());
break;
case Constants.COMMAND_DEFECT_INJECTED_PERCENTAGE:
new PieChart(etc.getProjectPlanSummary(), Constants.KEY_DEFECTS_INJECTED_IDX,
"Distribution of injected defects - " + etc.getProjectPlanSummary().getProject().getProjectName());
break;
case Constants.COMMAND_DEFECT_REMOVED_PERCENTAGE:
new PieChart(etc.getProjectPlanSummary(), Constants.KEY_DEFECTS_REMOVED_IDX,
"Distribution of removed defects - " + etc.getProjectPlanSummary().getProject().getProjectName());
break;
case Constants.COMMAND_TIME_TRACKING:
List<ScheduleEntry> entries =
Manager.getInstance().getSchedulePlanning(etc.getProjectPlanSummary().getProject().getProjectName());
new LineChart("Time Progress in Project - " + etc.getProjectPlanSummary().getProject().getProjectName(),
Constants.CHART_TIME, entries);
break;
case Constants.COMMAND_EARNED_VALUE_TRACKING:
List<ScheduleEntry> e =
Manager.getInstance().getSchedulePlanning(etc.getProjectPlanSummary().getProject().getProjectName());
new LineChart("Earned Value Tracking in Project - " + etc.getProjectPlanSummary().getProject().getProjectName(),
Constants.CHART_VALUE, e);
break;
}
}
private void exportData() {
// exports data to psp-file and create hash
try {
Shell activeShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
IRunnableWithProgress op = new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
monitor.beginTask("Export data to psp.csv file", 2);
PSPProject psp =
Manager.getInstance().loadBackupProject(etc.getProjectPlanSummary().getProject().getProjectName());
if (psp != null && psp.getSummary() != null) {
DataIO.saveToFile(etc.getProjectPlanSummary().getProject().getProjectName(), psp, null);
}
monitor.worked(1);
if (psp != null && psp.getSummary() != null) {
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
for (IProject project : projects) {
if (project.getName().equals(etc.getProjectPlanSummary().getProject().getProjectName())) {
IFile file = CheckOperation.getProjectFile(project);
String hash = FileHash.hash(file);
try {
file.setPersistentProperty(Constants.PROPERTY_HASH, hash);
} catch (CoreException e) {
e.printStackTrace();
}
}
}
}
monitor.worked(1);
} finally {
monitor.done();
}
}
};
new ProgressMonitorDialog(activeShell).run(true, true, op);
} catch (InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void dispose() {}
}
| Java |
1.0.0 / 2014-12-24
==================
* 0.1.2
- Add X-XSS-Protection header options
* 0.1.1
- Request body or query sanitize | Java |
---
layout: post
title: "From interaction-based to state-based testing"
description: "Indiscriminate use of Mocks and Stubs can lead to brittle test suites. A more functional design can make state-based testing easier, leading to more robust test suites."
date: 2019-02-18 8:19 UTC
tags: [Unit Testing, Article Series]
---
{% include JB/setup %}
<div id="post">
<p>
<em>{{ page.description }}</em>
</p>
<p>
The original premise of <a href="http://amzn.to/YPdQDf">Refactoring</a> was that in order to refactor, you must have a trustworthy suite of unit tests, so that you can be confident that you didn't break any functionality.
<blockquote>
<p>"to refactor, the essential precondition is [...] solid tests"</p>
<footer><cite>Martin Fowler, <a href="http://amzn.to/YPdQDf">Refactoring</a></cite></footer>
</blockquote>
The idea is that you can change how the code is organised, and as long as you don't break any tests, all is good. The experience that most people seem to have, though, is that when they change something in the code, tests break.
</p>
<p>
This is a well-known test smell. In <a href="http://bit.ly/xunitpatterns">xUnit Test Patterns</a> this is called <em>Fragile Test</em>, and it's often caused by <em>Overspecified Software</em>. Even if you follow the proper practice of using <a href="/2013/10/23/mocks-for-commands-stubs-for-queries">Mocks for Commands, Stubs for Queries</a>, you can still end up with a code base where the tests are highly coupled to implementation details of the software.
</p>
<p>
The cause is often that when relying on Mocks and Stubs, test verification hinges on how the System Under Test (SUT) interacts with its dependencies. For that reason, we can call such tests <em>interaction-based tests</em>. For more information, watch my Pluralsight course <a href="{{ site.production_url }}/advanced-unit-testing">Advanced Unit Testing</a>.
</p>
<h3 id="fb4f2eb1191943c09450c7281a6c8cb0">
Lessons from functional programming <a href="#fb4f2eb1191943c09450c7281a6c8cb0" title="permalink">#</a>
</h3>
<p>
Another way to verify the outcome of a test is to inspect the state of the system after exercising the SUT. We can, quite naturally, call this <em>state-based testing</em>. In object-oriented design, this can lead to other problems. <a href="http://natpryce.com">Nat Pryce</a> has pointed out that <a href="http://natpryce.com/articles/000342.html">state-based testing breaks encapsulation</a>.
</p>
<p>
Interestingly, in his article, Nat Pryce concludes:
<blockquote>
"I have come to think of object oriented programming as an inversion of functional programming. In a lazy functional language data is pulled through functions that transform the data and combine it into a single result. In an object oriented program, data is pushed out in messages to objects that transform the data and push it out to other objects for further processing."
</blockquote>
That's an impressively perceptive observation to make in 2004. I wish I was that perspicacious, but I only <a href="{{ site.production_url }}/functional-architecture-with-fsharp">reached a similar conclusion ten years later</a>.
</p>
<p>
Functional programming is based on the fundamental principle of <a href="https://en.wikipedia.org/wiki/Referential_transparency">referential transparency</a>, which, among other things, means that data must be immutable. Thus, no objects change state. Instead, functions can return data that contains immutable state. In unit tests, you can verify that return values are as expected. <a href="/2015/05/07/functional-design-is-intrinsically-testable">Functional design is intrinsically testable</a>; we can consider it a kind of state-based testing, although the states you'd be verifying are immutable return values.
</p>
<p>
In this article series, you'll see three different styles of testing, from interaction-based testing with Mocks and Stubs in C#, over strictly functional state-based testing in <a href="https://www.haskell.org">Haskell</a>, to pragmatic state-based testing in <a href="https://fsharp.org">F#</a>, finally looping back to C# to apply the lessons from functional programming.
<ul>
<li><a href="/2019/02/25/an-example-of-interaction-based-testing-in-c">An example of interaction-based testing in C#</a></li>
<li><a href="/2019/03/11/an-example-of-state-based-testing-in-haskell">An example of state-based testing in Haskell</a></li>
<li><a href="/2019/03/25/an-example-of-state-based-testing-in-f">An example of state based-testing in F#</a></li>
<li><a href="/2019/04/01/an-example-of-state-based-testing-in-c">An example of state-based testing in C#</a></li>
<li><a href="/2019/04/08/a-pure-test-spy">A pure Test Spy</a></li>
</ul>
The code for all of these articles is <a href="https://github.com/ploeh/UserManagement">available on GitHub</a>.
</p>
<h3 id="d370a0ae3bc34440b68f8fddab6c1b25">
Summary <a href="#d370a0ae3bc34440b68f8fddab6c1b25" title="permalink">#</a>
</h3>
<p>
Adopting a more functional design, even in a fundamentally object-oriented language like C# can, in my experience, lead to a more sustainable code base. Various maintenance tasks become easier, including unit tests. Functional programming, however, is no panacea. My intent with this article series is only to inspire; to show alternatives to the ways things are normally done. Adopting one of those alternatives could lead to better code, but you must still exercise context-specific judgement.
</p>
<p>
<strong>Next:</strong> <a href="/2019/02/25/an-example-of-interaction-based-testing-in-c">An example of interaction-based testing in C#</a>.
</p>
</div> | Java |
/// This is the sensor class
///
/// Sensor is a box2d fixture that is attached to a parent body
/// Sensors are used to detect entities in an area.
#pragma once
#include <AFP/Scene/SceneNode.hpp>
#include <AFP/Entity/Entity.hpp>
#include <AFP/Entity/Character.hpp>
namespace AFP
{
class Sensor : public SceneNode
{
public:
enum Type
{
Foot,
Surround,
Vision,
Jump
};
/// Constructor
///
///
Sensor(Entity* parent, Type type);
/// Return sensor category
///
/// Returns the sensor category based on the type
virtual unsigned int getCategory() const;
/// Create foot sensor
///
/// Creates a foot sensor on feet
void createFootSensor(float sizeX, float sizeY);
/// Create vision sensor
///
/// Creates a vision sensor for the entity.
///Takes radius in meters and the angle in degrees as parameters
void createVisionSensor(float radius, float angle);
/// Create surround sensor
///
/// Creates a foot sensor on feet
void createSurroundSensor(float radius);
/// Create foot sensor
///
/// Creates a foot sensor on feet
void createJumpSensor(float sizeX, float sizeY);
/// Begin contact
///
/// Begin contact with an entity
void beginContact();
/// Begin contact
///
/// Begin contact with an character
void beginContact(Character& character);
/// End contact
///
/// End contact with an entity
void endContact();
/// End contact
///
/// End contact with a character
void endContact(Character& character);
private:
/// Update
///
/// Update sensor data.
virtual void updateCurrent(sf::Time dt, CommandQueue& commands);
private:
/// Sensor fixture
///
/// Sensors fixture is linked to the body of the parent.
b2Fixture* mFixture;
/// Parent entity
///
/// Entity on which the sensor is attached to
Entity* mParent;
/// Type
///
/// Type of the sensor
Type mType;
};
}
| Java |
# Liplis-iOS
デスクトップマスコット LiplisのiOS版です。仮想デスクトップ上でキャラクターがおしゃべりします。
# ライセンス
MITライセンス
| Java |
package insanityradio.insanityradio;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class PlayPauseReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
FragmentNowPlaying.getInstance().playPauseButtonTapped(false);
} catch (NullPointerException e) {
Intent startActivityIntent = new Intent(context.getApplicationContext(), MainActivity.class);
startActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startActivityIntent);
}
}
}
| Java |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['HERTZ_SECRET_KEY']
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ['HERTZ_DEBUG'] != 'False'
ALLOWED_HOSTS = ['*' if DEBUG else os.environ['HERTZ_HOST']]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'widget_tweaks',
'attendance',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'hertz.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'hertz.wsgi.application'
# Database
if 'DATABASE_HOST' in os.environ:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ['POSTGRES_PASSWORD'],
'HOST': os.environ['DATABASE_HOST'],
'PORT': 5432,
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Sao_Paulo'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# STATICFILES_DIRS = [
# os.path.join(BASE_DIR, 'static'),
# ]
LOGIN_REDIRECT_URL = '/'
LOGIN_URL = '/login'
| Java |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Robot - Robot")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Robot - Robot")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("960726e6-c6b1-4271-8c7e-94110f97ad98")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Java |
<?php
/* FOSUserBundle:Resetting:request_content.html.twig */
class __TwigTemplate_16fccc8b4081822ba4c49543c44f48b24850d6b4ad9846152c39968be5b4e7c7 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 2
echo "
<form action=\"";
// line 3
echo $this->env->getExtension('routing')->getPath("fos_user_resetting_send_email");
echo "\" method=\"POST\" class=\"fos_user_resetting_request\">
<div>
";
// line 5
if (array_key_exists("invalid_username", $context)) {
// line 6
echo " <p>";
echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("resetting.request.invalid_username", array("%username%" => (isset($context["invalid_username"]) ? $context["invalid_username"] : $this->getContext($context, "invalid_username"))), "FOSUserBundle"), "html", null, true);
echo "</p>
";
}
// line 8
echo " <label for=\"username\">";
echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("resetting.request.username", array(), "FOSUserBundle"), "html", null, true);
echo "</label>
<input type=\"text\" id=\"username\" name=\"username\" required=\"required\" />
</div>
<div>
<input type=\"submit\" value=\"";
// line 12
echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("resetting.request.submit", array(), "FOSUserBundle"), "html", null, true);
echo "\" />
</div>
</form>
";
}
public function getTemplateName()
{
return "FOSUserBundle:Resetting:request_content.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 43 => 12, 35 => 8, 29 => 6, 27 => 5, 22 => 3, 19 => 2,);
}
}
| Java |
export default (callback) => {
setTimeout(() => {
callback();
setTimeout(() => {
callback();
}, 3000);
}, 3000);
} | Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>アルゴリズム計算量入門 〜 ② - イノベーション エンジニアブログ</title>
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="description" content="">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="アルゴリズム計算量入門 〜 ②">
<meta name="twitter:description" content="">
<meta property="og:type" content="article">
<meta property="og:title" content="アルゴリズム計算量入門 〜 ②">
<meta property="og:description" content="">
<link href="/favicon.ico" rel="shortcut icon" type="image/x-icon">
<link href="/apple-touch-icon-precomposed.png" rel="apple-touch-icon">
<script type="text/javascript">
var _trackingid = 'LFT-10003-1';
(function() {
var lft = document.createElement('script'); lft.type = 'text/javascript'; lft.async = true;
lft.src = document.location.protocol + '//test.list-finder.jp/js/ja/track_test.js';
var snode = document.getElementsByTagName('script')[0]; snode.parentNode.insertBefore(lft, snode);
})();
</script>
<script type="text/javascript">
var _trackingid = 'LFT-10003-1';
(function() {
var lft = document.createElement('script'); lft.type = 'text/javascript'; lft.async = true;
lft.src = document.location.protocol + '//track.list-finder.jp/js/ja/track_prod_wao.js';
var snode = document.getElementsByTagName('script')[0]; snode.parentNode.insertBefore(lft, snode);
})();
</script>
<link rel="stylesheet" type="text/css" href="//tech.innovation.co.jp/themes/uno/assets/css/uno.css?v=1.0.0" />
<link rel="canonical" href="http://tech.innovation.co.jp/2018/06/25/Introduction-of-Computational-Complexity-2.html" />
<meta property="og:site_name" content="イノベーション エンジニアブログ" />
<meta property="og:type" content="article" />
<meta property="og:title" content="アルゴリズム計算量入門 〜 ②" />
<meta property="og:description" content="どうも、bigenです。 なぜ2本連続で書いているかというと、先週のブログ当番をブッチしてしまった罰ゲームです! そんなわけで、 前回の記事に引き続き、ソートアルゴリズムの計算量について見ていこうと思います。 【前回の記事のまとめ】 バブルソート: 時間計算量 O(n2), 空間計算量O(n) バケツソート: 時間計算量 O(m + n), 空間計算量O(m + n) マージソート: 時間計算量 O(n log n), 空間計算量O(n) 【まとめおわり】 今回は、実際にphpでそれぞれのアルゴリズムを動かして、「計算量本当にそれであってん..." />
<meta property="og:url" content="http://tech.innovation.co.jp/2018/06/25/Introduction-of-Computational-Complexity-2.html" />
<meta property="article:published_time" content="2018-06-24T15:00:00.000Z" />
<meta property="article:modified_time" content="2018-07-25T20:24:35.348Z" />
<meta property="article:tag" content="Complexity" />
<meta property="article:tag" content="Sort Algorithm" />
<meta property="article:tag" content="bigen" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="アルゴリズム計算量入門 〜 ②" />
<meta name="twitter:description" content="どうも、bigenです。 なぜ2本連続で書いているかというと、先週のブログ当番をブッチしてしまった罰ゲームです! そんなわけで、 前回の記事に引き続き、ソートアルゴリズムの計算量について見ていこうと思います。 【前回の記事のまとめ】 バブルソート: 時間計算量 O(n2), 空間計算量O(n) バケツソート: 時間計算量 O(m + n), 空間計算量O(m + n) マージソート: 時間計算量 O(n log n), 空間計算量O(n) 【まとめおわり】 今回は、実際にphpでそれぞれのアルゴリズムを動かして、「計算量本当にそれであってん..." />
<meta name="twitter:url" content="http://tech.innovation.co.jp/2018/06/25/Introduction-of-Computational-Complexity-2.html" />
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "Article",
"publisher": "イノベーション エンジニアブログ",
"author": {
"@type": "Person",
"name": null,
"image": "https://avatars2.githubusercontent.com/u/39402426?v=4",
"url": "undefined/author/undefined",
"sameAs": ""
},
"headline": "アルゴリズム計算量入門 〜 ②",
"url": "http://tech.innovation.co.jp/2018/06/25/Introduction-of-Computational-Complexity-2.html",
"datePublished": "2018-06-24T15:00:00.000Z",
"dateModified": "2018-07-25T20:24:35.348Z",
"keywords": "Complexity, Sort Algorithm, bigen",
"description": "どうも、bigenです。 なぜ2本連続で書いているかというと、先週のブログ当番をブッチしてしまった罰ゲームです! そんなわけで、 前回の記事に引き続き、ソートアルゴリズムの計算量について見ていこうと思います。 【前回の記事のまとめ】 バブルソート: 時間計算量 O(n2), 空間計算量O(n) バケツソート: 時間計算量 O(m + n), 空間計算量O(m + n) マージソート: 時間計算量 O(n log n), 空間計算量O(n) 【まとめおわり】 今回は、実際にphpでそれぞれのアルゴリズムを動かして、「計算量本当にそれであってん..."
}
</script>
<meta name="generator" content="Ghost ?" />
<link rel="alternate" type="application/rss+xml" title="イノベーション エンジニアブログ" href="http://tech.innovation.co.jp/rss" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">
</head>
<body class="post-template tag-Complexity tag-Sort-Algorithm tag-bigen no-js">
<span class="mobile btn-mobile-menu">
<i class="icon icon-list btn-mobile-menu__icon"></i>
<i class="icon icon-x-circle btn-mobile-close__icon hidden"></i>
</span>
<header class="panel-cover panel-cover--collapsed " >
<div class="panel-main">
<div class="panel-main__inner panel-inverted">
<div class="panel-main__content">
<h1 class="panel-cover__title panel-title"><a href="http://tech.innovation.co.jp" title="link to homepage for イノベーション エンジニアブログ">イノベーション エンジニアブログ</a></h1>
<hr class="panel-cover__divider" />
<p class="panel-cover__description">株式会社イノベーションのエンジニアたちの技術系ブログです。ITトレンド・List Finderの開発をベースに、業務外での技術研究などもブログとして発信していってます!</p>
<hr class="panel-cover__divider panel-cover__divider--secondary" />
<div class="navigation-wrapper">
<nav class="cover-navigation cover-navigation--primary">
<ul class="navigation">
<li class="navigation__item"><a href="http://tech.innovation.co.jp/#blog" title="link to イノベーション エンジニアブログ blog" class="blog-button">Blog</a></li>
</ul>
</nav>
<nav class="cover-navigation navigation--social">
<ul class="navigation">
</ul>
</nav>
</div>
</div>
</div>
<div class="panel-cover--overlay"></div>
</div>
</header>
<div class="content-wrapper">
<!-- ソーシャルボタンここから -->
<div id="boxArea" style="display: table; padding: 0 0 0 2px;">
<div style="width: 74px; height: 22px; float: left;">
<a href="https://twitter.com/share" class="twitter-share-button"
{count} data-lang="ja" data-dnt="true">ツイート</a>
<script>
!function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/
.test(d.location) ? 'http' : 'https';
if (!d.getElementById(id)) {
js = d.createElement(s);
js.id = id;
js.src = p + '://platform.twitter.com/widgets.js';
fjs.parentNode.insertBefore(js, fjs);
}
}(document, 'script', 'twitter-wjs');
</script>
</div>
<div style="width: 76px; height: 22px; float: left;">
<div class="g-plusone" data-size="medium"></div>
<script type="text/javascript">
window.___gcfg = {
lang : 'ja'
};
(function() {
var po = document.createElement('script');
po.type = 'text/javascript';
po.async = true;
po.src = 'https://apis.google.com/js/platform.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
</script>
</div>
<div style="width: 126px; height: 22px; float: left;">
<a href="http://b.hatena.ne.jp/entry/" class="hatena-bookmark-button"
data-hatena-bookmark-layout="standard-balloon"
data-hatena-bookmark-lang="ja" title="このエントリーをはてなブックマークに追加"><img
src="http://b.st-hatena.com/images/entry-button/button-only@2x.png"
alt="このエントリーをはてなブックマークに追加" width="20" height="20"
style="border: none;" /></a>
<script type="text/javascript"
src="http://b.st-hatena.com/js/bookmark_button.js" charset="utf-8"
async="async"></script>
</div>
<div style="width: 117px; height: 22px; float: left;">
<a data-pocket-label="pocket" data-pocket-count="horizontal"
class="pocket-btn" data-lang="en"></a>
</div>
<div style="width: 86px; height: 22px; float: left;">
<span><script type="text/javascript"
src="//media.line.me/js/line-button.js?v=20140411"></script>
<script type="text/javascript">
new media_line_me.LineButton({
"pc" : true,
"lang" : "ja",
"type" : "a"
});
</script></span>
</div>
<div style="width: 114px; height: 22px; float: left;">
<script src="//platform.linkedin.com/in.js" type="text/javascript">
lang: ja_JP
</script>
<script type="IN/Share" data-counter="right"></script>
</div>
<div style="width: 112px; height: 22px; float: left;">
<iframe
scrolling="no" frameborder="0" id="fbframe"
width="164" height="46" style="border:none;overflow:hidden"
allowTransparency="true"></iframe>
</div>
<script type="text/javascript">
(function() {
var url = encodeURIComponent(location.href);
document.getElementById('fbframe').src="//www.facebook.com/plugins/like.php?href=" + url +
"&width=164&layout=button_count&action=like&show_faces=true&share=true&height=46&appId=1613776965579453"
})();
</script>
</div>
<script type="text/javascript">
!function(d, i) {
if (!d.getElementById(i)) {
var j = d.createElement("script");
j.id = i;
j.src = "https://widgets.getpocket.com/v1/j/btn.js?v=1";
var w = d.getElementById(i);
d.body.appendChild(j);
}
}(document, "pocket-btn-js");
</script>
<!-- ソーシャルボタンここまで -->
<div class="content-wrapper__inner">
<article class="post-container post-container--single">
<header class="post-header">
<div class="post-meta">
<time datetime="25 Jun 2018" class="post-meta__date date">25 Jun 2018</time> • <span class="post-meta__tags tags">on <a href="http://tech.innovation.co.jp/tag/Complexity">Complexity</a>, <a href="http://tech.innovation.co.jp/tag/Sort-Algorithm"> Sort Algorithm</a>, <a href="http://tech.innovation.co.jp/tag/bigen"> bigen</a></span>
<span class="post-meta__author author"><img src="https://avatars2.githubusercontent.com/u/39402426?v=4" alt="profile image for " class="avatar post-meta__avatar" /> by </span>
</div>
<h1 class="post-title">アルゴリズム計算量入門 〜 ②</h1>
</header>
<section class="post tag-Complexity tag-Sort-Algorithm tag-bigen">
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>どうも、bigenです。<br>
なぜ2本連続で書いているかというと、先週のブログ当番をブッチしてしまった罰ゲームです!<br>
<br>
そんなわけで、 <a href="http://tech.innovation.co.jp/2018/06/26/Introduction-of-Computational-Complexity.html">前回の記事</a>に引き続き、ソートアルゴリズムの計算量について見ていこうと思います。<br>
<br>
【前回の記事のまとめ】<br>
バブルソート: 時間計算量 <strong><em>O(n<sup>2</sup>)</em></strong>, 空間計算量<strong><em>O(n)</em></strong><br>
バケツソート: 時間計算量 <strong><em>O(m + n)</em></strong>, 空間計算量<strong><em>O(m + n)</em></strong><br>
マージソート: 時間計算量 <strong><em>O(n</em> log <em>n)</em></strong>, 空間計算量<strong><em>O(n)</em></strong><br>
【まとめおわり】<br>
<br>
今回は、実際にphpでそれぞれのアルゴリズムを動かして、「計算量本当にそれであってんの?」っていうのを見ていきたいと思います。<br>
<br></p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="__">前提条件</h2>
<div class="sectionbody">
<div class="paragraph">
<p>OS: macOS High Sierra ver.10.13.5<br>
CPU: 第7世代の2.3GHzデュアルコアIntel Core i5プロセッサ<br>
メモリ: 8GB 2,133MHz LPDDR3メモリ<br>
PHP version: 7.1.16<br>
<br>
対象とする問題は、<br></p>
</div>
<div class="literalblock">
<div class="content">
<pre>1~mの範囲のランダムな自然数n個からなる配列を昇順にソートする</pre>
</div>
</div>
<div class="paragraph">
<p>としています。<br>
ソースは初心にかえって自力で用意しました。<br>
記事の末尾に付録としておいておきますので、暇な方はご参照ください。<br>
<br>
また、全体の流れとして、この後</p>
</div>
<div class="literalblock">
<div class="content">
<pre>データの数nや、データの取りうる種類mを増やした時に、計算時間とメモリの消費がどのように変化するか</pre>
</div>
</div>
<div class="paragraph">
<p>を実測で見ていきます。</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="___2">計算時間について</h2>
<div class="sectionbody">
<div class="paragraph">
<p>時間計算量は、それぞれ<br>
<br>
バブルソート: 時間計算量 <strong><em>O(n<sup>2</sup>)</em></strong><br>
バケツソート: 時間計算量 <strong><em>O(m + n)</em></strong><br>
マージソート: 時間計算量 <strong><em>O(n</em> log <em>n)</em></strong> <br>
<br>
でした。<br>
<strong><em>O(n<sup>2</sup>)</em></strong>は「nが10倍になったら計算時間は100倍」<br>
<strong><em>O(m+n)</em></strong>は「nが10倍になったら計算時間も10倍、mが10倍になったら計算時間も10倍」<br>
<strong><em>O(n</em> log <em>n)</em></strong>は「nが10倍になったら計算時間は(10*ちょっと)倍、nが大きいほどちょっとは小さくなる」 <br>
という意味です。<br>
<br></p>
</div>
<div class="sect3">
<h4 id="__n">データの数が増える場合(nが増える場合)</h4>
<div class="paragraph">
<p>まずはデータの範囲は1~100の自然数に固定(<strong><em>m=100</em></strong>)し、データの数<strong><em>n</em></strong>を変化させた時に計算時間がどうなるか見ていきましょう。<br>
<br></p>
</div>
<table class="tableblock frame-all grid-all spread">
<caption class="title">Table 1. 計算時間(s) , m = 100</caption>
<colgroup>
<col style="width: 20%;">
<col style="width: 20%;">
<col style="width: 20%;">
<col style="width: 20%;">
<col style="width: 20%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top"></th>
<th class="tableblock halign-left valign-top">n=100</th>
<th class="tableblock halign-left valign-top">n=1000</th>
<th class="tableblock halign-left valign-top">n=10000</th>
<th class="tableblock halign-left valign-top">n=100000</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">バブルソート</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0002770</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0278578</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">2.7695038</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">287.1152839</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">バケツソート</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0000241</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0000670</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0005970</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0061991</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">マージソート</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0002079</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0030000</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.1332741</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">11.2226848</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p><strong>バブルソート</strong>から見てみると、nが10倍になるにつれ、ほぼ<strong>100倍→10000倍→1000000倍</strong>ときれいに遅くなっていますね。<br>
典型的な<strong><em>O(n<sup>2</sup>)</em></strong>の増え方です。
アルゴリズムがシンプルなのもあり、他の依存要素が少ないため綺麗に比例してくれました。<br></p>
</div>
<div class="paragraph">
<p><strong>バケツソート</strong> は、n:100 → 1000は3倍程度しか増えていませんが、n: 1000 →10000 → 100000はほぼ10倍ずつ増えています。
これは、nが小さい領域ではデータの範囲mに依存する分が大きかったためでしょう。 <br>
n=100: 100(mに依存する時間) + 20(nに依存する時間) = 120<br>
n=1000: 100(mに依存する時間) + 200(nに依存する時間) = 300(3倍ぐらい)<br>
n=10000: 100(mに依存する時間) + 2000(nに依存する時間) = 2100(9倍ぐらい)<br>
n=10000: 100(mに依存する時間) + 20000(nに依存する時間) = 20100(10倍ぐらい)<br>
みたいな感じで増えていっただろうっていうことですね。<br>
理論通りの<strong><em>O(m+n)</em></strong>っぽい増え方をしてくれています。<br></p>
</div>
<div class="paragraph">
<p><strong>マージソート</strong>は、理論どおりにはいってくれませんでした。<br>
nが10倍ずつ増えていくとき、計算時間は<br>
<strong>15倍→45倍→80倍</strong><br>
と増えています。理屈上は増え方が減っていってほしいのですが・・・。<br>
原因としては、再起呼び出し条件が最適化されていなかったりするところでしょうか。<br>
(呼ばなくていい再帰呼び出しをしている箇所がある)<br>
それでも、計算量の増え方は、バブルソートよりかなり遅いのが見て取れます。<br>
<br></p>
</div>
</div>
<div class="sect3">
<h4 id="__m">データの取りうる範囲が大きくなる場合(mが増える場合)</h4>
<div class="paragraph">
<p>次に、データの数nを固定(n=100)して、データの取りうる範囲mを大きくしてみます。<br></p>
</div>
<table class="tableblock frame-all grid-all spread">
<caption class="title">Table 2. 計算時間(s) , n = 100</caption>
<colgroup>
<col style="width: 20%;">
<col style="width: 20%;">
<col style="width: 20%;">
<col style="width: 20%;">
<col style="width: 20%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top"></th>
<th class="tableblock halign-left valign-top">m=100</th>
<th class="tableblock halign-left valign-top">m=1000</th>
<th class="tableblock halign-left valign-top">m=10000</th>
<th class="tableblock halign-left valign-top">m=100000</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">バブルソート</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0003309</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0002930</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0003278</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0002920</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">バケツソート</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0000350</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0000579</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0004789</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0067119</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">マージソート</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0002470</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0002210</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0002301</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">0.0002169</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p><strong>バブルソート</strong>と<strong>マージソート</strong>は<strong>データの取りうる範囲mに依存していない</strong>ことが見て取れます。<br>
<br>
また、<strong>バケツソート</strong>だけm=1000~100000の間で大体10倍ずつ増えていっていることが分かります。<br>
<strong><em>O(m + n)</em></strong>っぽいですね!<br></p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="___3">メモリ使用量について</h2>
<div class="sectionbody">
<div class="paragraph">
<p>空間計算量はそれぞれ、<br>
<br>
バブルソート: 空間計算量 <strong><em>O(n)</em></strong><br>
バケツソート: 空間計算量 <strong><em>O(m + n)</em></strong><br>
マージソート: 空間計算量 <strong><em>O(n)</em></strong> <br></p>
</div>
<div class="paragraph">
<p>でした。<br>
<br>
メモリ使用量を計測するのは難しいのですが、phpではざっくり図るために<br>
<code>memory_get_peak_usage()</code>と<code>memory_get_usage()</code>の差を使って計測しました。<br>
計算の前後で増えたメモリ割り当て量が分かります。<br>
ノイズが多いので正確ではないですが、大体の増え方はつかめるんじゃないでしょうか。<br></p>
</div>
<div class="sect3">
<h4 id="__n_2">データの数が増える場合(nが増える場合)</h4>
<div class="paragraph">
<p>まずはじめに、データの取りうる範囲mを固定(m=100)して、データの数を増やしたときに割当てメモリがどう増えるか見てみましょう<br></p>
</div>
<table class="tableblock frame-all grid-all spread">
<caption class="title">Table 3. メモリ使用量(byte) , m = 100</caption>
<colgroup>
<col style="width: 20%;">
<col style="width: 20%;">
<col style="width: 20%;">
<col style="width: 20%;">
<col style="width: 20%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top"></th>
<th class="tableblock halign-left valign-top">n=100</th>
<th class="tableblock halign-left valign-top">n=1000</th>
<th class="tableblock halign-left valign-top">n=10000</th>
<th class="tableblock halign-left valign-top">n=100000</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">バブルソート</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">36544</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">36920</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">528440</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">4198480</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">バケツソート</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">36544</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">45168</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">536688</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">4206728</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">マージソート</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">36544</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">95784</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">1112040</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">8477032</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p><strong>バブルソート</strong>と<strong>バケツソート</strong>はほぼ同じ増え方をしています。<br>
n=1000~100000の間で大体10倍ずつ増えています。<br>
<strong><em>O(n)</em></strong>とか<strong><em>O(m+n)</em></strong> っぽいですね。<br>
少し不安定なのでもう少し様子をみたかったのですが、バブルソートはデータ数がこれ以上増えると計算時間がなかなかのものだったので諦めました。<br>
<br>
<strong>マージソート</strong>も、他の2つに比べてメモリが多いように見えますが、増え方を見ると10倍ずつ大きくなっており、結局
<strong><em>O(n)</em></strong>っぽいですね。<br>
計算通りでした。<br></p>
</div>
</div>
<div class="sect3">
<h4 id="__m_2">データの取りうる範囲が大きくなる場合(mが増える場合)</h4>
<div class="paragraph">
<p>次に、データの数nを固定(n=100)して、データの取りうる範囲mを増やしてみました。<br></p>
</div>
<table class="tableblock frame-all grid-all spread">
<caption class="title">Table 4. メモリ使用量(byte) , n = 100</caption>
<colgroup>
<col style="width: 20%;">
<col style="width: 20%;">
<col style="width: 20%;">
<col style="width: 20%;">
<col style="width: 20%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top"></th>
<th class="tableblock halign-left valign-top">m=100</th>
<th class="tableblock halign-left valign-top">m=1000</th>
<th class="tableblock halign-left valign-top">m=10000</th>
<th class="tableblock halign-left valign-top">m=100000</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">バブルソート</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">36544</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">36544</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">36544</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">36544</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">バケツソート</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">36544</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">45168</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">536688</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">4206728</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">マージソート</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">36544</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">36544</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">36544</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">36544</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>phpの基本使用料が36500byteぐらい使うのは良いとして、<strong>バケツソートだけ</strong> m=1000~100000の間で大体10倍ずつ増えていくのが分かりました。<br>
<strong><em>O(m+n)</em></strong>っぽいですね。<br>
また、<strong>バブルソート</strong>と<strong>マージソート</strong>は<strong>データの範囲mには依存していない</strong>ことも分かります。<br>
どちらも計算通り、といったところでしょうか。<br>
<br></p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="___4">まとめ</h2>
<div class="sectionbody">
<div class="paragraph">
<p>全体として、理論上の増え方になかなか近い実測値が出たんじゃないでしょうか。<br>
<br>
みなさんも、エンジニアであれば<br>
<strong>「とりあえず動かしてみたけど結果が返ってこない。あと1分で終わるかもしれないし、1年かもしれない。いつまで待てばいいんだ?」</strong><br>
みたいな時ありますよね?<br></p>
</div>
<div class="paragraph">
<p>あらかじめプログラムの計算量がわかっていると、データ数だけ見れば「数時間」なのか「数日」なのか「数年」なのかぐらいは大体分かるのです。 <br>
すごい!<br>
<br>
また、<strong><em>O(n)</em></strong>のような書き方を<strong>オーダー記法</strong>や<strong>ビッグオー記法</strong>といったりするのですが、これをわかってると<br>
「そのアルゴリズムってどれぐらい早いの?」<br>
「エヌログエヌオーダーだぜ!今までのエヌニジョウオーダーとは比べ物にならないぜ!」<br>
みたいな会話ができるわけですね。<br>
すごい!!<br>
<br>
興味ある方は、ぜひ色々調べてみてください。<br>
こちらからは以上です。<br></p>
</div>
<div class="sect2">
<h3 id="___5">付録</h3>
<div class="paragraph">
<p>ソースコードはこちら。
GitHubはこちら。
<a href="https://github.com/bigen1925/complexity_of_sort_algorithm" class="bare">https://github.com/bigen1925/complexity_of_sort_algorithm</a></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-php" data-lang="php"><?php
//////////////
// Usage
// Call from command line
// $ php sort.php <number_of_data> <max_range_of_data> <kind_of_sort_method>
// Sample: $ php sort.php 1000 100 bubble
//////////////
// データの数
$length_array = (int)$argv[1] ?: 1000;
// データのとりうる値の上限
$max_range = (int)$argv[2] ?: 100;
// ソートアルゴリズム
$sort_method = $argv[3] ?: "all";
// 計測
main($length_array, $max_range, $sort_method);
function main($length_array, $max_range, $sort_method)
{
// 1~max_rangeまでの数字から成る、ランダムな順序の数列を生成
$array = array();
for ($i=0; $i < $length_array; $i++) {
$array[] = rand(1, $max_range);
}
// 初期の割当メモリ
$initial_memory_usage = memory_get_usage();
if ($sort_method === "all" || $sort_method === "bubble") {
$time_start = microtime(true);
bubbleSort($array);
$time = microtime(true) - $time_start;
echo "bubbleSort:: {$time}s\n";
}
if ($sort_method === "all" || $sort_method === "buckets") {
$time_start = microtime(true);
bucketsSort($array, $max_range);
$time = microtime(true) - $time_start;
echo "bucketsSort:: {$time}s\n";
}
if ($sort_method === "all" || $sort_method === "merge") {
$time_start = microtime(true);
mergeSort($array);
$time = microtime(true) - $time_start;
echo "mergeSort:: {$time}s\n";
}
// プログラム実行中に追加で割り当てられたメモリ量
$used_memory = memory_get_peak_usage() - $initial_memory_usage;
echo "used_memory:: {$used_memory}\n";
}
// バブルソート
// @param array @array ソートしたい自然数配列
// @return array ソート済みの配列
function bubbleSort(array $array)
{
$length = count($array);
for ($i=0; $i < $length; $i++) {
for ($j=0; $j < $length - $i - 1; $j++) {
if ($array[$j] > $array[$j + 1]) {
$temp = $array[$j];
$array[$j] = $array[$j + 1];
$array[$j + 1] = $temp;
}
}
}
return $array;
}
// バケツソート
// @param array $array ソートしたい自然数配列
// @param integer $max_range データのとりうる最大値
// @return array ソート済みの配列
function bucketsSort(array $array, $max_range)
{
$length = count($array);
$buckets = array_fill(1, $max_range, 0);
$sorted_array = array();
foreach ($array as $value) {
$buckets[$value]++;
}
foreach ($buckets as $value => $count) {
for ($i = 0; $i < $count; $i++) {
$sorted_array[] = $value;
}
}
return $sorted_array;
}
// マージソート
// @param array $array ソートしたい自然数配列
// @return array ソート済み配列
function mergeSort(array $array)
{
$length = count($array);
$sorted_array = array();
if ($length > 1) {
$mid_index = floor(($length + 0.5) / 2);
$left_array = array_slice($array, 0, $mid_index);
$right_array = array_slice($array, $mid_index);
$left_array = mergeSort($left_array);
$right_array = mergeSort($right_array);
while (count($left_array) || count($right_array)) {
if (count($left_array) == 0) {
$sorted_array[] = array_shift($right_array);
} elseif (count($right_array) == 0) {
$sorted_array[] = array_shift($left_array);
} elseif ($left_array[0] > $right_array[0]) {
$sorted_array[] = array_shift($right_array);
} else {
$sorted_array[] = array_shift($left_array);
}
}
} else {
$sorted_array = $array;
}
return $sorted_array;
}</code></pre>
</div>
</div>
</div>
</div>
</div>
</section>
</article>
<footer class="footer">
<span class="footer__copyright">© 2018. All rights reserved.</span>
<span class="footer__copyright"><a href="http://uno.daleanthony.com" title="link to page for Uno Ghost theme">Uno theme</a> by <a href="http://daleanthony.com" title="link to website for Dale-Anthony">Dale-Anthony</a></span>
<span class="footer__copyright">Proudly published with <a href="http://hubpress.io" title="link to Hubpress website">Hubpress</a></span>
</footer>
</div>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js?v="></script> <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.min.js?v="></script> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js?v="></script>
<script type="text/javascript">
jQuery( document ).ready(function() {
// change date with ago
jQuery('ago.ago').each(function(){
var element = jQuery(this).parent();
element.html( moment(element.text()).fromNow());
});
});
hljs.initHighlightingOnLoad();
</script>
<script type="text/javascript" src="//tech.innovation.co.jp/themes/uno/assets/js/main.js?v=1.0.0"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-105881090-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
| Java |
### Tree `flatten`
Write a procedure called `tree->list` that completely flattens a tree to a list
Example usage:
```racket
(tree->list '[1 2 [3 [4]] [5]])
;;=> '[1 2 3 4 5]
```
| Java |
.float-btn-wrapper {
width: 75;
height: 75;
}
.float-btn-shadow {
width: 56;
height: 56;
}
.float-btn {
background-color: #FF69B4;
border-radius: 28;
width: 56;
height: 56;
text-align: center;
vertical-align: middle;
}
.float-btn.down{
animation-name: down;
animation-duration: 0.2s;
animation-fill-mode: forwards;
}
.float-btn-text {
color: #ffffff;
font-size: 36;
margin-top: -3;
margin-right: -1;
}
@keyframes down {
from { background-color: #FF69B4 }
to { background-color: #FFA9B4 }
} | Java |
import re
import warnings
import ctds
from .base import TestExternalDatabase
from .compat import PY3, PY36, unicode_
class TestTdsParameter(TestExternalDatabase):
def test___doc__(self):
self.assertEqual(
ctds.Parameter.__doc__,
'''\
Parameter(value, output=False)
Explicitly define a parameter for :py:meth:`.callproc`,
:py:meth:`.execute`, or :py:meth:`.executemany`. This is necessary
to indicate whether a parameter is *SQL* `OUTPUT` or `INPUT/OUTPUT`
parameter.
:param object value: The parameter's value.
:param bool output: Is the parameter an output parameter.
'''
)
def test_parameter(self):
param1 = ctds.Parameter(b'123', output=True)
self.assertEqual(param1.value, b'123')
self.assertTrue(isinstance(param1, ctds.Parameter))
param2 = ctds.Parameter(b'123')
self.assertEqual(param1.value, b'123')
self.assertEqual(type(param1), type(param2))
self.assertTrue(isinstance(param2, ctds.Parameter))
def test___repr__(self):
for parameter, expected in (
(
ctds.Parameter(b'123', output=True),
"ctds.Parameter(b'123', output=True)" if PY3 else "ctds.Parameter('123', output=True)"
),
(
ctds.Parameter(unicode_('123'), output=False),
"ctds.Parameter('123')" if PY3 else "ctds.Parameter(u'123')"
),
(
ctds.Parameter(None),
"ctds.Parameter(None)"
),
(
ctds.Parameter(ctds.SqlVarBinary(b'4321', size=10)),
"ctds.Parameter(ctds.SqlVarBinary(b'4321', size=10))"
if PY3 else
"ctds.Parameter(ctds.SqlVarBinary('4321', size=10))"
)
):
self.assertEqual(repr(parameter), expected)
def _test__cmp__(self, __cmp__, expected, oper):
cases = (
(ctds.Parameter(b'1234'), ctds.Parameter(b'123')),
(ctds.Parameter(b'123'), ctds.Parameter(b'123')),
(ctds.Parameter(b'123'), ctds.Parameter(b'123', output=True)),
(ctds.Parameter(b'123'), ctds.Parameter(b'1234')),
(ctds.Parameter(b'123'), b'123'),
(ctds.Parameter(b'123'), ctds.Parameter(123)),
(ctds.Parameter(b'123'), unicode_('123')),
(ctds.Parameter(b'123'), ctds.SqlBinary(None)),
(ctds.Parameter(b'123'), 123),
(ctds.Parameter(b'123'), None),
)
for index, args in enumerate(cases):
operation = '[{0}]: {1} {2} {3}'.format(index, repr(args[0]), oper, repr(args[1]))
if expected[index] == TypeError:
try:
__cmp__(*args)
except TypeError as ex:
regex = (
r"'{0}' not supported between instances of '[^']+' and '[^']+'".format(oper)
if not PY3 or PY36
else
r'unorderable types: \S+ {0} \S+'.format(oper)
)
self.assertTrue(re.match(regex, str(ex)), ex)
else:
self.fail('{0} did not fail as expected'.format(operation)) # pragma: nocover
else:
self.assertEqual(__cmp__(*args), expected[index], operation)
def test___cmp__eq(self):
self._test__cmp__(
lambda left, right: left == right,
(
False,
True,
True,
False,
True,
False,
not PY3,
False,
False,
False,
),
'=='
)
def test___cmp__ne(self):
self._test__cmp__(
lambda left, right: left != right,
(
True,
False,
False,
True,
False,
True,
PY3,
True,
True,
True,
),
'!='
)
def test___cmp__lt(self):
self._test__cmp__(
lambda left, right: left < right,
(
False,
False,
False,
True,
False,
TypeError if PY3 else False,
TypeError if PY3 else False,
TypeError if PY3 else False,
TypeError if PY3 else False,
TypeError if PY3 else False,
),
'<'
)
def test___cmp__le(self):
self._test__cmp__(
lambda left, right: left <= right,
(
False,
True,
True,
True,
True,
TypeError if PY3 else False,
TypeError if PY3 else True,
TypeError if PY3 else False,
TypeError if PY3 else False,
TypeError if PY3 else False,
),
'<='
)
def test___cmp__gt(self):
self._test__cmp__(
lambda left, right: left > right,
(
True,
False,
False,
False,
False,
TypeError if PY3 else True,
TypeError if PY3 else False,
TypeError if PY3 else True,
TypeError if PY3 else True,
TypeError if PY3 else True,
),
'>'
)
def test___cmp__ge(self):
self._test__cmp__(
lambda left, right: left >= right,
(
True,
True,
True,
False,
True,
TypeError if PY3 else True,
TypeError if PY3 else True,
TypeError if PY3 else True,
TypeError if PY3 else True,
TypeError if PY3 else True,
),
'>='
)
def test_typeerror(self):
for case in (None, object(), 123, 'foobar'):
self.assertRaises(TypeError, ctds.Parameter, case, b'123')
self.assertRaises(TypeError, ctds.Parameter)
self.assertRaises(TypeError, ctds.Parameter, output=False)
for case in (None, object(), 123, 'foobar'):
self.assertRaises(TypeError, ctds.Parameter, b'123', output=case)
def test_reuse(self):
with self.connect() as connection:
with connection.cursor() as cursor:
for value in (
None,
123456,
unicode_('hello world'),
b'some bytes',
):
for output in (True, False):
parameter = ctds.Parameter(value, output=output)
for _ in range(0, 2):
# Ignore warnings generated due to output parameters
# used with result sets.
with warnings.catch_warnings(record=True):
cursor.execute(
'''
SELECT :0
''',
(parameter,)
)
self.assertEqual(
[tuple(row) for row in cursor.fetchall()],
[(value,)]
)
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace HolisticWare.Ph4ct3x.Server.Pages.Ph4ct3x.Communication
{
public class InstantMessagingChatModel : PageModel
{
public void OnGet()
{
}
}
}
| Java |
/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef MODULES_AUDIO_CODING_NETEQ_TOOLS_PACKET_H_
#define MODULES_AUDIO_CODING_NETEQ_TOOLS_PACKET_H_
#include <list>
#include <memory>
#include BOSS_WEBRTC_U_api__rtp_headers_h //original-code:"api/rtp_headers.h" // NOLINT(build/include)
#include BOSS_WEBRTC_U_common_types_h //original-code:"common_types.h" // NOLINT(build/include)
#include BOSS_WEBRTC_U_rtc_base__constructormagic_h //original-code:"rtc_base/constructormagic.h"
#include BOSS_WEBRTC_U_typedefs_h //original-code:"typedefs.h" // NOLINT(build/include)
namespace webrtc {
class RtpHeaderParser;
namespace test {
// Class for handling RTP packets in test applications.
class Packet {
public:
// Creates a packet, with the packet payload (including header bytes) in
// |packet_memory|. The length of |packet_memory| is |allocated_bytes|.
// The new object assumes ownership of |packet_memory| and will delete it
// when the Packet object is deleted. The |time_ms| is an extra time
// associated with this packet, typically used to denote arrival time.
// The first bytes in |packet_memory| will be parsed using |parser|.
Packet(uint8_t* packet_memory,
size_t allocated_bytes,
double time_ms,
const RtpHeaderParser& parser);
// Same as above, but with the extra argument |virtual_packet_length_bytes|.
// This is typically used when reading RTP dump files that only contain the
// RTP headers, and no payload (a.k.a RTP dummy files or RTP light). The
// |virtual_packet_length_bytes| tells what size the packet had on wire,
// including the now discarded payload, whereas |allocated_bytes| is the
// length of the remaining payload (typically only the RTP header).
Packet(uint8_t* packet_memory,
size_t allocated_bytes,
size_t virtual_packet_length_bytes,
double time_ms,
const RtpHeaderParser& parser);
// The following two constructors are the same as above, but without a
// parser. Note that when the object is constructed using any of these
// methods, the header will be parsed using a default RtpHeaderParser object.
// In particular, RTP header extensions won't be parsed.
Packet(uint8_t* packet_memory, size_t allocated_bytes, double time_ms);
Packet(uint8_t* packet_memory,
size_t allocated_bytes,
size_t virtual_packet_length_bytes,
double time_ms);
virtual ~Packet();
// Parses the first bytes of the RTP payload, interpreting them as RED headers
// according to RFC 2198. The headers will be inserted into |headers|. The
// caller of the method assumes ownership of the objects in the list, and
// must delete them properly.
bool ExtractRedHeaders(std::list<RTPHeader*>* headers) const;
// Deletes all RTPHeader objects in |headers|, but does not delete |headers|
// itself.
static void DeleteRedHeaders(std::list<RTPHeader*>* headers);
const uint8_t* payload() const { return payload_; }
size_t packet_length_bytes() const { return packet_length_bytes_; }
size_t payload_length_bytes() const { return payload_length_bytes_; }
size_t virtual_packet_length_bytes() const {
return virtual_packet_length_bytes_;
}
size_t virtual_payload_length_bytes() const {
return virtual_payload_length_bytes_;
}
const RTPHeader& header() const { return header_; }
void set_time_ms(double time) { time_ms_ = time; }
double time_ms() const { return time_ms_; }
bool valid_header() const { return valid_header_; }
private:
bool ParseHeader(const RtpHeaderParser& parser);
void CopyToHeader(RTPHeader* destination) const;
RTPHeader header_;
std::unique_ptr<uint8_t[]> payload_memory_;
const uint8_t* payload_; // First byte after header.
const size_t packet_length_bytes_; // Total length of packet.
size_t payload_length_bytes_; // Length of the payload, after RTP header.
// Zero for dummy RTP packets.
// Virtual lengths are used when parsing RTP header files (dummy RTP files).
const size_t virtual_packet_length_bytes_;
size_t virtual_payload_length_bytes_;
double time_ms_; // Used to denote a packet's arrival time.
bool valid_header_; // Set by the RtpHeaderParser.
RTC_DISALLOW_COPY_AND_ASSIGN(Packet);
};
} // namespace test
} // namespace webrtc
#endif // MODULES_AUDIO_CODING_NETEQ_TOOLS_PACKET_H_
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Cross-correlations: GlobalVariables Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">Cross-correlations
 <span id="projectnumber">1.0</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.8.0 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Defines</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</div>
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> </div>
<div class="headertitle">
<div class="title">GlobalVariables Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<p><code>#include <<a class="el" href="global__variables_8h_source.html">global_variables.h</a>></code></p>
<p><a href="class_global_variables-members.html">List of all members.</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:a4631d1ecf5fe11e440926a3464028eb0"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a4631d1ecf5fe11e440926a3464028eb0">GlobalVariables</a> ()</td></tr>
<tr class="memitem:aa30e576f3563c41b63177a5ae93b9aab"><td class="memItemLeft" align="right" valign="top">double </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#aa30e576f3563c41b63177a5ae93b9aab">c</a> () const </td></tr>
<tr class="memitem:ab8932c7446ddcc1bbf9f19d07ec44424"><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#ab8932c7446ddcc1bbf9f19d07ec44424">correlation_file_name</a> () const </td></tr>
<tr class="memitem:ab5102be8fa70c050ab20349e47fa388d"><td class="memItemLeft" align="right" valign="top">double </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#ab5102be8fa70c050ab20349e47fa388d">h</a> () const </td></tr>
<tr class="memitem:a1ae6b307005b7da0849b79173ab5b62d"><td class="memItemLeft" align="right" valign="top">double </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a1ae6b307005b7da0849b79173ab5b62d">h0</a> () const </td></tr>
<tr class="memitem:a7b251a0da7026b671d8a68279cab4ae7"><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a7b251a0da7026b671d8a68279cab4ae7">lya_spectra_catalog</a> () const </td></tr>
<tr class="memitem:a7ef593cd3a148af75812f2e8479595ae"><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a7ef593cd3a148af75812f2e8479595ae">lya_spectra_catalog_name</a> () const </td></tr>
<tr class="memitem:ac337ea3586fbb1346240ad25c696f6f0"><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#ac337ea3586fbb1346240ad25c696f6f0">lya_spectra_dir</a> () const </td></tr>
<tr class="memitem:a2893eb2c29a895d604ac471c320f4a39"><td class="memItemLeft" align="right" valign="top">double </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a2893eb2c29a895d604ac471c320f4a39">lya_wl</a> () const </td></tr>
<tr class="memitem:ae3688afd60bb03fd4e788d27af1ac8fe"><td class="memItemLeft" align="right" valign="top">double </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#ae3688afd60bb03fd4e788d27af1ac8fe">max_pi</a> () const </td></tr>
<tr class="memitem:a13694704b2bb849bae0d46e577246fb0"><td class="memItemLeft" align="right" valign="top">double </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a13694704b2bb849bae0d46e577246fb0">max_sigma</a> () const </td></tr>
<tr class="memitem:aae93df7713a9e59706c8d8cd03e62a8a"><td class="memItemLeft" align="right" valign="top">double </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#aae93df7713a9e59706c8d8cd03e62a8a">neighbours_max_distance</a> () const </td></tr>
<tr class="memitem:a7481f788f94ed1bdb590057d7a0f48ca"><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a7481f788f94ed1bdb590057d7a0f48ca">normalized_correlation</a> () const </td></tr>
<tr class="memitem:a8df4bf4e1962af98f59cd43947188509"><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a8df4bf4e1962af98f59cd43947188509">num_bins</a> () const </td></tr>
<tr class="memitem:a08ee1fac0ba1c1eccb8fd405c1f9cb1c"><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a08ee1fac0ba1c1eccb8fd405c1f9cb1c">num_pi_bins</a> () const </td></tr>
<tr class="memitem:a09a6fd5da6b9c5a3a9aa63bee7e4466f"><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a09a6fd5da6b9c5a3a9aa63bee7e4466f">num_plates</a> () const </td></tr>
<tr class="memitem:a054d4cf825a69d3461475a3590799774"><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a054d4cf825a69d3461475a3590799774">num_points_interpolation</a> () const </td></tr>
<tr class="memitem:a5ccd02c696d64e9c33fc6a7e1ba8b9ef"><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a5ccd02c696d64e9c33fc6a7e1ba8b9ef">num_sigma_bins</a> () const </td></tr>
<tr class="memitem:ab3641ef310a60651c562a7dc8864d0e9"><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#ab3641ef310a60651c562a7dc8864d0e9">objects_catalog</a> () const </td></tr>
<tr class="memitem:a8412ac07504633c4abd23702b4d4d823"><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a8412ac07504633c4abd23702b4d4d823">objects_catalog_name</a> () const </td></tr>
<tr class="memitem:ac10711bcd7293ce5da996b4f5b79de2b"><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#ac10711bcd7293ce5da996b4f5b79de2b">pairs_file_name</a> () const </td></tr>
<tr class="memitem:abf1a6505c3dab27b4dc58fc1634e70e7"><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#abf1a6505c3dab27b4dc58fc1634e70e7">plate_neighbours</a> () const </td></tr>
<tr class="memitem:a825d2ce1a68bbdca6395aa10690e3407"><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a825d2ce1a68bbdca6395aa10690e3407">plots</a> () const </td></tr>
<tr class="memitem:a03e3e8cbe112ab714544e57f541a693f"><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a03e3e8cbe112ab714544e57f541a693f">pwd</a> () const </td></tr>
<tr class="memitem:a53b4346935148918029cc1a2daaad80c"><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a53b4346935148918029cc1a2daaad80c">results</a> () const </td></tr>
<tr class="memitem:aba979c1ae01246184e65e4034007f0ca"><td class="memItemLeft" align="right" valign="top">double </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#aba979c1ae01246184e65e4034007f0ca">step_pi</a> () const </td></tr>
<tr class="memitem:a0a1e6c768c7323c1da081db7c375060e"><td class="memItemLeft" align="right" valign="top">double </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a0a1e6c768c7323c1da081db7c375060e">step_sigma</a> () const </td></tr>
<tr class="memitem:ae01eadf8a6614c2b8f5e5a5da5b0a7c3"><td class="memItemLeft" align="right" valign="top">double </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#ae01eadf8a6614c2b8f5e5a5da5b0a7c3">wm</a> () const </td></tr>
<tr class="memitem:a09e2005546be6c1147d898fbd9f040e0"><td class="memItemLeft" align="right" valign="top">double </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a09e2005546be6c1147d898fbd9f040e0">z_max</a> () const </td></tr>
<tr class="memitem:ad2dee77ee4d577e3a9575184089735ac"><td class="memItemLeft" align="right" valign="top">double </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#ad2dee77ee4d577e3a9575184089735ac">z_max_interpolation</a> () const </td></tr>
<tr class="memitem:ac6ed0b46b3ab483ba201b193b0953905"><td class="memItemLeft" align="right" valign="top">double </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#ac6ed0b46b3ab483ba201b193b0953905">z_min</a> () const </td></tr>
<tr class="memitem:a3f167911da6733d4f4ebf58949d24c02"><td class="memItemLeft" align="right" valign="top">double </td><td class="memItemRight" valign="bottom"><a class="el" href="class_global_variables.html#a3f167911da6733d4f4ebf58949d24c02">z_min_interpolation</a> () const </td></tr>
</table>
<hr/><a name="details" id="details"></a><h2>Detailed Description</h2>
<div class="textblock"><p>global _variables.h Purpose: This file defines the class <a class="el" href="class_global_variables.html">GlobalVariables</a>. This class contains the constant variables which are used in a "global" sense</p>
<dl class="section author"><dt>Author:</dt><dd>Ignasi Pérez-Ràfols (<a href="#" onclick="location.href='mai'+'lto:'+'ipr'+'af'+'ols'+'@i'+'cc.'+'ub'+'.ed'+'u'; return false;">ipraf<span style="display: none;">.nosp@m.</span>ols@<span style="display: none;">.nosp@m.</span>icc.u<span style="display: none;">.nosp@m.</span>b.ed<span style="display: none;">.nosp@m.</span>u</a>) </dd></dl>
<dl class="section version"><dt>Version:</dt><dd>1.0 on 17/06/14 </dd></dl>
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00025">25</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
</div><hr/><h2>Constructor & Destructor Documentation</h2>
<a class="anchor" id="a4631d1ecf5fe11e440926a3464028eb0"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="class_global_variables.html#a4631d1ecf5fe11e440926a3464028eb0">GlobalVariables::GlobalVariables</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p><a class="el" href="global__variables_8cpp.html">global_variables.cpp</a> Purpose: This files contains the body for the functions defined in <a class="el" href="global__variables_8h.html">global_variables.h</a></p>
<dl class="section author"><dt>Author:</dt><dd>Ignasi Pérez-Ràfols </dd></dl>
<dl class="section version"><dt>Version:</dt><dd>1.0 06/17/2014 </dd></dl>
<p>EXPLANATION: Cosntructs a <a class="el" href="class_global_variables.html">GlobalVariables</a> instance and initializes all its variables</p>
<p>INPUTS: NONE</p>
<p>OUTPUTS: NONE</p>
<p>CLASSES USED: <a class="el" href="class_global_variables.html">GlobalVariables</a></p>
<p>FUNCITONS USED: NONE</p>
<p>Definition at line <a class="el" href="global__variables_8cpp_source.html#l00011">11</a> of file <a class="el" href="global__variables_8cpp_source.html">global_variables.cpp</a>.</p>
<div class="fragment"><pre class="fragment"> {
<span class="comment">//</span>
<span class="comment">// general settings</span>
<span class="comment">//</span>
<span class="comment">//pwd_ = "/Users/iprafols/cross_correlations/";</span>
pwd_ = <span class="stringliteral">"/triforce/iprafols/cross_correlations/"</span>;
results_ = pwd_ + <span class="stringliteral">"results2/"</span>;
plots_ = pwd_ + <span class="stringliteral">"plots2/"</span>;
objects_catalog_ = pwd_ + <span class="stringliteral">"DR11Q_alpha_v0.fits"</span>;
objects_catalog_name_ = <span class="stringliteral">"DR11Q_alpha_v0"</span>;
pairs_file_name_ = <span class="stringliteral">"qso_spectrum_pairs_plate_"</span>;
correlation_file_name_ = results_ + <span class="stringliteral">"correlation_bin_"</span>;
normalized_correlation_ = results_ + <span class="stringliteral">"normalized_correlation.dat"</span>;
plate_neighbours_ = pwd_ + <span class="stringliteral">"plate_neighbours.dat"</span>;
lya_spectra_dir_ = pwd_ + <span class="stringliteral">"spectrum_fits_files/"</span>;
<span class="comment">//lya_spectra_catalog_ = pwd_ + "DR11Q_spectra_forest_one_spectrum.ls";// versió per fer proves</span>
lya_spectra_catalog_ = pwd_ + <span class="stringliteral">"DR11Q_spectra_forest_some_spectrum.ls"</span>;<span class="comment">// versió per fer proves</span>
<span class="comment">//lya_spectra_catalog_ = pwd_ + "DR11Q_spectra_forest_list.ls"; // versió definitiva</span>
lya_spectra_catalog_name_ = <span class="stringliteral">"DR11Q_spectra_forest"</span>;
num_plates_ = 2044; <span class="comment">// DR11</span>
<span class="comment">//</span>
<span class="comment">// Fidutial model</span>
<span class="comment">//</span>
h0_ = 68.0;
h_ = h0_/100.0;
wm_ = 0.3;
<span class="comment">//</span>
<span class="comment">// bin setting</span>
<span class="comment">//</span>
neighbours_max_distance_ = 3.0*acos(-1.0)/180.0; <span class="comment">// (in radians)</span>
max_pi_ = 50.0; <span class="comment">// (in Mpc/h)</span>
max_sigma_ = 50.0; <span class="comment">// (in Mpc/h)</span>
step_pi_ = 5.0; <span class="comment">// (in Mpc/h)</span>
step_sigma_ = 5.0; <span class="comment">// (in Mpc/h)</span>
num_pi_bins_ = int(2.0*max_pi_/step_pi_);
num_sigma_bins_ = int(max_sigma_/step_sigma_);
num_bins_ = num_pi_bins_*num_sigma_bins_;
<span class="comment">//</span>
<span class="comment">// line and redshift settings</span>
<span class="comment">//</span>
lya_wl_ = 1215.67;
z_min_ = 2.0;
z_max_ = 3.5;
z_min_interpolation_ = 1.5;
z_max_interpolation_ = 4.0;
num_points_interpolation_ = 30000;
<span class="comment">//</span>
<span class="comment">// Some mathematical and physical constants</span>
<span class="comment">//</span>
c_ = 299792.458;
}</pre></div>
</div>
</div>
<hr/><h2>Member Function Documentation</h2>
<a class="anchor" id="aa30e576f3563c41b63177a5ae93b9aab"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double <a class="el" href="class_global_variables.html#aa30e576f3563c41b63177a5ae93b9aab">GlobalVariables::c</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00038">38</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> c_;}
</pre></div>
</div>
</div>
<a class="anchor" id="ab8932c7446ddcc1bbf9f19d07ec44424"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string <a class="el" href="class_global_variables.html#ab8932c7446ddcc1bbf9f19d07ec44424">GlobalVariables::correlation_file_name</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00041">41</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> correlation_file_name_;}
</pre></div>
</div>
</div>
<a class="anchor" id="ab5102be8fa70c050ab20349e47fa388d"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double <a class="el" href="class_global_variables.html#ab5102be8fa70c050ab20349e47fa388d">GlobalVariables::h</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00044">44</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> h_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a1ae6b307005b7da0849b79173ab5b62d"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double <a class="el" href="class_global_variables.html#a1ae6b307005b7da0849b79173ab5b62d">GlobalVariables::h0</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00047">47</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> h0_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a7b251a0da7026b671d8a68279cab4ae7"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string <a class="el" href="class_global_variables.html#a7b251a0da7026b671d8a68279cab4ae7">GlobalVariables::lya_spectra_catalog</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00050">50</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> lya_spectra_catalog_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a7ef593cd3a148af75812f2e8479595ae"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string <a class="el" href="class_global_variables.html#a7ef593cd3a148af75812f2e8479595ae">GlobalVariables::lya_spectra_catalog_name</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00053">53</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> lya_spectra_catalog_name_;}
</pre></div>
</div>
</div>
<a class="anchor" id="ac337ea3586fbb1346240ad25c696f6f0"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string <a class="el" href="class_global_variables.html#ac337ea3586fbb1346240ad25c696f6f0">GlobalVariables::lya_spectra_dir</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00056">56</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> lya_spectra_dir_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a2893eb2c29a895d604ac471c320f4a39"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double <a class="el" href="class_global_variables.html#a2893eb2c29a895d604ac471c320f4a39">GlobalVariables::lya_wl</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00059">59</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> lya_wl_;}
</pre></div>
</div>
</div>
<a class="anchor" id="ae3688afd60bb03fd4e788d27af1ac8fe"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double <a class="el" href="class_global_variables.html#ae3688afd60bb03fd4e788d27af1ac8fe">GlobalVariables::max_pi</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00062">62</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> max_pi_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a13694704b2bb849bae0d46e577246fb0"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double <a class="el" href="class_global_variables.html#a13694704b2bb849bae0d46e577246fb0">GlobalVariables::max_sigma</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00065">65</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> max_sigma_;}
</pre></div>
</div>
</div>
<a class="anchor" id="aae93df7713a9e59706c8d8cd03e62a8a"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double <a class="el" href="class_global_variables.html#aae93df7713a9e59706c8d8cd03e62a8a">GlobalVariables::neighbours_max_distance</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00068">68</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> neighbours_max_distance_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a7481f788f94ed1bdb590057d7a0f48ca"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string <a class="el" href="class_global_variables.html#a7481f788f94ed1bdb590057d7a0f48ca">GlobalVariables::normalized_correlation</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00071">71</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> normalized_correlation_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a8df4bf4e1962af98f59cd43947188509"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int <a class="el" href="class_global_variables.html#a8df4bf4e1962af98f59cd43947188509">GlobalVariables::num_bins</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00074">74</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> num_bins_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a08ee1fac0ba1c1eccb8fd405c1f9cb1c"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int <a class="el" href="class_global_variables.html#a08ee1fac0ba1c1eccb8fd405c1f9cb1c">GlobalVariables::num_pi_bins</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00077">77</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> num_pi_bins_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a09a6fd5da6b9c5a3a9aa63bee7e4466f"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int <a class="el" href="class_global_variables.html#a09a6fd5da6b9c5a3a9aa63bee7e4466f">GlobalVariables::num_plates</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00080">80</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> num_plates_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a054d4cf825a69d3461475a3590799774"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int <a class="el" href="class_global_variables.html#a054d4cf825a69d3461475a3590799774">GlobalVariables::num_points_interpolation</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00083">83</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> num_points_interpolation_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a5ccd02c696d64e9c33fc6a7e1ba8b9ef"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int <a class="el" href="class_global_variables.html#a5ccd02c696d64e9c33fc6a7e1ba8b9ef">GlobalVariables::num_sigma_bins</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00086">86</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> num_sigma_bins_;}
</pre></div>
</div>
</div>
<a class="anchor" id="ab3641ef310a60651c562a7dc8864d0e9"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string <a class="el" href="class_global_variables.html#ab3641ef310a60651c562a7dc8864d0e9">GlobalVariables::objects_catalog</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00089">89</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> objects_catalog_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a8412ac07504633c4abd23702b4d4d823"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string <a class="el" href="class_global_variables.html#a8412ac07504633c4abd23702b4d4d823">GlobalVariables::objects_catalog_name</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00092">92</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> objects_catalog_name_;}
</pre></div>
</div>
</div>
<a class="anchor" id="ac10711bcd7293ce5da996b4f5b79de2b"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string <a class="el" href="class_global_variables.html#ac10711bcd7293ce5da996b4f5b79de2b">GlobalVariables::pairs_file_name</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00095">95</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> pairs_file_name_;}
</pre></div>
</div>
</div>
<a class="anchor" id="abf1a6505c3dab27b4dc58fc1634e70e7"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string <a class="el" href="class_global_variables.html#abf1a6505c3dab27b4dc58fc1634e70e7">GlobalVariables::plate_neighbours</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00098">98</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> plate_neighbours_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a825d2ce1a68bbdca6395aa10690e3407"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string <a class="el" href="class_global_variables.html#a825d2ce1a68bbdca6395aa10690e3407">GlobalVariables::plots</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00101">101</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> plots_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a03e3e8cbe112ab714544e57f541a693f"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string <a class="el" href="class_global_variables.html#a03e3e8cbe112ab714544e57f541a693f">GlobalVariables::pwd</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00104">104</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> pwd_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a53b4346935148918029cc1a2daaad80c"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string <a class="el" href="class_global_variables.html#a53b4346935148918029cc1a2daaad80c">GlobalVariables::results</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00107">107</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> results_;}
</pre></div>
</div>
</div>
<a class="anchor" id="aba979c1ae01246184e65e4034007f0ca"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double <a class="el" href="class_global_variables.html#aba979c1ae01246184e65e4034007f0ca">GlobalVariables::step_pi</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00110">110</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> step_pi_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a0a1e6c768c7323c1da081db7c375060e"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double <a class="el" href="class_global_variables.html#a0a1e6c768c7323c1da081db7c375060e">GlobalVariables::step_sigma</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00113">113</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> step_sigma_;}
</pre></div>
</div>
</div>
<a class="anchor" id="ae01eadf8a6614c2b8f5e5a5da5b0a7c3"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double <a class="el" href="class_global_variables.html#ae01eadf8a6614c2b8f5e5a5da5b0a7c3">GlobalVariables::wm</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00116">116</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> wm_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a09e2005546be6c1147d898fbd9f040e0"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double <a class="el" href="class_global_variables.html#a09e2005546be6c1147d898fbd9f040e0">GlobalVariables::z_max</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00119">119</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> z_max_;}
</pre></div>
</div>
</div>
<a class="anchor" id="ad2dee77ee4d577e3a9575184089735ac"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double <a class="el" href="class_global_variables.html#ad2dee77ee4d577e3a9575184089735ac">GlobalVariables::z_max_interpolation</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00122">122</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> z_max_interpolation_;}
</pre></div>
</div>
</div>
<a class="anchor" id="ac6ed0b46b3ab483ba201b193b0953905"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double <a class="el" href="class_global_variables.html#ac6ed0b46b3ab483ba201b193b0953905">GlobalVariables::z_min</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00125">125</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> z_min_;}
</pre></div>
</div>
</div>
<a class="anchor" id="a3f167911da6733d4f4ebf58949d24c02"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double <a class="el" href="class_global_variables.html#a3f167911da6733d4f4ebf58949d24c02">GlobalVariables::z_min_interpolation</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="global__variables_8h_source.html#l00128">128</a> of file <a class="el" href="global__variables_8h_source.html">global_variables.h</a>.</p>
<div class="fragment"><pre class="fragment">{<span class="keywordflow">return</span> z_min_interpolation_;}
</pre></div>
</div>
</div>
<hr/>The documentation for this class was generated from the following files:<ul>
<li><a class="el" href="global__variables_8h_source.html">global_variables.h</a></li>
<li><a class="el" href="global__variables_8cpp_source.html">global_variables.cpp</a></li>
</ul>
</div><!-- contents -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Oct 14 2014 09:19:21 for Cross-correlations by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.0
</small></address>
</body>
</html>
| Java |
#include "Renderer.h"
#include "Core/Windows/Window.h"
#include <Resources/ResourceCache.h>
namespace uut
{
UUT_MODULE_IMPLEMENT(Renderer)
{}
Renderer::Renderer()
: _screenSize(0)
{
}
Renderer::~Renderer()
{
}
//////////////////////////////////////////////////////////////////////////////
bool Renderer::OnInit()
{
if (!Super::OnInit())
return false;
ModuleInstance<ResourceCache> cache;
cache->AddResource(CreateMonoTexture(Color32::White), "white");
cache->AddResource(CreateMonoTexture(Color32::Black), "black");
return true;
}
void Renderer::OnDone()
{
}
SharedPtr<Texture2D> Renderer::CreateMonoTexture(const Color32& color)
{
auto tex = CreateTexture(Vector2i(1), TextureAccess::Static);
uint32_t* buf = static_cast<uint32_t*>(tex->Lock());
if (buf == nullptr)
return nullptr;
buf[0] = color.ToInt();
tex->Unlock();
return tex;
}
}
| Java |
package jnt.scimark2;
public class kernel
{
// each measurement returns approx Mflops
public static double measureFFT(int N, double mintime, Random R)
{
// initialize FFT data as complex (N real/img pairs)
double x[] = RandomVector(2*N, R);
double oldx[] = NewVectorCopy(x);
long cycles = 1;
Stopwatch Q = new Stopwatch();
while(true)
{
Q.start();
for (int i=0; i<cycles; i++)
{
FFT.transform(x); // forward transform
FFT.inverse(x); // backward transform
}
Q.stop();
if (Q.read() >= mintime)
break;
cycles *= 2;
}
// approx Mflops
final double EPS = 1.0e-10;
if ( FFT.test(x) / N > EPS )
return 0.0;
return FFT.num_flops(N)*cycles/ Q.read() * 1.0e-6;
}
// public static double measureSOR(int N, double min_time, Random R)
// {
// double G[][] = RandomMatrix(N, N, R);
//
// //Stopwatch Q = new Stopwatch();
// int cycles=1;
// //while(true)
// while(cycles <= 32768)
// {
// //Q.start();
// SOR.execute(1.25, G, cycles);
// //Q.stop();
// //if (Q.read() >= min_time) break;
//
// cycles *= 2;
// }
// // approx Mflops
// //return SOR.num_flops(N, N, cycles) / Q.read() * 1.0e-6;
// return SOR.num_flops(N, N, cycles);
// }
public static double measureSOR(int N, double min_time, Random R)
{
double G[][] = RandomMatrix(N, N, R);
int rep = 10; // 11s @ 594MHz
//rep = 75; // 42.5s @ 1026MHz
//rep = 150; // 68s @ 1026MHz, this just fully melts PCM, at end of benchmark
//rep = 250; // 113s @ 1026MHz
//rep = 300; // 126s @ 1026MHz, using this setting in my house, PCM melts fully
rep = 75;
// 75 short duration
// 300 medium duration
// 400 long duration
int cycles = 2048;
for (int i = 0; i < rep; i++)
{
SOR.execute(1.25, G, cycles);
}
return SOR.num_flops(N, N, cycles);
}
public static double measureMonteCarlo(double min_time, Random R)
{
Stopwatch Q = new Stopwatch();
int cycles=1;
while(true)
{
Q.start();
MonteCarlo.integrate(cycles);
Q.stop();
if (Q.read() >= min_time) break;
cycles *= 2;
}
// approx Mflops
return MonteCarlo.num_flops(cycles) / Q.read() * 1.0e-6;
}
public static double measureSparseMatmult(int N, int nz,
double min_time, Random R)
{
// initialize vector multipliers and storage for result
// y = A*y;
double x[] = RandomVector(N, R);
double y[] = new double[N];
// initialize square sparse matrix
//
// for this test, we create a sparse matrix wit M/nz nonzeros
// per row, with spaced-out evenly between the begining of the
// row to the main diagonal. Thus, the resulting pattern looks
// like
// +-----------------+
// +* +
// +*** +
// +* * * +
// +** * * +
// +** * * +
// +* * * * +
// +* * * * +
// +* * * * +
// +-----------------+
//
// (as best reproducible with integer artihmetic)
// Note that the first nr rows will have elements past
// the diagonal.
int nr = nz/N; // average number of nonzeros per row
int anz = nr *N; // _actual_ number of nonzeros
double val[] = RandomVector(anz, R);
int col[] = new int[anz];
int row[] = new int[N+1];
row[0] = 0;
for (int r=0; r<N; r++)
{
// initialize elements for row r
int rowr = row[r];
row[r+1] = rowr + nr;
int step = r/ nr;
if (step < 1) step = 1; // take at least unit steps
for (int i=0; i<nr; i++)
col[rowr+i] = i*step;
}
//Stopwatch Q = new Stopwatch();
int cycles = 2048;
//while(true)
//while(cycles <= 65536) // about 20 seconds
//while(cycles <= 1048576) // about 200 seconds
int rep = 30; // 14 sec @ 594
for (int i = 0; i < rep; i++)
{
//Q.start();
SparseCompRow.matmult(y, val, row, col, x, cycles);
//Q.stop();
//if (Q.read() >= min_time) break;
//cycles *= 2;
}
// approx Mflops
//return SparseCompRow.num_flops(N, nz, cycles) / Q.read() * 1.0e-6;
return SparseCompRow.num_flops(N, nz, cycles);
}
public static double measureLU(int N, double min_time, Random R)
{
// compute approx Mlfops, or O if LU yields large errors
double A[][] = RandomMatrix(N, N, R);
double lu[][] = new double[N][N];
int pivot[] = new int[N];
//Stopwatch Q = new Stopwatch();
//while(true)
//while (cycles <= 8192)
//while (cycles <= 2048) // approx 20 sec
//while (cycles <= 6144) // approx 30 sec @ 1242MHz
//while (cycles <= 12288) // approx 60 sec @ 1242MHz
//while (cycles <= 14336) // approx 70 sec @ 1242MHz
//while (cycles <= 16384) // approx 80 sec @ 1242MHz
int cycles = 2048; // 14 sec @ 594Hz
for (int j = 0; j < cycles; j++)
{
//Q.start();
//for (int i=0; i<cycles; i++)
//{
CopyMatrix(lu, A);
LU.factor(lu, pivot);
//}
//Q.stop();
//if (Q.read() >= min_time) break;
//cycles *= 2;
}
// verify that LU is correct
double b[] = RandomVector(N, R);
double x[] = NewVectorCopy(b);
LU.solve(lu, pivot, x);
final double EPS = 1.0e-12;
if ( normabs(b, matvec(A,x)) / N > EPS )
return 0.0;
// else return approx Mflops
//
//return LU.num_flops(N) * cycles / Q.read() * 1.0e-6;
return LU.num_flops(N) * cycles;
}
private static double[] NewVectorCopy(double x[])
{
int N = x.length;
double y[] = new double[N];
for (int i=0; i<N; i++)
y[i] = x[i];
return y;
}
private static void CopyVector(double B[], double A[])
{
int N = A.length;
for (int i=0; i<N; i++)
B[i] = A[i];
}
private static double normabs(double x[], double y[])
{
int N = x.length;
double sum = 0.0;
for (int i=0; i<N; i++)
sum += Math.abs(x[i]-y[i]);
return sum;
}
public static void CopyMatrix(double B[][], double A[][])
{
int M = A.length;
int N = A[0].length;
int remainder = N & 3; // N mod 4;
for (int i=0; i<M; i++)
{
double Bi[] = B[i];
double Ai[] = A[i];
for (int j=0; j<remainder; j++)
Bi[j] = Ai[j];
for (int j=remainder; j<N; j+=4)
{
Bi[j] = Ai[j];
Bi[j+1] = Ai[j+1];
Bi[j+2] = Ai[j+2];
Bi[j+3] = Ai[j+3];
}
}
}
public static double[][] RandomMatrix(int M, int N, Random R)
{
double A[][] = new double[M][N];
for (int i=0; i<N; i++)
for (int j=0; j<N; j++)
A[i][j] = R.nextDouble();
return A;
}
public static double[] RandomVector(int N, Random R)
{
double A[] = new double[N];
for (int i=0; i<N; i++)
A[i] = R.nextDouble();
return A;
}
private static double[] matvec(double A[][], double x[])
{
int N = x.length;
double y[] = new double[N];
matvec(A, x, y);
return y;
}
private static void matvec(double A[][], double x[], double y[])
{
int M = A.length;
int N = A[0].length;
for (int i=0; i<M; i++)
{
double sum = 0.0;
double Ai[] = A[i];
for (int j=0; j<N; j++)
sum += Ai[j] * x[j];
y[i] = sum;
}
}
}
| Java |
'use strict'
const reduce = Function.bind.call(Function.call, Array.prototype.reduce);
const isEnumerable = Function.bind.call(Function.call, Object.prototype.propertyIsEnumerable);
const concat = Function.bind.call(Function.call, Array.prototype.concat);
const keys = Reflect.ownKeys;
if (!Object.values) {
Object.values = (O) => reduce(keys(O), (v, k) => concat(v, typeof k === 'string' && isEnumerable(O, k) ? [O[k]] : []), []);
}
if (!Object.entries) {
Object.entries = (O) => reduce(keys(O), (e, k) => concat(e, typeof k === 'string' && isEnumerable(O, k) ? [
[k, O[k]]
] : []), []);
}
//from
//https://medium.com/@_jh3y/throttling-and-debouncing-in-javascript-b01cad5c8edf#.jlqokoxtu
//or
//https://remysharp.com/2010/07/21/throttling-function-calls
function debounce(callback, delay) {
let timeout;
return function() {
const context = this,
args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => callback.apply(context, args), delay);
};
};
function throttle(func, limit) {
let inThrottle,
lastFunc,
throttleTimer;
return function() {
const context = this,
args = arguments;
if (inThrottle) {
clearTimeout(lastFunc);
return lastFunc = setTimeout(function() {
func.apply(context, args);
inThrottle = false;
}, limit);
} else {
func.apply(context, args);
inThrottle = true;
return throttleTimer = setTimeout(() => inThrottle = false, limit);
}
};
};
/*END POLIFILL*/ | Java |
class Admin::DashboardController < AdminAreaController
def index
#You are entering an area where no project is concerned, so forget about your current project
session[:project] = nil
end
end
| Java |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::DevTestLabs::Mgmt::V2018_09_15
module Models
#
# Defines values for SourceControlType
#
module SourceControlType
VsoGit = "VsoGit"
GitHub = "GitHub"
end
end
end
| Java |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>retro-205 Cardatron Control Unit</title>
<!--
/***********************************************************************
* retro-205/webUI D205CardatronControl.html
************************************************************************
* Copyright (c) 2015, Paul Kimpel.
* Licensed under the MIT License, see
* http://www.opensource.org/licenses/mit-license.php
************************************************************************
* ElectroData/Burroughs Datatron 205 Cardatron Control page.
************************************************************************
* 2015-02-01 P.Kimpel
* Original version, from D205ControlConsole.html.
***********************************************************************/
-->
<meta name="Author" content="Paul Kimpel">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<meta http-equiv="Content-Style-Type" content="text/css">
<link id=defaultStyleSheet rel=stylesheet type="text/css" href="D205Common.css">
<link id=consoleStyleSheet rel=stylesheet type="text/css" href="D205CardatronControl.css">
</head>
<body id=cardatronControlBody class=deviceBody>
<div id=PanelSurface>
<div id=InputSetupBtn class=blackButton1> </div>
<div id=InputSetupBtnCaption class=caption>INPUT<br>SETUP</div>
<div id=ClearBtn class=redButton1> </div>
<div id=ClearBtnCaption class=caption>GENERAL<br>CLEAR</div>
</div>
</body>
</html> | Java |
# infinite zoom plugin
"infinite zoom" is an jQuery-Plugin that creates a nice foto/image show as background on DOM-containers.
## Features
* applicable to any DOM-container
* adjustable zoom properties
* asynchronous image loading (just loads what's needed)
* rendering with the high-performance CSS3-transitions
## Requirements
* jQuery 1.3 or upwards
* a container which must have
* a 'overflow:hidden' css style
* a 'position' css style
* content with
* a 'position' css style
* a 'z-index' css style greater than 0
## Install
It`s very easy to install:
1. download or clone the current version
2. include the minified version into your code
## Usage
Will coming soon!
## License
See the "LICENSE" file in the root of the repo.
| Java |
<?php
use History\Entities\Models\Company;
use History\Entities\Models\Question;
use History\Entities\Models\Request;
use History\Entities\Models\Threads\Comment;
use History\Entities\Models\Threads\Thread;
use History\Entities\Models\User;
use History\Entities\Models\Vote;
use League\FactoryMuffin\FactoryMuffin;
use League\FactoryMuffin\Faker\Facade;
use League\FactoryMuffin\Faker\Faker;
/* @var FactoryMuffin $fm */
/** @var Faker $faker */
$faker = Facade::instance();
if (!function_exists('random')) {
/**
* @param string $class
*
* @return Closure
*/
function random($class)
{
if (!$class::count()) {
return 'factory|'.$class;
}
return function () use ($class) {
return $class::pluck('id')->shuffle()->first();
};
}
}
$fm->define(User::class)->setDefinitions([
'name' => $faker->userName(),
'full_name' => $faker->name(),
'email' => $faker->email(),
'contributions' => $faker->sentence(),
'company_id' => random(Company::class),
'no_votes' => $faker->randomNumber(1),
'yes_votes' => $faker->randomNumber(1),
'total_votes' => $faker->randomNumber(1),
'approval' => $faker->randomFloat(null, 0, 1),
'success' => $faker->randomFloat(null, 0, 1),
'hivemind' => $faker->randomFloat(null, 0, 1),
'created_at' => $faker->dateTimeThisYear(),
'updated_at' => $faker->dateTimeThisYear(),
]);
$fm->define(Request::class)->setDefinitions([
'name' => $faker->sentence(),
'contents' => $faker->paragraph(),
'link' => $faker->url(),
'condition' => $faker->boolean(2 / 3),
'approval' => $faker->randomFloat(null, 0, 1),
'status' => $faker->numberBetween(0, 5),
'created_at' => $faker->dateTimeThisDecade(),
'updated_at' => $faker->dateTimeThisDecade(),
])->setCallback(function (Request $request) {
$users = User::pluck('id')->shuffle()->take(2);
$request->authors()->sync($users->all());
});
$fm->define(Thread::class)->setDefinitions([
'name' => $faker->sentence(),
'user_id' => random(User::class),
'request_id' => random(Request::class),
'created_at' => $faker->dateTimeThisDecade(),
'updated_at' => $faker->dateTimeThisDecade(),
]);
$fm->define(Comment::class)->setDefinitions([
'name' => $faker->sentence(),
'contents' => $faker->paragraph(),
'xref' => $faker->randomNumber(1),
'created_at' => $faker->dateTimeThisYear(),
'updated_at' => $faker->dateTimeThisYear(),
'user_id' => random(User::class),
'thread_id' => random(Thread::class),
]);
$fm->define(Question::class)->setDefinitions([
'name' => $faker->sentence(),
'choices' => ['Yes', 'No'],
'approval' => $faker->randomFloat(null, 0, 1),
'passed' => $faker->boolean(),
'request_id' => random(Request::class),
'created_at' => $faker->dateTimeThisYear(),
'updated_at' => $faker->dateTimeThisYear(),
]);
$fm->define(Vote::class)->setDefinitions([
'choice' => $faker->numberBetween(1, 2),
'question_id' => random(Question::class),
'user_id' => random(User::class),
'created_at' => $faker->dateTimeThisYear(),
'updated_at' => $faker->dateTimeThisYear(),
]);
$fm->define(Company::class)->setDefinitions([
'name' => $faker->word(),
'representation' => $faker->randomNumber(1),
]);
| Java |
import {Routes} from '@angular/router';
import {JournalComponent} from '../journal/journal.component';
export const LUOO_APP_ROUTERS: Routes = [
{path: 'journal', component: JournalComponent}
]
| Java |
<template name="testWelcome">
<h2 class="center-align">Welcome Page</h2>
<div class="col-sm-6 col-md-offset-4 welcome-introduction">
<p>Welcome to Fram^ Online Testing</p>
<p>You have {{testingDuration}} minutes to complete your testting</p>
<p>Notice 1</p>
<p>Notice 2</p>
<p>Notice 3</p>
<p>......</p>
<p>...</p>
<p>ARE YOU READY ???</p>
</div>
<div class="center-align col-sm-12"> <button type="button" data-process-id="{{process._id}}" data-interview-index="{{this.index}}" class="btn btn-primary startTestingBtn">LET'S GO !!</button></div>
</template> | Java |
// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#include "swganh_core/gamesystems/gamesystems_service_binding.h"
BOOST_PYTHON_MODULE(py_gamesystems)
{
docstring_options local_docstring_options(true, true, false);
exportGameSystemsService();
} | Java |
var htmlparser = require('htmlparser2');
var _ = require('lodash');
var ent = require('ent');
module.exports = sanitizeHtml;
function sanitizeHtml(html, options) {
var result = '';
if (!options) {
options = sanitizeHtml.defaults;
} else {
_.defaults(options, sanitizeHtml.defaults);
}
// Tags that contain something other than HTML. If we are not allowing
// these tags, we should drop their content too. For other tags you would
// drop the tag but keep its content.
var nonTextTagsMap = {
script: true,
style: true
};
var allowedTagsMap = {};
_.each(options.allowedTags, function(tag) {
allowedTagsMap[tag] = true;
});
var selfClosingMap = {};
_.each(options.selfClosing, function(tag) {
selfClosingMap[tag] = true;
});
var allowedAttributesMap = {};
_.each(options.allowedAttributes, function(attributes, tag) {
allowedAttributesMap[tag] = {};
_.each(attributes, function(name) {
allowedAttributesMap[tag][name] = true;
});
});
var depth = 0;
var skipMap = {};
var skipText = false;
var parser = new htmlparser.Parser({
onopentag: function(name, attribs) {
var skip = false;
if (!_.has(allowedTagsMap, name)) {
skip = true;
if (_.has(nonTextTagsMap, name)) {
skipText = true;
}
skipMap[depth] = true;
}
depth++;
if (skip) {
// We want the contents but not this tag
return;
}
result += '<' + name;
if (_.has(allowedAttributesMap, name)) {
_.each(attribs, function(value, a) {
if (_.has(allowedAttributesMap[name], a)) {
result += ' ' + a;
if ((a === 'href') || (a === 'src')) {
if (naughtyHref(value)) {
return;
}
}
if (value.length) {
// Values are ALREADY escaped, calling escapeHtml here
// results in double escapes
result += '="' + value + '"';
}
}
});
}
if (_.has(selfClosingMap, name)) {
result += " />";
} else {
result += ">";
}
},
ontext: function(text) {
if (skipText) {
return;
}
// It is NOT actually raw text, entities are already escaped.
// If we call escapeHtml here we wind up double-escaping.
result += text;
},
onclosetag: function(name) {
skipText = false;
depth--;
if (skipMap[depth]) {
delete skipMap[depth];
return;
}
if (_.has(selfClosingMap, name)) {
// Already output />
return;
}
result += "</" + name + ">";
}
});
parser.write(html);
parser.end();
return result;
function escapeHtml(s) {
if (s === 'undefined') {
s = '';
}
if (typeof(s) !== 'string') {
s = s + '';
}
return s.replace(/\&/g, '&').replace(/</g, '<').replace(/\>/g, '>').replace(/\"/g, '"');
}
function naughtyHref(href) {
// So we don't get faked out by a hex or decimal escaped javascript URL #1
href = ent.decode(href);
// Browsers ignore character codes of 32 (space) and below in a surprising
// number of situations. Start reading here:
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Embedded_tab
href = href.replace(/[\x00-\x20]+/, '');
// Case insensitive so we don't get faked out by JAVASCRIPT #1
var matches = href.match(/^([a-zA-Z]+)\:/);
if (!matches) {
// No scheme = no way to inject js (right?)
return false;
}
var scheme = matches[1].toLowerCase();
return (!_.contains(['http', 'https', 'ftp', 'mailto' ], scheme));
}
}
// Defaults are accessible to you so that you can use them as a starting point
// programmatically if you wish
sanitizeHtml.defaults = {
allowedTags: [ 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre' ],
allowedAttributes: {
a: [ 'href', 'name', 'target' ],
// We don't currently allow img itself by default, but this
// would make sense if we did
img: [ 'src' ]
},
// Lots of these won't come up by default because we don't allow them
selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ]
};
| Java |
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ExtendComponent } from './src/components/extend.component';
import { SubExtendComponent } from './src/components/sub-extend.component';
const extendRoutes: Routes = [
{
path: '',
component: ExtendComponent,
},
{
path: 'main',
component: ExtendComponent,
},
{
path: 'sub',
component: SubExtendComponent
},
];
@NgModule({
imports: [
RouterModule.forChild(extendRoutes)
],
exports: [
RouterModule
]
})
export class ExtendRoutingModule {} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.