code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/**
*
* app.js
*
* This is the entry file for the application
*
*/
import FilmLocationSearchComponent from '../MovieSearchApp/Containers/FilmSearchContainer/FilmSearchComponent';
import AppComponent from '../CommonComponent/app.js';
import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
console.log("current href",window.location.href);
const getAppRouter = () => {
return (
<Route component={AppComponent}>
<Route component={FilmLocationSearchComponent} path='/searchmovies' />
</Route>
);
}
export {
getAppRouter
}
| anil26/MovieSearchGoogleMaps | js/Routes/AppRouter.js | JavaScript | mit | 597 |
/* Accordion directive */
app.directive('vmfAccordionContainer', ['$compile', function($compile) {
return {
restrict: 'EA',
scope: {
type: '@',
headers: '=',
accData: '=',
selAcc: '=',
customClass:'='
},
link: function(scope, elem, attrs) {
var template;
if(scope.type === '1') {
template = '<table class="vmf-accordion-table1"><thead class="vmf-accordion-table-header"><tr><td class="col1"></td>';
var count = 1;
angular.forEach(scope.headers, function(item) {
// if(count === 1) {
// template += '<td colspan="2">' + item + '</td>';
// }
// else {
template += '<td class="col' + (count + 1) +'">' + item + '</td>';
// }
count += 1;
});
template += '</tr></thead><tbody class="vmf-accordion-table-body">';
scope.accordionIndex = 0;
angular.forEach(scope.accData, function(item) {
template += '<tr class="vmf-accordion-header" ng-click="toggleAccordion(' + scope.accordionIndex + ')"><td ><span class="vmf-arrow"></span></td><td colspan="3">' + item.header + '</td></tr>';
angular.forEach(item.contents, function(content) {
template += '<tr class="vmf-accordion-row" ng-show="activeIndex =='+ scope.accordionIndex + '"><td colspan="1"></td>';
angular.forEach(content, function(cellData) {
template += '<td colspan="1">' + cellData + '</td>';
});
template += '</tr>';
});
scope.accordionIndex += 1;
});
template += '</tbody></table>';
elem.append(template);
// console.log(template);
$compile(elem.contents())(scope);
// for IE7
elem.find('.vmf-accordion-row').hide();
}
else if(scope.type === '2') {
template = '<table class="vmf-accordion-table2"><thead class="vmf-accordion-table2-header" style="background-color: lightgray;"><tr><td class="col1"></td>';
var headerCount = 0;
angular.forEach(scope.headers, function(item) {
if(headerCount !== scope.headers.length - 1) {
template += '<td class="col' + (headerCount + 1 + 1)+ '">' + item + '</td>';
}
else {
template += '<td colspan="2" class="col' + (headerCount + 1 + 1)+ '">' + item + '</td>';
}
headerCount += 1;
});
template += '</tr></thead><tbody class="vmf-accordion-table2-body">';
scope.accordionIndex = 0;
angular.forEach(scope.accData, function(item) {
template += '<tr class="vmf-accordion-header2" ng-click="toggleAccordion(' + scope.accordionIndex + ')"><td><span class="vmf-arrow"></span></td>';
var accHeadersCount = 1;
angular.forEach(item.headers, function(header) {
if(accHeadersCount !== item.headers.length) {
template += '<td>' + header + '</td>';
}
else {
template += '<td class="vmf-acc-header-last-child">' + header + '</td>';
}
accHeadersCount += 1;
});
template += '</tr><tr class="vmf-accordion-row2"><td></td><td class="vmf-acc-header-last-child" colspan="' + item.headers.length + '"><table class="vmf-accordion-sub-table" ng-show="activeIndex =='+ scope.accordionIndex + '">';
var count = 0;
angular.forEach(item.contents, function(content) {
if(count !== 0) {
template += '<tr class="vmf-accordion-sub-table-row">';
angular.forEach(content, function(cellData) {
template += '<td>' + cellData + '</td>';
});
template += '</tr>';
}
else {
template += '<thead class="vmf-accordion-sub-table-header"><tr>';
var subHeaderCount = 1;
angular.forEach(content, function(cellData) {
template += '<td class="col' + subHeaderCount + '">' + cellData + '</td>';
subHeaderCount += 1;
});
template += '</tr></thead><tbody class="vmf-accordion-sub-table-body">';
}
count += 1;
});
template += '</tbody></table></td></tr>';
scope.accordionIndex += 1;
});
template += '</tbody></table>';
elem.append(template);
// console.log(template);
if(scope.customClass){
angular.forEach(scope.customClass, function(item) {
elem.find(item.selector).addClass(item.cusclass);
});
}
$compile(elem.contents())(scope);
// for IE7
elem.find('.vmf-accordion-row2').hide();
// elem.find('.vmf-accordion-row2').hide();
}
scope.toggleAccordion = function(index) {
scope.activeIndex = scope.activeIndex === index ? -1 : index;
var accordions, accordionRows;
if(scope.type === '1') {
elem.find('.vmf-accordion-row').hide();
accordions = elem.find('.vmf-accordion-header');
accordions.removeClass('vmf-active-row');
// for IE7
if(scope.activeIndex !== -1) {
// accordions = elem.find('.vmf-accordion-header');
// console.log(accordions[index]);
$(accordions[index]).addClass('vmf-active-row');
accordionRows = $(accordions[index]).nextUntil('.vmf-accordion-header');
$(accordionRows).show();
}
}
else if(scope.type === '2') {
elem.find('.vmf-accordion-row2').hide();
accordions = elem.find('.vmf-accordion-header2');
accordions.removeClass('vmf-active-row');
// for IE7
if(scope.activeIndex !== -1) {
$(accordions[index]).addClass('vmf-active-row');
accordionRows = $(accordions[index]).nextUntil('.vmf-accordion-header2');
$(accordionRows).show();
}
}
};
scope.buttonClick = function($event, index) {
$event.stopPropagation();
scope.selAcc = index;
};
}
};
}]); | anandharshan/Web-components-DD | dev/modules/Accordion/accordionDirectives.js | JavaScript | mit | 8,055 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.comci.bigbib;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.bson.types.ObjectId;
import org.codehaus.jackson.annotate.JsonProperty;
import org.jbibtex.BibTeXEntry;
import org.jbibtex.Key;
import org.jbibtex.StringValue;
import org.jbibtex.Value;
/**
*
* @author Sebastian
*/
@XmlRootElement()
@XmlAccessorType(XmlAccessType.NONE)
public class PeristentBibTexEntry extends BibTeXEntry {
private ObjectId id;
public PeristentBibTexEntry(Key type, Key key) {
super(type, key);
}
static Map<String, Key> keyMapping = new HashMap<String, Key>();
static {
keyMapping.put("address", BibTeXEntry.KEY_ADDRESS);
keyMapping.put("annote", BibTeXEntry.KEY_ANNOTE);
keyMapping.put("author", BibTeXEntry.KEY_AUTHOR);
keyMapping.put("booktitle", BibTeXEntry.KEY_BOOKTITLE);
keyMapping.put("chapter", BibTeXEntry.KEY_CHAPTER);
keyMapping.put("crossref", BibTeXEntry.KEY_CROSSREF);
keyMapping.put("doi", BibTeXEntry.KEY_DOI);
keyMapping.put("edition", BibTeXEntry.KEY_EDITION);
keyMapping.put("editor", BibTeXEntry.KEY_EDITOR);
keyMapping.put("eprint", BibTeXEntry.KEY_EPRINT);
keyMapping.put("howpublished", BibTeXEntry.KEY_HOWPUBLISHED);
keyMapping.put("institution", BibTeXEntry.KEY_INSTITUTION);
keyMapping.put("journal", BibTeXEntry.KEY_JOURNAL);
keyMapping.put("key", BibTeXEntry.KEY_KEY);
keyMapping.put("month", BibTeXEntry.KEY_MONTH);
keyMapping.put("note", BibTeXEntry.KEY_NOTE);
keyMapping.put("number", BibTeXEntry.KEY_NUMBER);
keyMapping.put("organization", BibTeXEntry.KEY_ORGANIZATION);
keyMapping.put("pages", BibTeXEntry.KEY_PAGES);
keyMapping.put("publisher", BibTeXEntry.KEY_PUBLISHER);
keyMapping.put("school", BibTeXEntry.KEY_SCHOOL);
keyMapping.put("series", BibTeXEntry.KEY_SERIES);
keyMapping.put("title", BibTeXEntry.KEY_TITLE);
keyMapping.put("type", BibTeXEntry.KEY_TYPE);
keyMapping.put("url", BibTeXEntry.KEY_URL);
keyMapping.put("volume", BibTeXEntry.KEY_VOLUME);
keyMapping.put("year", BibTeXEntry.KEY_YEAR);
}
public PeristentBibTexEntry(DBObject persistentObject) {
super(
new Key((String) persistentObject.get("type")),
new Key((String) persistentObject.get("key"))
);
BasicDBObject fields = (BasicDBObject) persistentObject.get("fields");
id = (ObjectId) persistentObject.get("_id");
for (String key : fields.keySet()) {
if (keyMapping.containsKey(key)) {
this.addField(keyMapping.get(key), new StringValue(fields.getString(key), StringValue.Style.BRACED));
} else {
this.addField(new Key(key), new StringValue(fields.getString(key), StringValue.Style.BRACED));
}
}
}
@JsonProperty("id")
@XmlElement(name="id")
public String getStringId() {
return id.toString();
}
@JsonProperty("key")
@XmlElement(name="key")
public String getStringKey() {
return super.getKey().getValue();
}
@JsonProperty("type")
@XmlElement(name="type")
public String getStringType() {
return super.getType().getValue();
}
@JsonProperty("fields")
@XmlElement(name="fields")
public Map<String, String> getStringFields() {
Map<String, String> fields = new HashMap<String, String>();
for (Entry<Key,Value> e : getFields().entrySet()) {
if (e.getKey() != null && e.getValue() != null) {
fields.put(e.getKey().getValue(), e.getValue().toUserString());
}
}
return fields;
}
@Override
public String toString() {
return String.format("[%s:%s] %s: %s (%s)",
this.getType(),
this.getKey(),
this.getField(KEY_AUTHOR).toUserString(),
this.getField(KEY_TITLE).toUserString(),
this.getField(KEY_YEAR).toUserString());
}
}
| maiers/bigbib | src/main/java/de/comci/bigbib/PeristentBibTexEntry.java | Java | mit | 4,524 |
module Admin::BaseHelper
include ActionView::Helpers::DateHelper
def subtabs_for(current_module)
output = []
AccessControl.project_module(current_user.profile.label, current_module).submenus.each_with_index do |m,i|
current = (m.url[:controller] == params[:controller] && m.url[:action] == params[:action]) ? "current" : ""
output << subtab(_(m.name), current, m.url)
end
content_for(:tasks) { output.join("\n") }
end
def subtab(label, style, options = {})
content_tag :li, link_to(label, options, { "class"=> style })
end
def show_page_heading
content_tag(:h2, @page_heading, :class => 'mb20') unless @page_heading.blank?
end
def cancel(url = {:action => 'index'})
link_to _("Cancel"), url
end
def save(val = _("Store"))
'<input type="submit" value="' + val + '" class="save" />'
end
def confirm_delete(val = _("Delete"))
'<input type="submit" value="' + val + '" />'
end
def link_to_show(record, controller = @controller.controller_name)
if record.published?
link_to image_tag('admin/show.png', :alt => _("show"), :title => _("Show content")),
{:controller => controller, :action => 'show', :id => record.id},
{:class => "lbOn"}
end
end
def link_to_edit(label, record, controller = @controller.controller_name)
link_to label, :controller => controller, :action => 'edit', :id => record.id
end
def link_to_edit_with_profiles(label, record, controller = @controller.controller_name)
if current_user.admin? || current_user.id == record.user_id
link_to label, :controller => controller, :action => 'edit', :id => record.id
end
end
def link_to_destroy(record, controller = @controller.controller_name)
link_to image_tag('admin/delete.png', :alt => _("delete"), :title => _("Delete content")),
:controller => controller, :action => 'destroy', :id => record.id
end
def link_to_destroy_with_profiles(record, controller = @controller.controller_name)
if current_user.admin? || current_user.id == record.user_id
link_to(_("delete"),
{ :controller => controller, :action => 'destroy', :id => record.id }, :confirm => _("Are you sure?"), :method => :post, :title => _("Delete content"))
end
end
def text_filter_options
TextFilter.find(:all).collect do |filter|
[ filter.description, filter ]
end
end
def text_filter_options_with_id
TextFilter.find(:all).collect do |filter|
[ filter.description, filter.id ]
end
end
def alternate_class
@class = @class != '' ? '' : 'class="shade"'
end
def reset_alternation
@class = nil
end
def task_quickpost(title)
link_to_function(title, toggle_effect('quick-post', 'Effect.BlindUp', "duration:0.4", "Effect.BlindDown", "duration:0.4"))
end
def task_overview
content_tag :li, link_to(_('Back to overview'), :action => 'index')
end
def task_add_resource_metadata(title,id)
link_to_function(title, toggle_effect('add-resource-metadata-' + id.to_s, 'Effect.BlindUp', "duration:0.4", "Effect.BlindDown", "duration:0.4"))
end
def task_edit_resource_metadata(title,id)
link_to_function(title, toggle_effect('edit-resource-metadata-' + id.to_s, 'Effect.BlindUp', "duration:0.4", "Effect.BlindDown", "duration:0.4"))
end
def task_edit_resource_mime(title,id)
link_to_function(title, toggle_effect('edit-resource-mime-' + id.to_s, 'Effect.BlindUp', "duration:0.4", "Effect.BlindDown", "duration:0.4"))
end
def class_write
if controller.controller_name == "content" or controller.controller_name == "pages"
"current" if controller.action_name == "new"
end
end
def class_content
if controller.controller_name =~ /content|pages|categories|resources|feedback/
"current" if controller.action_name =~ /list|index|show/
end
end
def class_themes
"current" if controller.controller_name =~ /themes|sidebar/
end
def class_users
controller.controller_name =~ /users/ ? "current right" : "right"
end
def class_dashboard
controller.controller_name =~ /dashboard/ ? "current right" : "right"
end
def class_settings
controller.controller_name =~ /settings|textfilter/ ? "current right" : "right"
end
def class_profile
controller.controller_name =~ /profiles/ ? "current right" : "right"
end
def alternate_editor
return 'visual' if current_user.editor == 'simple'
return 'simple'
end
def collection_select_with_current(object, method, collection, value_method, text_method, current_value, prompt=false)
result = "<select name='#{object}[#{method}]'>\n"
if prompt == true
result << "<option value=''>" << _("Please select") << "</option>"
end
for element in collection
if current_value and current_value == element.send(value_method)
result << "<option value='#{element.send(value_method)}' selected='selected'>#{element.send(text_method)}</option>\n"
else
result << "<option value='#{element.send(value_method)}'>#{element.send(text_method)}</option>\n"
end
end
result << "</select>\n"
return result
end
def render_void_table(size, cols)
if size == 0
"<tr>\n<td colspan=#{cols}>" + _("There are no %s yet. Why don't you start and create one?", _(controller.controller_name)) + "</td>\n</tr>\n"
end
end
def cancel_or_save
result = '<p class="right">'
result << cancel
result << " "
result << _("or")
result << " "
result << save( _("Save") + " »")
result << '</p>'
return result
end
def link_to_published(item)
item.published? ? link_to_permalink(item, _("published"), '', 'published') : "<span class='unpublished'>#{_("unpublished")}</span>"
end
def macro_help_popup(macro, text)
unless current_user.editor == 'visual'
"<a rel='lightbox' href=\"#{url_for :controller => 'textfilters', :action => 'macro_help', :id => macro.short_name}\" onclick=\"return popup(this, 'Typo Macro Help')\">#{text}</a>"
end
end
def render_macros(macros)
result = link_to_function _("Show help on Typo macros") + " (+/-)",update_page { |page| page.visual_effect(:toggle_blind, "macros", :duration => 0.2) }
result << "<table id='macros' style='display: none;'>"
result << "<tr>"
result << "<th>#{_('Name')}</th>"
result << "<th>#{_('Description')}</th>"
result << "<th>#{_('Tag')}</th>"
result << "</tr>"
for macro in macros.sort_by { |f| f.short_name }
result << "<tr #{alternate_class}>"
result << "<td>#{macro_help_popup macro, macro.display_name}</td>"
result << "<td>#{h macro.description}</td>"
result << "<td><code><typo:#{h macro.short_name}></code></td>"
result << "</tr>"
end
result << "</table>"
end
def build_editor_link(label, action, id, update, editor)
link = link_to_remote(label,
:url => { :action => action, 'editor' => editor},
:loading => "new Element.show('update_spinner_#{id}')",
:success => "new Element.toggle('update_spinner_#{id}')",
:update => "#{update}")
link << image_tag("spinner-blue.gif", :id => "update_spinner_#{id}", :style => 'display:none;')
end
def display_pagination(collection, cols)
if WillPaginate::ViewHelpers.total_pages_for_collection(collection) > 1
return "<tr><td colspan=#{cols} class='paginate'>#{will_paginate(collection)}</td></tr>"
end
end
def show_thumbnail_for_editor(image)
thumb = "#{RAILS_ROOT}/public/files/thumb_#{image.filename}"
picture = "#{this_blog.base_url}/files/#{image.filename}"
image.create_thumbnail unless File.exists? thumb
# If something went wrong with thumbnail generation, we just display a place holder
thumbnail = (File.exists? thumb) ? "#{this_blog.base_url}/files/thumb_#{image.filename}" : "#{this_blog.base_url}/images/thumb_blank.jpg"
picture = "<img class='tumb' src='#{thumbnail}' "
picture << "alt='#{this_blog.base_url}/files/#{image.filename}' "
picture << " onclick=\"edInsertImageFromCarousel('article_body_and_extended', '#{this_blog.base_url}/files/#{image.filename}');\" />"
return picture
end
end
| jasondew/cola.rb | app/helpers/admin/base_helper.rb | Ruby | mit | 8,319 |
<?php
namespace Editionista\WebsiteBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller as Controller;
use Editionista\WebsiteBundle\Entity\Tag;
/**
* Edition controller.
*
* @Route("/tags")
*/
class TagController extends Controller
{
/**
* @Route("/", name="tags")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$tags = $em->getRepository('EditionistaWebsiteBundle:Tag')->findAll();
return array('tags' => $tags);
}
/**
* @Route("/{tag}", name="show_tag")
* @Template()
*/
public function showAction($tag)
{
$em = $this->getDoctrine()->getManager();
$tag = $em->getRepository('EditionistaWebsiteBundle:Tag')->findOneByName($tag);
$editions = $tag->getEditions();
return array('tag' => $tag, 'editions' => $editions);
}
/**
* @Route("/push", name="push_tags")
* @Method({"POST"})
*/
public function pushAction(Request $request)
{
$pushedTag = $request->request->get('tag');
$em = $this->getDoctrine()->getManager();
$storedTag = $em->getRepository('EditionistaWebsiteBundle:Tag')->findOneByName($pushedTag);
if($storedTag == null) {
$tag = new Tag();
$tag->setName($pushedTag);
$em = $this->getDoctrine()->getManager();
$em->persist($tag);
$em->flush();
}
$response = new Response(json_encode(array('tag' => $pushedTag)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/pull", name="pull_tags")
*/
public function pullAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('EditionistaWebsiteBundle:Tag')->findAll();
$tags = array();
foreach($entities as $entity) {
$tags['tags'][] = array('tag' => $entity->getName());
}
$response = new Response(json_encode($tags));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
| fabstei/editionista | src/Editionista/WebsiteBundle/Controller/TagController.php | PHP | mit | 2,557 |
using System;
using System.Reflection;
namespace Light.DataCore
{
abstract class DynamicFieldMapping : FieldMapping
{
public static DynamicFieldMapping CreateDynmaicFieldMapping (PropertyInfo property, DynamicCustomMapping mapping)
{
DynamicFieldMapping fieldMapping;
Type type = property.PropertyType;
TypeInfo typeInfo = type.GetTypeInfo();
string fieldName = property.Name;
if (typeInfo.IsGenericType) {
Type frameType = type.GetGenericTypeDefinition ();
if (frameType.FullName == "System.Nullable`1") {
Type [] arguments = type.GetGenericArguments ();
type = arguments [0];
typeInfo = type.GetTypeInfo();
}
}
if (type.IsArray) {
throw new LightDataException(string.Format(SR.DataMappingUnsupportFieldType, property.DeclaringType, property.Name, type));
}
else if (type.IsGenericParameter || typeInfo.IsGenericTypeDefinition) {
throw new LightDataException(string.Format(SR.DataMappingUnsupportFieldType, property.DeclaringType, property.Name, type));
}
else if (typeInfo.IsEnum) {
DynamicEnumFieldMapping enumFieldMapping = new DynamicEnumFieldMapping (type, fieldName, mapping);
fieldMapping = enumFieldMapping;
}
else {
TypeCode code = Type.GetTypeCode (type);
switch (code) {
case TypeCode.Empty:
case TypeCode.Object:
throw new LightDataException(string.Format(SR.DataMappingUnsupportFieldType, property.DeclaringType, property.Name, type));
default:
DynamicPrimitiveFieldMapping primitiveFieldMapping = new DynamicPrimitiveFieldMapping (type, fieldName, mapping);
fieldMapping = primitiveFieldMapping;
break;
}
}
return fieldMapping;
}
protected DynamicFieldMapping (Type type, string fieldName, DynamicCustomMapping mapping, bool isNullable)
: base (type, fieldName, fieldName, mapping, isNullable, null)
{
}
}
}
| aquilahkj/Light.DataCore | Light.DataCore/Mappings/DynamicFieldMapping.cs | C# | mit | 1,881 |
class Solution {
public:
int findRadius(vector<int>& houses, vector<int>& heaters) {
sort(houses.begin(), houses.end());
sort(heaters.begin(), heaters.end());
auto radius = 0;
auto idx = 0;
for (auto house : houses) {
auto current = abs(house - heaters[idx]);
if (current <= radius) continue;
for (auto n = idx + 1; n < heaters.size(); ++n) {
if (abs(house - heaters[n]) <= current) {
current = abs(house - heaters[n]);
idx = n;
} else {
break;
}
}
radius = max(radius, current);
}
return radius;
}
}; | wait4pumpkin/leetcode | 475.cc | C++ | mit | 561 |
from django.conf.urls import patterns, include, url
import views
urlpatterns = patterns('',
url(r'^logout', views.logout, name='logout'),
url(r'^newUser', views.newUser, name='newUser'),
url(r'^appHandler', views.appHandler, name='appHandler'),
url(r'^passToLogin', views.loginByPassword, name='passToLogin'),
url(r'^signToLogin', views.loginBySignature, name='signToLogin'),
url(r'^authUserHandler', views.authUserHandler, name='authUserHandler'),
)
| odeke-em/restAssured | auth/urls.py | Python | mit | 477 |
module Dragoman
module Mapper
def localize
locales = I18n.available_locales
unscoped_locales = [I18n.default_locale]
scoped_locales = locales - unscoped_locales
scope ':locale', shallow_path: ':locale', defaults: {dragoman_options: {locales: scoped_locales}} do
yield
end
defaults dragoman_options: {locales: unscoped_locales} do
yield
end
@locales = nil
end
end
end | pietervisser/dragoman | lib/dragoman/mapper.rb | Ruby | mit | 442 |
<?php
if(!defined('BASEPATH'))
die;
class MY_Controller extends CI_Controller
{
public $session;
public $user;
function __construct(){
parent::__construct();
$this->output->set_header('X-Powered-By: ' . config_item('system_vendor'));
$this->output->set_header('X-Deadpool: ' . config_item('header_message'));
$this->load->library('SiteEnum', '', 'enum');
$this->load->library('SiteParams', '', 'setting');
$this->load->library('SiteTheme', '', 'theme');
$this->load->library('SiteMenu', '', 'menu');
$this->load->library('SiteForm', '', 'form');
$this->load->library('SiteMeta', '', 'meta');
$this->load->library('ObjectMeta', '', 'ometa');
$this->load->library('ActionEvent', '', 'event');
$cookie_name = config_item('sess_cookie_name');
$hash = $this->input->cookie($cookie_name);
if($hash){
$this->load->model('Usersession_model', 'USession');
$session = $this->USession->getBy('hash', $hash);
$this->session = $session;
if($session){
$this->load->model('User_model', 'User');
$user = $this->User->get($session->user);
// TODO
// Increase session expiration if it's almost expired
if($user && $user->status > 1){
$this->user = $user;
$this->user->perms = [];
if($user){
if($user->id == 1){
$this->load->model('Perms_model', 'Perms');
$user_perms = $this->Perms->getByCond([], true, false);
$this->user->perms = prop_values($user_perms, 'name');
}else{
$this->load->model('Userperms_model', 'UPerms');
$user_perms = $this->UPerms->getBy('user', $user->id, true);
if($user_perms)
$this->user->perms = prop_values($user_perms, 'perms');
}
$this->user->perms[] = 'logged_in';
}
}
}
}
if($this->theme->current() == 'admin/')
$this->lang->load('admin', config_item('language'));
}
/**
* Return to client as ajax respond.
* @param mixed data The data to return.
* @param mixed error The error data.
* @param mixed append Additional data to append to result.
*/
public function ajax($data, $error=false, $append=null){
$result = array(
'data' => $data,
'error'=> $error
);
if($append)
$result = array_merge($result, $append);
$cb = $this->input->get('cb');
if(!$cb)
$cb = $this->input->get('callback');
$json = json_encode($result);
$cset = config_item('charset');
if($cb){
$json = "$cb($json);";
$this->output
->set_status_header(200)
->set_content_type('application/javascript', $cset)
->set_output($json)
->_display();
exit;
}else{
$this->output
->set_status_header(200)
->set_content_type('application/json', $cset)
->set_output($json)
->_display();
exit;
}
}
/**
* Check if current admin user can do something
* @param string perms The perms to check.
* @return boolean true on allowed, false otherwise.
*/
public function can_i($perms){
if(!$this->user)
return false;
return in_array($perms, $this->user->perms);
}
/**
* Redirect to some URL.
* @param string next Target URL.
* @param integer status Redirect status.
*/
public function redirect($next='/', $status=NULL){
if(substr($next, 0, 4) != 'http')
$next = base_url($next);
redirect($next, 'auto', $status);
}
/**
* Print page.
* @param string view The view to load.
* @param array params The parameters to send to view.
*/
public function respond($view, $params=array()){
$page_title = '';
if(array_key_exists('title', $params))
$page_title = $params['title'] . ' - ';
$page_title.= $this->setting->item('site_name');
$params['page_title'] = $page_title;
if(!$this->theme->exists($view) && !is_dev())
return $this->show_404();
$this->theme->load($view, $params);
}
/**
* Print 404 page
*/
public function show_404(){
$this->load->model('Urlredirection_model', 'Redirection');
$next = $this->Redirection->getBy('source', uri_string());
if($next)
return $this->redirect($next->target, 301);
$this->output->set_status_header('404');
$params = array(
'title' => _l('Page not found')
);
$this->respond('404', $params);
}
} | iqbalfn/admin | application/core/MY_Controller.php | PHP | mit | 5,404 |
/* ================================================================
* startserver by xdf(xudafeng[at]126.com)
*
* first created at : Mon Jun 02 2014 20:15:51 GMT+0800 (CST)
*
* ================================================================
* Copyright 2013 xdf
*
* Licensed under the MIT License
* You may not use this file except in compliance with the License.
*
* ================================================================ */
'use strict';
var logx = require('logx');
function *logger() {
var log = 'Method: '.gray + this.req.method.red;
log += ' Url: '.gray + this.req.url.red;
logx.info(log);
yield this.next();
}
module.exports = logger;
| xudafeng/startserver | lib/middleware/logger/index.js | JavaScript | mit | 675 |
/**
* Default admin
*/
new User({
firstName: 'Admin',
lastName: 'Admin',
username: 'admin',
type: 'admin',
password: 'admin',
email: 'admin@admin.com',
subscribed: false,
}).save((u) => {
})
/**
* Test users
*/
new User({
firstName: 'Jonathan',
lastName: 'Santos',
username: 'santojon',
type: 'user',
password: 'test',
email: 'santojon5@gmail.com',
gender: 'Male',
subscribed: true,
image: 'https://avatars1.githubusercontent.com/u/4976482'
}).save((u) => {
UserController.updateUser(u)
})
new User({
firstName: 'Raphael',
lastName: 'Tulyo',
username: 'crazybird',
type: 'user',
password: 'test',
email: 'rtsd@cin.ufpe.br',
gender: 'Male',
subscribed: true
}).save((u) => {
UserController.updateUser(u)
})
new User({
firstName: 'Vinícius',
lastName: 'Emanuel',
username: 'vems',
type: 'user',
password: 'test',
email: 'vems@cin.ufpe.br',
gender: 'Male',
subscribed: true
}).save((u) => {
UserController.updateUser(u)
})
/**
* More test users
*/
for (i = 0; i < 5; i++) {
new User({
firstName: 'Test' + i,
lastName: '' + i,
username: 'testuser' + i,
type: 'user',
password: 'test',
email: 'test' + i + '@test.br',
gender: (i % 2 === 0) ? 'Male' : 'Female',
subscribed: true
}).save((u) => {
UserController.updateUser(u)
})
}
Subscription.findAll().forEach((s) => {
s.status = true
s.update(s)
}) | santojon/hardStone | bootstrap.js | JavaScript | mit | 1,538 |
using UnityEngine;
using System.Collections;
public class GravitySwitch : MonoBehaviour
{
public float GravityStrength;
float momentum;
float click;
public bool GameState;
bool GravityState;
public GameObject Explosion;
public GameObject[] Jets;
public GameObject[] CharacterPieces;
public Vector3 hitposition;
public GameObject EndScreen;
public UILabel BestScore;
void Start()
{
GravityStrength = 0;
BestScore.text = "Best:" + PlayerPrefs.GetFloat("BestScore").ToString();
GameState = true;
}
void Update ()
{
Gravity();
Controls();
if (GameState == false)
{
transform.position = hitposition;
EndScreen.SetActive(true);
}
}
void Gravity()
{
//transform.Translate(new Vector3(3,0) * Time.deltaTime);
switch (GravityState)
{
case true: Physics2D.gravity = new Vector2(momentum,GravityStrength); /*transform.localEulerAngles = new Vector2(-180, 0);*/ break;
case false: Physics2D.gravity = new Vector2(momentum,-GravityStrength); /*transform.localEulerAngles = new Vector2(0, 0);*/ break;
}
if (GravityStrength == 0)
{
transform.position = new Vector3(0,-5.5f,0);
}
}
void Controls()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GravityState = !GravityState;
}
if (Input.GetMouseButtonDown(0))
{
GravityState = !GravityState;
if (click == 0)
{
momentum = 2;
GravityStrength = 27;
foreach(GameObject jet in Jets)
{
jet.SetActive(true);
}
}
click+=1;
}
}
void OnCollisionEnter2D(Collision2D other)
{
//Application.LoadLevel(Application.loadedLevel);
if (GameState == true)
{
foreach (ContactPoint2D contact in other.contacts)
{
GameObject Hit = Instantiate (Explosion, contact.point, Quaternion.identity) as GameObject;
hitposition = Hit.transform.position;
GameState = false;
}
foreach (GameObject self in CharacterPieces)
{
self.SetActive(false);
}
}
}
}
| parodyband/Polarity | Assets/Code/GravitySwitch.cs | C# | mit | 1,927 |
import sys
import pytest
from opentracing.ext import tags
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import mysqldb as mysqldb_hooks
from opentracing_instrumentation.request_context import span_in_context
from .sql_common import metadata, User
SKIP_REASON_PYTHON_3 = 'MySQLdb is not compatible with Python 3'
SKIP_REASON_CONNECTION = 'MySQL is not running or cannot connect'
MYSQL_CONNECTION_STRING = 'mysql://root@127.0.0.1/test'
@pytest.fixture
def session():
Session = sessionmaker()
engine = create_engine(MYSQL_CONNECTION_STRING)
Session.configure(bind=engine)
metadata.create_all(engine)
try:
yield Session()
except:
pass
@pytest.fixture(autouse=True, scope='module')
def patch_sqlalchemy():
mysqldb_hooks.install_patches()
try:
yield
finally:
mysqldb_hooks.reset_patches()
def is_mysql_running():
try:
import MySQLdb
with MySQLdb.connect(host='127.0.0.1', user='root'):
pass
return True
except:
return False
def assert_span(span, operation, parent=None):
assert span.operation_name == 'MySQLdb:' + operation
assert span.tags.get(tags.SPAN_KIND) == tags.SPAN_KIND_RPC_CLIENT
if parent:
assert span.parent_id == parent.context.span_id
assert span.context.trace_id == parent.context.trace_id
else:
assert span.parent_id is None
@pytest.mark.skipif(not is_mysql_running(), reason=SKIP_REASON_CONNECTION)
@pytest.mark.skipif(sys.version_info.major == 3, reason=SKIP_REASON_PYTHON_3)
def test_db(tracer, session):
root_span = tracer.start_span('root-span')
# span recording works for regular operations within a context only
with span_in_context(root_span):
user = User(name='user', fullname='User', password='password')
session.add(user)
session.commit()
spans = tracer.recorder.get_spans()
assert len(spans) == 4
connect_span, insert_span, commit_span, rollback_span = spans
assert_span(connect_span, 'Connect')
assert_span(insert_span, 'INSERT', root_span)
assert_span(commit_span, 'commit', root_span)
assert_span(rollback_span, 'rollback', root_span)
| uber-common/opentracing-python-instrumentation | tests/opentracing_instrumentation/test_mysqldb.py | Python | mit | 2,279 |
// Write a boolean expression that returns if the bit at position p (counting from 0)
// in a given integer number v has value of 1. Example: v=5; p=1 -> false.
using System;
class BitInIntegerCheck
{
static void Main()
{
// декларираме променливи за числото (v) и позицията (p), за която ще проверяваме
int v = 8;
int p = 3;
// израза е прекалено лесен и не мисля, че си заслужава декларацията на 2 допълнителни променливи...
// умножаваме "v" с 1 предварително отместено "p" пъти наляво, след което резултатът бива отместен "p" пъти надясно
// със същият успех може и да се премести единицата от дясната страна на израза "p" пъти наляво,
// като по този начин си спестяваме връщането "p" пъти надясно от другата страна на равенството и е по-лесно за разбиране/четене
// => if( v & ( 1 << p ) == 1 << p )
if( ( v & ( 1 << p ) ) >> p == 1 )
{
Console.WriteLine("The value {0} has a 1 at bit number {1}", v, p);
}
else
{
Console.WriteLine("The value {0} has a 0 at bit number {1}", v, p);
}
}
} | Steffkn/TelerikAcademy | Programming/01. CSharp Part 1/03.OperatorsAndExpressions/10.BinInIntegerCheck/BitInIntegerCheck.cs | C# | mit | 1,546 |
/*
* Copyright 2017 Max Schafer, Ammar Mahdi, Riley Dixon, Steven Weikai Lu, Jiaxiong Yang
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.example.lit.habit;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Base64;
import android.util.Log;
import com.example.lit.exception.BitmapTooLargeException;
import com.example.lit.exception.HabitFormatException;
import com.example.lit.saving.Saveable;
import com.example.lit.exception.HabitFormatException;
import io.searchbox.annotations.JestId;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* This class is an abstract habit class
* @author Steven Weikai Lu
*/
public abstract class Habit implements Habitable , Parcelable, Saveable {
private String title;
private SimpleDateFormat format;
private Date date;
public abstract String habitType();
private String user;
private String reason;
private int titleLength = 20;
private int reasonLength = 30;
private List<Calendar> calendars;
private List<Date> dates;
private String encodedImage;
@JestId
private String id;
private Bitmap image;
public String getID(){ return id ;}
public void setID(String id){ this.id = id ;}
public Habit(String title) throws HabitFormatException {
this.setTitle(title);
this.setDate(new Date());
}
public Habit(String title, Date date) throws HabitFormatException{
this.setTitle(title);
this.setDate(date);
}
public Habit(String title, Date date, String reason) throws HabitFormatException {
this.setTitle(title);
this.setDate(date);
this.setReason(reason);
}
/**
* This is the main constructor we are using in AddHabitActivity
*
* @see com.example.lit.activity.AddHabitActivity
* @param title Habit name, should be at most 20 char long.
* @param reason Habit Comment, should be at most 30 char long.
* @param date Set by GPS when creating the habit
* @param calendarList Set by user when creating the habit
* @throws HabitFormatException thrown when title longer than 20 char or reason longer than 30 char
* */
public Habit(String title, Date date, String reason, List<Calendar> calendarList) throws HabitFormatException {
this.setTitle(title);
this.setDate(date);
this.setReason(reason);
this.setCalendars(calendarList);
}
public Habit(String title, Date date, String reason, List<Calendar> calendars, Bitmap image)throws HabitFormatException, BitmapTooLargeException{
this.setTitle(title);
this.setDate(date);
this.setReason(reason);
this.setCalendars(calendars);
this.setImage(image);
}
// TODO: Constructor with JestID
public String getTitle() {
return title;
}
public void setTitle(String title) throws HabitFormatException {
if (title.length() > this.titleLength){
throw new HabitFormatException();
}
this.title = title;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public Date getDate() {
return date;
}
/**
* Function takes in a Date object and formats it to dd-MM-yyyy
* @param date
*/
public void setDate(Date date) {
// Format the current time.
SimpleDateFormat format = new SimpleDateFormat ("dd-MM-yyyy");
String dateString = format.format(date);
// Parse the previous string back into a Date.
ParsePosition pos = new ParsePosition(0);
this.date = format.parse(dateString, pos);
}
public String getReason() {
return reason;
}
public void setReason(String reason) throws HabitFormatException {
if (reason.length() < this.reasonLength) {
this.reason = reason;
}
else {
throw new HabitFormatException();
}
}
public List<Calendar> getCalendars() {
return calendars;
}
public void setCalendars(List<Calendar> calendars) {
this.calendars = calendars;
}
public Bitmap getImage() {
if(encodedImage != null) {
byte[] decodedString = Base64.decode(this.encodedImage, Base64.DEFAULT);
this.image = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
}
return this.image;
}
/**
* Function takes in a Bitmap object and decodes it to a 64Base string
* @param image
* @throws BitmapTooLargeException
*/
public void setImage(Bitmap image) throws BitmapTooLargeException {
if (image == null){
this.image = null;
}
else if (image.getByteCount() > 65536){
throw new BitmapTooLargeException();
}
else {
this.image = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] byteArray = baos.toByteArray();
this.encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
//Log.i("encoded",this.encodedImage);
}
}
@Override
public String toString() {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
return "Habit Name: " + this.getTitle() + '\n' +
"Started From: " + format.format(this.getDate());
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.title);
dest.writeSerializable(this.format);
dest.writeLong(this.date != null ? this.date.getTime() : -1);
dest.writeString(this.user);
dest.writeString(this.reason);
dest.writeInt(this.titleLength);
dest.writeInt(this.reasonLength);
dest.writeList(this.calendars);
dest.writeList(this.dates);
dest.writeString(this.encodedImage);
dest.writeString(this.id);
dest.writeParcelable(this.image, flags);
}
protected Habit(Parcel in) {
this.title = in.readString();
this.format = (SimpleDateFormat) in.readSerializable();
long tmpDate = in.readLong();
this.date = tmpDate == -1 ? null : new Date(tmpDate);
this.user = in.readString();
this.reason = in.readString();
this.titleLength = in.readInt();
this.reasonLength = in.readInt();
this.calendars = new ArrayList<Calendar>();
in.readList(this.calendars, Calendar.class.getClassLoader());
this.dates = new ArrayList<Date>();
in.readList(this.dates, Date.class.getClassLoader());
this.encodedImage = in.readString();
this.id = in.readString();
this.image = in.readParcelable(Bitmap.class.getClassLoader());
}
}
| CMPUT301F17T06/Lit | app/src/main/java/com/example/lit/habit/Habit.java | Java | mit | 8,243 |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M2 21.5c0 .28.22.5.49.5h13.02c.27 0 .49-.22.49-.5V20H2v1.5zM15.5 16H11v-2H7v2H2.5c-.28 0-.5.22-.5.5V18h14v-1.5c0-.28-.22-.5-.5-.5zm4.97-.55c.99-1.07 1.53-2.48 1.53-3.94V2h-6v9.47c0 1.48.58 2.92 1.6 4l.4.42V22h4v-2h-2v-4.03l.47-.52zM18 4h2v4h-2V4zm1.03 10.07c-.65-.71-1.03-1.65-1.03-2.6V10h2v1.51c0 .95-.34 1.85-.97 2.56z" />
, 'BrunchDiningOutlined');
| callemall/material-ui | packages/material-ui-icons/src/BrunchDiningOutlined.js | JavaScript | mit | 477 |
# 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::DataMigration::Mgmt::V2018_07_15_preview
module Models
#
# Results for query analysis comparison between the source and target
#
class QueryAnalysisValidationResult
include MsRestAzure
# @return [QueryExecutionResult] List of queries executed and it's
# execution results in source and target
attr_accessor :query_results
# @return [ValidationError] Errors that are part of the execution
attr_accessor :validation_errors
#
# Mapper for QueryAnalysisValidationResult class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'QueryAnalysisValidationResult',
type: {
name: 'Composite',
class_name: 'QueryAnalysisValidationResult',
model_properties: {
query_results: {
client_side_validation: true,
required: false,
serialized_name: 'queryResults',
type: {
name: 'Composite',
class_name: 'QueryExecutionResult'
}
},
validation_errors: {
client_side_validation: true,
required: false,
serialized_name: 'validationErrors',
type: {
name: 'Composite',
class_name: 'ValidationError'
}
}
}
}
}
end
end
end
end
| Azure/azure-sdk-for-ruby | management/azure_mgmt_data_migration/lib/2018-07-15-preview/generated/azure_mgmt_data_migration/models/query_analysis_validation_result.rb | Ruby | mit | 1,785 |
import {MdSnackBar} from '@angular/material';
export abstract class CommonCrudService {
constructor(private snackBar: MdSnackBar) {
}
// todo refactor crud operations to here (use metadata?)
onOperationPerformedNotify(opName: string): (res: boolean) => void {
return (res) => {
let text;
if (res) {
text = `Successful ${opName}!`;
} else {
text = `Failed to ${opName}!`;
}
this.snackBar.open(text, null, {
duration: 1000
});
};
}
}
| Ivanbmstu/angular | src/app/modules/shared/editor/common-crud.service.ts | TypeScript | mit | 514 |
package org.vitrivr.cineast.core.util.audio.pitch.tracking;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import org.vitrivr.cineast.core.util.audio.pitch.Pitch;
/**
* This is a helper class for pitch tracking. It represents a pitch contour, that is, a candidate for a melody fragment. The contour has a fixed length and each slot in the sequence represents a specific timeframe (e.g. belonging to a FFT bin in the underlying STFT).
* <p>
* The intention behind this class is the simplification of comparison between different pitch contours, either on a frame-by-frame basis but also as an entity. In addition to the actual pitch information, the pitch contour class also provides access to pitch contour statistics related to salience and pitch frequency.
*
* @see PitchTracker
*/
public class PitchContour {
/**
* The minimum frequency in Hz on the (artifical) cent-scale.
*/
private static final float CENT_SCALE_MINIMUM = 55.0f;
/**
* Entity that keeps track of salience related contour statistics.
*/
private SummaryStatistics salienceStatistics = new SummaryStatistics();
/**
* Entity that keeps track of frequency related contour statistics.
*/
private SummaryStatistics frequencyStatistics = new SummaryStatistics();
/**
* Sequence of pitches that form the PitchContour.
*/
private final List<Pitch> contour = new LinkedList<>();
/**
* Indicates that the PitchContour statistics require recalculation.
*/
private boolean dirty = true;
/**
* The start frame-index of the pitch-contour. Marks beginning in time.
*/
private int start;
/**
* The end frame-index of the pitch-contour. Marks ending in time.
*/
private int end;
/**
* Constructor for PitchContour.
*
* @param start Start-index of the contour.
* @param pitch Pitch that belongs to the start-index.
*/
public PitchContour(int start, Pitch pitch) {
this.start = start;
this.end = start;
this.contour.add(pitch);
}
/**
* Sets the pitch at the given index if the index is within the bounds of the PitchContour.
*
* @param p Pitch to append.
*/
public void append(Pitch p) {
this.contour.add(p);
this.end += 1;
this.dirty = true;
}
/**
* Sets the pitch at the given index if the index is within the bounds of the PitchContour.
*
* @param p Pitch to append.
*/
public void prepend(Pitch p) {
this.contour.add(0, p);
this.start -= 1;
this.dirty = true;
}
/**
* Returns the pitch at the given index or null, if the index is out of bounds. Note that even if the index is within bounds, the Pitch can still be null.
*
* @param i Index for which to return a pitch.
*/
public Pitch getPitch(int i) {
if (i >= this.start && i <= this.end) {
return this.contour.get(i - this.start);
} else {
return null;
}
}
/**
* Getter for start.
*
* @return Start frame-index.
*/
public final int getStart() {
return start;
}
/**
* Getter for end.
*
* @return End frame-index.
*/
public final int getEnd() {
return end;
}
/**
* Size of the pitch-contour. This number also includes empty slots.
*
* @return Size of the contour.
*/
public final int size() {
return this.contour.size();
}
/**
* Returns the mean of all pitches in the melody.
*
* @return Pitch mean
*/
public final double pitchMean() {
if (this.dirty) {
this.calculate();
}
return this.frequencyStatistics.getMean();
}
/**
* Returns the standard-deviation of all pitches in the melody.
*
* @return Pitch standard deviation
*/
public final double pitchDeviation() {
if (this.dirty) {
this.calculate();
}
return this.frequencyStatistics.getStandardDeviation();
}
/**
* Returns the mean-salience of all pitches in the contour.
*
* @return Salience mean
*/
public final double salienceMean() {
if (this.dirty) {
this.calculate();
}
return this.salienceStatistics.getMean();
}
/**
* Returns the salience standard deviation of all pitches in the contour.
*
* @return Salience standard deviation.
*/
public final double salienceDeviation() {
if (this.dirty) {
this.calculate();
}
return this.salienceStatistics.getStandardDeviation();
}
/**
* Returns the sum of all salience values in the pitch contour.
*/
public final double salienceSum() {
if (this.dirty) {
this.calculate();
}
return this.salienceStatistics.getSum();
}
/**
* Calculates the overlap between the given pitch-contours.
*
* @return Size of the overlap between two pitch-contours.
*/
public final int overlap(PitchContour contour) {
return Math.max(0, Math.min(this.end, contour.end) - Math.max(this.start, contour.start));
}
/**
* Determines if two PitchContours overlap and returns true of false.
*
* @return true, if two PitchContours overlap and falseotherwise.
*/
public final boolean overlaps(PitchContour contour) {
return this.overlap(contour) > 0;
}
/**
* Re-calculates the PitchContour statistics.
*/
private void calculate() {
this.salienceStatistics.clear();
this.frequencyStatistics.clear();
for (Pitch pitch : this.contour) {
if (pitch != null) {
this.salienceStatistics.addValue(pitch.getSalience());
this.frequencyStatistics.addValue(pitch.distanceCents(CENT_SCALE_MINIMUM));
}
}
this.dirty = false;
}
}
| vitrivr/cineast | cineast-core/src/main/java/org/vitrivr/cineast/core/util/audio/pitch/tracking/PitchContour.java | Java | mit | 5,638 |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;
// 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("RapidPliant.App.EarleyDebugger")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RapidPliant.App.EarleyDebugger")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly:ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "RapidPliant.App.EarleyDebugger.Views")]
| bilsaboob/RapidPliant | src/app/RapidPliant.App.EarleyDebugger/Properties/AssemblyInfo.cs | C# | mit | 2,546 |
package com.company;
import java.util.Scanner;
public class EvenPowersOf2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int num = 1;
for (int i = 0; i <= n ; i+=2) {
System.out.println(num);
num *= 4;
}
}
}
| ivelin1936/Studing-SoftUni- | Programing Basic/Programming Basics - Exercises/Advanced Loops/src/com/company/EvenPowersOf2.java | Java | mit | 368 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'Participant'
db.delete_table(u'pa_participant')
# Removing M2M table for field user on 'Participant'
db.delete_table('pa_participant_user')
# Adding M2M table for field user on 'ReportingPeriod'
db.create_table(u'pa_reportingperiod_user', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('reportingperiod', models.ForeignKey(orm[u'pa.reportingperiod'], null=False)),
('user', models.ForeignKey(orm[u'pa.user'], null=False))
))
db.create_unique(u'pa_reportingperiod_user', ['reportingperiod_id', 'user_id'])
def backwards(self, orm):
# Adding model 'Participant'
db.create_table(u'pa_participant', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('reporting_period', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['pa.ReportingPeriod'])),
))
db.send_create_signal(u'pa', ['Participant'])
# Adding M2M table for field user on 'Participant'
db.create_table(u'pa_participant_user', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('participant', models.ForeignKey(orm[u'pa.participant'], null=False)),
('user', models.ForeignKey(orm[u'pa.user'], null=False))
))
db.create_unique(u'pa_participant_user', ['participant_id', 'user_id'])
# Removing M2M table for field user on 'ReportingPeriod'
db.delete_table('pa_reportingperiod_user')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'pa.activity': {
'Meta': {'object_name': 'Activity'},
'category': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['pa.Category']"}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'pa.activityentry': {
'Meta': {'object_name': 'ActivityEntry'},
'activity': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['pa.Activity']"}),
'day': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'hour': ('django.db.models.fields.IntegerField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'slot': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['pa.User']"})
},
u'pa.category': {
'Meta': {'object_name': 'Category'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'grouping': ('django.db.models.fields.CharField', [], {'default': "'d'", 'max_length': '15'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'reporting_period': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['pa.ReportingPeriod']"})
},
u'pa.profession': {
'Meta': {'object_name': 'Profession'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '60'})
},
u'pa.reportingperiod': {
'Meta': {'object_name': 'ReportingPeriod'},
'end_date': ('django.db.models.fields.DateTimeField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '120'}),
'slots_per_hour': ('django.db.models.fields.IntegerField', [], {}),
'start_date': ('django.db.models.fields.DateTimeField', [], {}),
'user': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['pa.User']", 'symmetrical': 'False'})
},
u'pa.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'profession': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['pa.Profession']", 'null': 'True', 'blank': 'True'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
}
}
complete_apps = ['pa'] | Mathew/psychoanalysis | psychoanalysis/apps/pa/migrations/0002_auto__del_participant.py | Python | mit | 7,476 |
# Jrails-ui
module ActionView
module Helpers
module JavaScriptHelper
def hash_to_jquery(hash)
'{'+hash.map { |k,v|
[k,
case v.class.name
when 'String'
"'#{v}'"
when 'Hash'
hash_to_jquery(v)
else
v.to_s
end
].join(':')
}.join(',')+'}'
end
def flash_messages
content_tag(:div, :class => "ui-widget flash") do
flash.map { |type,message|
state = case type
when :notice; 'highlight'
when :error; 'error'
end
icon = case type
when :notice; 'info'
when :error; 'alert'
end
content_tag(:div, content_tag(:span, "", :class => "ui-icon ui-icon-#{icon}", :style => "float: left; margin-right: 0.3em;")+message, :class => "ui-state-#{state} ui-corner-all #{type}", :style => "margin-top: 5px; padding: 0.7em;")
}.join
end
end
def link_to_dialog(*args, &block)
div_id = "dialog#{args[1].gsub(/\//,'_')}"
dialog = {
:modal => true,
:draggable => false,
:resizable => false,
:width => 600
}.merge(args[2][:dialog] || {})
args[2].merge!(
:onclick => "$('##{div_id}').dialog(#{hash_to_jquery(dialog)});return false;"
)
args[2].delete(:dialog)
if block_given?
dialog_html = capture(&block)
else
render_options = args[2][:render] || {}
dialog_html = render(render_options)
end
link_html = link_to(*args)+content_tag(:div, dialog_html, :style => 'display:none;', :id => div_id, :title => args.first)
return block_given? ? concat(link_html) : link_html
end
end
end
end
| jadencarver/jquery_ui | lib/jrails_ui.rb | Ruby | mit | 1,890 |
/*
* Copyright (c) 2020 by Stefan Schubert under the MIT License (MIT).
* See project LICENSE file for the detailed terms and conditions.
*/
package de.bluewhale.sabi.webclient.rest.exceptions;
import de.bluewhale.sabi.exception.ExceptionCode;
import de.bluewhale.sabi.exception.MessageCode;
import de.bluewhale.sabi.exception.TankExceptionCodes;
/**
* MessageCodes that may arise by using the Tank Restservice
*
* @author schubert
*/
public enum TankMessageCodes implements MessageCode {
NO_SUCH_TANK(TankExceptionCodes.TANK_NOT_FOUND_OR_DOES_NOT_BELONG_TO_USER);
// ------------------------------ FIELDS ------------------------------
private TankExceptionCodes exceptionCode;
// --------------------------- CONSTRUCTORS ---------------------------
TankMessageCodes() {
exceptionCode = null;
}
TankMessageCodes(TankExceptionCodes pExceptionCode) {
exceptionCode = pExceptionCode;
}
// --------------------- GETTER / SETTER METHODS ---------------------
@Override
public ExceptionCode getExceptionCode() {
return exceptionCode;
}
}
| StefanSchubert/sabi | sabi-webclient/src/main/java/de/bluewhale/sabi/webclient/rest/exceptions/TankMessageCodes.java | Java | mit | 1,112 |
package okeanos.data.services.entities;
import javax.measure.quantity.Power;
import org.jscience.physics.amount.Amount;
public interface Price {
double getCostAtConsumption(Amount<Power> consumption);
}
| wolfgang-lausenhammer/Okeanos | okeanos.data/src/main/java/okeanos/data/services/entities/Price.java | Java | mit | 207 |
<?php
namespace Shop\MainBundle\Data;
use Doctrine\Common\Persistence\ObjectRepository;
use Shop\MainBundle\Entity\Settings;
/**
* Class ShopSettingsResource
* @package Shop\MainBundle\Data
*/
class ShopSettingsResource {
/**
* @var ObjectRepository
*/
protected $settingsRepository;
/**
* @var Settings|null
*/
protected $settings;
function __construct(ObjectRepository $settingsRepository)
{
$this->settingsRepository = $settingsRepository;
}
/**
* @return null|Settings
*/
public function getSettings()
{
if($this->settings === null){
$this->settings = $this->settingsRepository->findOneBy(array());
if (!$this->settings) {
$this->settings = new Settings();
}
}
return $this->settings;
}
/**
* @param $key
* @return mixed
*/
public function get($key){
return $this->getSettings()->offsetGet($key);
}
} | ja1cap/shop | src/Shop/MainBundle/Data/ShopSettingsResource.php | PHP | mit | 1,014 |
var builder = require("botbuilder");
var botbuilder_azure = require("botbuilder-azure");
const notUtils = require('./notifications-utils.js');
module.exports = [
function (session) {
session.beginDialog('notifications-common-symbol');
},
function (session, results) {
var pair = results.response;
session.dialogData.symbol = pair;
builder.Prompts.number(session, 'How big should the interval be?');
},
function (session, results) {
session.dialogData.interval = results.response;
builder.Prompts.text(session, "What name would you like to give to this notification?");
},
function (session, results) {
var sub = notUtils.getBaseNotification('interval', session.message.address);
sub.symbol = session.dialogData.symbol;
sub.interval = session.dialogData.interval;
sub.previousprice = 0;
sub.isfirstun = true;
sub.name = results.response;
notUtils.createNotification(sub).then((r) => {
session.endDialog('Notification created!');
}).catch((e) => {
session.endDialog('Couldn\'t create notification: ' + e);
});
}
]; | jantielens/CryptoBuddy | messages/dialogs/notifications-add-interval.js | JavaScript | mit | 1,193 |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Terra.WebUI.Models.AccountViewModels
{
public class LoginViewModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
}
| Arukim/terra | Terra.WebUI/Models/AccountViewModels/LoginViewModel.cs | C# | mit | 512 |
version https://git-lfs.github.com/spec/v1
oid sha256:a396601eca15b0c281513d01941cfd37300b927b32a1bb9bb6e708a9910f1b49
size 2712
| yogeshsaroya/new-cdnjs | ajax/libs/ckeditor/4.2/plugins/a11yhelp/dialogs/lang/sr-latn.min.js | JavaScript | mit | 129 |
package com.ruenzuo.weatherapp.adapters;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.ruenzuo.weatherapp.R;
import com.ruenzuo.weatherapp.models.City;
/**
* Created by ruenzuo on 08/05/14.
*/
public class CitiesAdapter extends ArrayAdapter<City> {
private int resourceId;
public CitiesAdapter(Context context, int resource) {
super(context, resource);
resourceId = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = ((Activity)getContext()).getLayoutInflater();
convertView = inflater.inflate(resourceId, null);
}
City country = getItem(position);
TextView txtViewCityName = (TextView) convertView.findViewById(R.id.txtViewCityName);
txtViewCityName.setText(country.getName());
return convertView;
}
} | Ruenzuo/android-facade-example | WeatherApp/src/main/java/com/ruenzuo/weatherapp/adapters/CitiesAdapter.java | Java | mit | 1,106 |
module SelecaoAdmin
class Engine < ::Rails::Engine
isolate_namespace SelecaoAdmin
end
end
| swayzepatryck/selecao_admin | lib/selecao_admin/engine.rb | Ruby | mit | 98 |
<?php
include __DIR__.'/../lib/SALT.php';
/** An example of using the SALT Secure Storage API to store then use a stored Credit Card */
use \SALT\Merchant;
use \SALT\HttpsCreditCardService;
use \SALT\CreditCard;
use \SALT\PaymentProfile;
// connection parameters to the gateway
$url = 'https://test.salt.com/gateway/creditcard/processor.do';
//$merchant = new Merchant ('Your Merchant ID', 'Your API Token');
$merchant = new Merchant ( VALID_MERCHANT_ID, VALID_API_TOKEN );
$service = new HttpsCreditCardService( $merchant, $url );
// credit card info from customer - to be stored
$creditCard = new CreditCard( '4242424242424242', '1010', null, '123 Street', 'A1B23C' );
// payment profile to be stored (just using the card component in this example)
$paymentProfile = new PaymentProfile( $creditCard, null );
// store data under the token 'my-token-001'
//$storageToken = 'my-token-'.date('Ymd');
$storageToken = uniqid();
$storageReceipt = $service->addToStorage( $storageToken, $paymentProfile );
if ( $storageReceipt->approved ) {
echo "Credit card storage approved.\n";
$purchaseOrderId = uniqid();
echo "Creating Single purchase with Order ID $purchaseOrderId\n";
$singlePurchaseReceipt = $service->singlePurchase( $purchaseOrderId, $storageToken, '100', null );
// optional array dump of response params
// print_r($receipt->params);
if ( $singlePurchaseReceipt->approved ) {
//Store the transaction id.
echo "Single Purchase Receipt approved\n";
} else {
echo "Single purchase receipt not approved\n";
}
} else {
echo "Credit card storage not approved.\n";
}
//Update the credit card stored
$updatedCreditCard = new CreditCard ( '4012888888881881', '1010', null, '1 Market St.', '94105' );
$paymentProfile->creditCard = $updatedCreditCard;
$updatedStorageReceipt = $service->updateStorage($storageToken, $paymentProfile);
if ( $updatedStorageReceipt->approved ) {
echo "Updated credit card storage approved.\n";
} else {
echo "Updated credit card storage not approved.\n";
}
//Query the credit card stored
$queryStorageReceipt = $service->queryStorage($storageToken);
if ( $queryStorageReceipt->approved ) {
echo "Secure storage query successful.\n";
echo "Response: \n";
print_r($queryStorageReceipt->params);
} else {
echo "Secure storage query failed.\n";
}
| SaltTechnology/salt-payment-client-php | examples/CreditCardStorage.php | PHP | mit | 2,376 |
package tehnut.resourceful.crops.compat;
import mcp.mobius.waila.api.*;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.items.ItemHandlerHelper;
import tehnut.resourceful.crops.block.tile.TileSeedContainer;
import tehnut.resourceful.crops.core.RegistrarResourcefulCrops;
import tehnut.resourceful.crops.core.data.Seed;
import javax.annotation.Nonnull;
import java.util.List;
@WailaPlugin
public class CompatibilityWaila implements IWailaPlugin {
@Override
public void register(IWailaRegistrar registrar) {
final CropProvider cropProvider = new CropProvider();
registrar.registerStackProvider(cropProvider, TileSeedContainer.class);
registrar.registerNBTProvider(cropProvider, TileSeedContainer.class);
}
public static class CropProvider implements IWailaDataProvider {
@Nonnull
@Override
public ItemStack getWailaStack(IWailaDataAccessor accessor, IWailaConfigHandler config) {
Seed seed = RegistrarResourcefulCrops.SEEDS.getValue(new ResourceLocation(accessor.getNBTData().getString("seed")));
if (seed == null)
return accessor.getStack();
if (seed.isNull())
return accessor.getStack();
if (seed.getOutputs().length == 0)
return accessor.getStack();
return ItemHandlerHelper.copyStackWithSize(seed.getOutputs()[0].getItem(), 1);
}
@Nonnull
@Override
public List<String> getWailaHead(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
return currenttip;
}
@Nonnull
@Override
public List<String> getWailaBody(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
return currenttip;
}
@Nonnull
@Override
public List<String> getWailaTail(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
return currenttip;
}
@Nonnull
@Override
public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, BlockPos pos) {
tag.setString("seed", ((TileSeedContainer) te).getSeedKey().toString());
return tag;
}
}
}
| TehNut/ResourcefulCrops | src/main/java/tehnut/resourceful/crops/compat/CompatibilityWaila.java | Java | mit | 2,650 |
<?php
/*
* This file is part of the WeatherUndergroundBundle.
*
* (c) Nikolay Ivlev <nikolay.kotovsky@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SunCat\WeatherUndergroundBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* DI extension
*
* @author suncat2000 <nikolay.kotovsky@gmail.com>
*/
class WeatherUndergroundExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
$container->setParameter('weather_underground.apikey', $config['apikey']);
$container->setParameter('weather_underground.format', $config['format']);
$container->setParameter('weather_underground.host_data_features', $config['host_data_features']);
$container->setParameter('weather_underground.host_autocomlete', $config['host_autocomlete']);
}
}
| suncat2000/WeatherUndergroundBundle | DependencyInjection/WeatherUndergroundExtension.php | PHP | mit | 1,429 |
import _ from 'lodash';
/**
* Represents a channel with which commands can be invoked.
*
* Channels are one-per-origin (protocol/domain/port).
*/
class Channel {
constructor(config, $rootScope, $timeout, contentWindow) {
this.config = config;
this.$rootScope = $rootScope;
this.$timeout = $timeout;
this._contentWindow = contentWindow;
this.messageCounter = 0;
}
ab2str(buffer) {
let result = "";
let bytes = new Uint8Array(buffer);
let len = bytes.byteLength;
for (let i = 0; i < len; i++) {
result += String.fromCharCode(bytes[i]);
}
return result;
};
/**
* Fire and forget pattern that sends the command to the target without waiting for a response.
*/
invokeDirect(command, data, targetOrigin, transferrablePropertyPath) {
if (!data) {
data = {};
}
if (!targetOrigin) {
targetOrigin = this.config.siteUrl;
}
if (!targetOrigin) {
targetOrigin = "*";
}
data.command = command;
data.postMessageId = `SP.RequestExecutor_${this.messageCounter++}`;
let transferrableProperty = undefined;
if (transferrablePropertyPath) {
transferrableProperty = _.get(data, transferrablePropertyPath);
}
if (transferrableProperty)
this._contentWindow.postMessage(data, targetOrigin, [transferrableProperty]);
else
this._contentWindow.postMessage(data, targetOrigin);
}
/**
* Invokes the specified command on the channel with the specified data, constrained to the specified domain awaiting for max ms specified in timeout
*/
async invoke(command, data, targetOrigin, timeout, transferrablePropertyPath) {
if (!data) {
data = {};
}
if (!targetOrigin) {
targetOrigin = this.config.siteUrl;
}
if (!targetOrigin) {
targetOrigin = "*";
}
if (!timeout) {
timeout = 0;
}
data.command = command;
data.postMessageId = `SP.RequestExecutor_${this.messageCounter++}`;
let resolve, reject;
let promise = new Promise((innerResolve, innerReject) => {
resolve = innerResolve;
reject = innerReject;
});
let timeoutPromise;
if (timeout > 0) {
timeoutPromise = this.$timeout(() => {
reject(new Error(`invoke() timed out while waiting for a response while executing ${data.command}`));
}, timeout);
}
let removeMonitor = this.$rootScope.$on(this.config.crossDomainMessageSink.incomingMessageName, (event, response) => {
if (response.postMessageId !== data.postMessageId)
return;
if (response.result === "error") {
reject(response);
}
else {
if (response.data) {
let contentType = response.headers["content-type"] || response.headers["Content-Type"];
if (contentType.startsWith("application/json")) {
let str = this.ab2str(response.data);
if (str.length > 0) {
try
{
response.data = JSON.parse(str);
}
catch(ex) {
}
}
} else if (contentType.startsWith("text")) {
response.data = this.ab2str(response.data);
}
}
resolve(response);
}
removeMonitor();
if (timeoutPromise)
this.$timeout.cancel(timeoutPromise);
});
let transferrableProperty = undefined;
if (transferrablePropertyPath) {
transferrableProperty = _.get(data, transferrablePropertyPath);
}
if (transferrableProperty)
this._contentWindow.postMessage(data, targetOrigin, [transferrableProperty]);
else
this._contentWindow.postMessage(data, targetOrigin);
return promise;
}
}
module.exports = Channel; | beyond-sharepoint/sp-angular-webpack | src/ng-sharepoint/Channel.js | JavaScript | mit | 4,352 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
include __DIR__.'/../../../application/config/config.php';
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| If this is not set then CodeIgniter will guess the protocol, domain and
| path to your installation.
|
*/
$config['base_url'] = $config['gi_base_url'].'/api/';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'AUTO' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'AUTO' Default - auto detects
| 'PATH_INFO' Uses the PATH_INFO
| 'QUERY_STRING' Uses the QUERY_STRING
| 'REQUEST_URI' Uses the REQUEST_URI
| 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO
|
*/
$config['uri_protocol'] = 'AUTO';
if( defined('__CLI_MODE') && __CLI_MODE === TRUE ) {
$config['uri_protocol'] = 'AUTO';
}
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/core_classes.html
| http://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'GI_';
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify with a regular expression which characters are permitted
| within your URLs. When someone tries to submit a URL with disallowed
| characters they will get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd'; // experimental not currently in use
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| If you have enabled error logging, you can set an error threshold to
| determine what gets logged. Threshold options are:
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ folder. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| system/cache/ folder. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class or the Session class you
| MUST set an encryption key. See the user guide for info.
|
*/
$config['encryption_key'] = 'dfsa09302qdflaskf0-2iq';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_cookie_name' = the name you want for the cookie
| 'sess_expiration' = the number of SECONDS you want the session to last.
| by default sessions last 7200 seconds (two hours). Set to zero for no expiration.
| 'sess_expire_on_close' = Whether to cause the session to expire automatically
| when the browser window is closed
| 'sess_encrypt_cookie' = Whether to encrypt the cookie
| 'sess_use_database' = Whether to save the session data to a database
| 'sess_table_name' = The name of the session database table
| 'sess_match_ip' = Whether to match the user's IP address when reading the session data
| 'sess_match_useragent' = Whether to match the User Agent when reading the session data
| 'sess_time_to_update' = how many seconds between CI refreshing Session Information
|
*/
$config['sess_cookie_name'] = 'gi_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = FALSE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookies will only be set if a secure HTTPS connection exists.
|
*/
$config['cookie_prefix'] = "";
$config['cookie_domain'] = "";
$config['cookie_path'] = "/";
$config['cookie_secure'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
*/
$config['global_xss_filtering'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or 'gmt'. This pref tells the system whether to use
| your server's local time as the master 'now' reference, or convert it to
| GMT. See the 'date helper' page of the user guide for information
| regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
*/
$config['rewrite_short_tags'] = FALSE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy IP
| addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR
| header in order to properly identify the visitor's IP address.
| Comma-delimited, e.g. '10.0.1.200,10.0.1.201'
|
*/
$config['proxy_ips'] = '';
/* End of file config.php */
/* Location: ./application/config/config.php */
| Minds-On-Design-Lab/giving-impact | gi-api/application/config/config.php | PHP | mit | 13,001 |
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
inject,
async,
TestBed,
ComponentFixture
} from '@angular/core/testing';
// Load the implementations that should be tested
import { AppComponent } from './app.component';
import { AppState } from './app.service';
describe(`App`, () => {
});
| Kseniya-Smirnova/study_app | src/app/app.component.spec.ts | TypeScript | mit | 312 |
export function getName(value) {
if (value == 0) {
return "上班";
}
if (value == 1) {
return "下班";
}
throw "invalid route direction";
}
export function getValue(name) {
if (name == "上班") {
return 0;
}
if (name == "下班") {
return 1;
}
throw "invalid route direction";
} | plantain-00/demo-set | js-demo/restful-api-demo/services/routeDirection.ts | TypeScript | mit | 354 |
// config/database.js
module.exports = {
'secret': 'puneetvashisht',
'url' : 'mongodb://localhost/userdb' // looks like mongodb://<user>:<pass>@mongo.onmodulus.net:27017/Mikha4ot
};
| arun2786/tk-mean | database.js | JavaScript | mit | 191 |
import {
LOAD_SEARCH_RESULT_SUCCESS,
CLEAR_SEARCH_RESULTS,
} from 'actions/search';
import { createActionHandlers } from 'utils/reducer/actions-handlers';
const actionHandlers = {};
export function loadSearchResultSuccess(state, searchResultsList) {
return searchResultsList.reduce((acc, result) => {
return {
...acc,
[result.id]: result,
};
}, {});
}
export function clearSearchResult() {
return {};
}
actionHandlers[LOAD_SEARCH_RESULT_SUCCESS] = loadSearchResultSuccess;
actionHandlers[CLEAR_SEARCH_RESULTS] = clearSearchResult;
export default createActionHandlers(actionHandlers);
| InseeFr/Pogues | src/reducers/search-result-by-id.js | JavaScript | mit | 619 |
import { autoinject } from 'aurelia-framework';
import { Customers } from './customers';
import { Router } from 'aurelia-router';
@autoinject()
export class List {
heading = 'Customer management';
customerList = [];
customers: Customers;
router: Router;
constructor(customers: Customers, router: Router) {
this.customers = customers;
this.router = router;
}
gotoCustomer(customer: any) {
this.router.navigateToRoute('edit', {id: customer.id});
}
new() {
this.router.navigateToRoute('create');
}
activate() {
return this.customers.getAll()
.then(customerList => this.customerList = customerList);
}
}
| doktordirk/aurelia-authentication-loopback-sample | client-ts/src/modules/customer/list.ts | TypeScript | mit | 657 |
/**
* Created by huangxinghui on 2016/1/20.
*/
var $ = require('jquery')
var Widget = require('../../widget')
var plugin = require('../../plugin')
var TreeNode = require('./treenode')
var Tree = Widget.extend({
options: {
'labelField': null,
'labelFunction': null,
'childrenField': 'children',
'autoOpen': true
},
events: {
'click li': '_onSelect',
'click i': '_onExpand'
},
_create: function() {
this.$element.addClass('tree')
var that = this
var $ul = $('<ul></ul>')
this._loadFromDataSource()
this.nodes.forEach(function(node) {
that._createNode(node)
$ul.append(node.element)
})
this.$element.append($ul)
},
_onSelect: function(e) {
var $li = $(e.currentTarget),
node = $li.data('node')
e.preventDefault()
if (!$li.hasClass('active')) {
this._setSelectedNode(node)
this._trigger('itemClick', node.data)
}
},
_onExpand: function(e) {
var $li = $(e.currentTarget).closest('li'),
node = $li.data('node')
e.preventDefault()
if (node.isOpen) {
this.collapseNode(node)
}
else {
this.expandNode(node)
}
},
_setSelectedNode: function(node) {
var $active = this.$element.find('.active')
$active.removeClass('active')
var $li = node.element
$li.addClass('active')
this._trigger('change', node.data)
},
_createNode: function(node) {
if (node.isBranch()) {
this._createFolder(node)
}
else {
this._createLeaf(node)
}
},
_createLeaf: function(node) {
var html = ['<li><a href="#"><span>']
html.push(this._createIndentationHtml(node.getLevel()))
html.push(this.itemToLabel(node.data))
html.push('</span></a></li>')
var $li = $(html.join(''))
$li.data('node', node)
node.element = $li
return $li
},
_createFolder: function(node) {
var that = this
var html = []
if (node.isOpen) {
html.push('<li class="open"><a href="#"><span>')
html.push(this._createIndentationHtml(node.getLevel() - 1))
html.push('<i class="glyphicon glyphicon-minus-sign js-folder"></i>')
}
else {
html.push('<li><a href="#"><span>')
html.push(this._createIndentationHtml(node.getLevel() - 1))
html.push('<i class="glyphicon glyphicon-plus-sign js-folder"></i>')
}
html.push(this.itemToLabel(node.data))
html.push('</span></a></li>')
var $li = $(html.join(''))
var $ul = $('<ul class="children-list"></ul>')
node.children.forEach(function(childNode) {
that._createNode(childNode)
$ul.append(childNode.element)
})
$li.append($ul)
$li.data('node', node)
node.element = $li
return $li
},
_createLabel: function(node) {
var html = ['<span>']
var level = node.getLevel()
if (node.isBranch()) {
html.push(this._createIndentationHtml(level - 1))
html.push('<i class="glyphicon ',
node.isOpen ? 'glyphicon-minus-sign' : 'glyphicon-plus-sign',
' js-folder"></i>')
}
else {
html.push(this._createIndentationHtml(level))
}
html.push(this.itemToLabel(node.data))
html.push('</span>')
return html.join('')
},
_createIndentationHtml: function(count) {
var html = []
for (var i = 0; i < count; i++) {
html.push('<i class="glyphicon tree-indentation"></i>')
}
return html.join('')
},
_loadFromDataSource: function() {
var node, children, nodes = [], that = this
if (this.options.dataSource) {
this.options.dataSource.forEach(function(item) {
node = new TreeNode(item)
children = item[that.options.childrenField]
if (children) {
node.isOpen = that.options.autoOpen
that._loadFromArray(children, node)
}
nodes.push(node)
})
}
this.nodes = nodes
},
_loadFromArray: function(array, parentNode) {
var node, children, that = this
array.forEach(function(item) {
node = new TreeNode(item)
parentNode.addChild(node)
children = item[that.childrenField]
if (children) {
node.isOpen = that.autoOpen
that._loadFromArray(children, node)
}
})
},
expandNode: function(node) {
if (!node.isBranch()) {
return
}
var $li = node.element
var $disclosureIcon = $li.children('a').find('.js-folder')
if (!node.isOpen) {
node.isOpen = true
$li.addClass('open')
$disclosureIcon.removeClass('glyphicon-plus-sign').addClass('glyphicon-minus-sign')
this._trigger('itemOpen')
}
},
collapseNode: function(node) {
if (!node.isBranch()) {
return
}
var $li = node.element
var $disclosureIcon = $li.children('a').find('.js-folder')
if (node.isOpen) {
node.isOpen = false
$li.removeClass('open')
$disclosureIcon.removeClass('glyphicon-minus-sign').addClass('glyphicon-plus-sign')
this._trigger('itemClose')
}
},
expandAll: function() {
var that = this
this.nodes.forEach(function(node) {
that.expandNode(node)
})
},
collapseAll: function() {
var that = this
this.nodes.forEach(function(node) {
that.collapseNode(node)
})
},
append: function(item, parentNode) {
var $ul, $li, $prev, node = new TreeNode(item)
if (parentNode.isBranch()) {
parentNode.addChild(node)
$ul = parentNode.element.children('ul')
this._createNode(node)
$li = node.element
$ul.append($li)
}
else {
parentNode.addChild(node)
$li = parentNode.element
$prev = $li.prev()
$ul = $li.parent()
parentNode.element = null
$li.remove()
$li = this._createFolder(parentNode)
if ($prev.length) {
$prev.after($li)
}
else {
$ul.append($li)
}
}
this.expandNode(parentNode)
this._setSelectedNode(node)
},
remove: function(node) {
var parentNode = node.parent
node.element.remove()
node.destroy()
this._setSelectedNode(parentNode)
},
update: function(node) {
var $li = node.element
$li.children('a').html(this._createLabel(node))
},
getSelectedNode: function() {
var $li = this.$element.find('.active')
return $li.data('node')
},
getSelectedItem: function() {
var node = this.getSelectedNode()
return node.data
},
itemToLabel: function(data) {
if (!data) {
return ''
}
if (this.options.labelFunction != null) {
return this.options.labelFunction(data)
}
else if (this.options.labelField != null) {
return data[this.options.labelField]
}
else {
return data
}
}
})
plugin('tree', Tree)
| huang-x-h/Bean.js | src/components/tree/index.js | JavaScript | mit | 6,725 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Advent of Code 2015 from http://adventofcode.com/2015/day/5
Author: James Walker
Copyrighted 2017 under the MIT license:
http://www.opensource.org/licenses/mit-license.php
Execution:
python advent_of_code_2015_day_05.py
--- Day 5: Doesn't He Have Intern-Elves For This? ---
Santa needs help figuring out which strings in his text file are naughty or
nice.
A nice string is one with all of the following properties:
It contains at least three vowels (aeiou only), like aei, xazegov, or
aeiouaeiouaeiou.
It contains at least one letter that appears twice in a row, like xx,
abcdde (dd), or aabbccdd (aa, bb, cc, or dd).
It does not contain the strings ab, cd, pq, or xy, even if they are part of
one of the other requirements.
For example:
ugknbfddgicrmopn is nice because it has at least three vowels
(u...i...o...), a double letter (...dd...), and none of the disallowed
substrings.
aaa is nice because it has at least three vowels and a double letter, even
though the letters used by different rules overlap.
jchzalrnumimnmhp is naughty because it has no double letter.
haegwjzuvuyypxyu is naughty because it contains the string xy.
dvszwmarrgswjxmb is naughty because it contains only one vowel.
How many strings are nice?
Answer: 258
--- Day 5: Part Two ---
Realizing the error of his ways, Santa has switched to a better model of
determining whether a string is naughty or nice. None of the old rules apply,
as they are all clearly ridiculous. Now, a nice string is one with all of the
following properties:
It contains a pair of any two letters that appears at least twice in the
string without overlapping, like xyxy (xy) or aabcdefgaa (aa), but not
like aaa (aa, but it overlaps).
It contains at least one letter which repeats with exactly one letter
between them, like xyx, abcdefeghi (efe), or even aaa.
For example:
qjhvhtzxzqqjkmpb is nice because is has a pair that appears twice (qj) and
a letter that repeats with exactly one letter between them (zxz).
xxyxx is nice because it has a pair that appears twice and a letter that
repeats with one between, even though the letters used by each rule
overlap.
uurcxstgmygtbstg is naughty because it has a pair (tg) but no repeat with a
single letter between them.
ieodomkazucvgmuy is naughty because it has a repeating letter with one
between (odo), but no pair that appears twice.
How many strings are nice under these new rules?
Answer: 53
"""
import collections
import os
import re
import sys
TestCase = collections.namedtuple('TestCase', 'input expected1 expected2')
class Advent_Of_Code_2015_Solver_Day05(object):
"""Advent of Code 2015 Day 5: Doesn't He Have Intern-Elves For This?"""
def __init__(self, file_name=None):
self._file_name = file_name
self._puzzle_input = None
self._solved_output = (
"The text file had {0} nice strings using the original rules\n"
"and it had {1} nice strings using the new rules."
)
self.__regex_vowels = re.compile('[aeiou]')
self.__regex_double_char = re.compile('(\w)\\1+')
self.__regex_naughty = re.compile('ab|cd|pq|xy')
self.__regex_double_pair = re.compile('(\w{2})\w*\\1')
self.__regex_triplet = re.compile('(\w)\w\\1')
def _load_puzzle_file(self):
filePath = "{dir}/{f}".format(dir=os.getcwd(), f=self._file_name)
try:
with open(filePath, mode='r') as puzzle_file:
self._puzzle_input = puzzle_file.readlines()
except IOError as err:
errorMsg = (
"ERROR: Failed to read the puzzle input from file '{file}'\n"
"{error}"
)
print(errorMsg.format(file=self._file_name, error=err))
exit(1)
def __is_nice_string_using_old_rules(self, string):
return (self.__regex_naughty.search(string) is None
and len(self.__regex_vowels.findall(string)) > 2
and self.__regex_double_char.search(string))
def __is_nice_string_using_new_rules(self, string):
return (self.__regex_double_pair.search(string)
and self.__regex_triplet.search(string))
def _solve_puzzle_parts(self):
old_nice_count = 0
new_nice_count = 0
for string in self._puzzle_input:
if not string:
continue
if self.__is_nice_string_using_old_rules(string):
old_nice_count += 1
if self.__is_nice_string_using_new_rules(string):
new_nice_count += 1
return (old_nice_count, new_nice_count)
def get_puzzle_solution(self, alt_input=None):
if alt_input is None:
self._load_puzzle_file()
else:
self._puzzle_input = alt_input
old_nice_count, new_nice_count = self._solve_puzzle_parts()
return self._solved_output.format(old_nice_count, new_nice_count)
def _run_test_case(self, test_case):
correct_output = self._solved_output.format(
test_case.expected1,
test_case.expected2
)
test_output = self.get_puzzle_solution(test_case.input)
if correct_output == test_output:
print("Test passed for input '{0}'".format(test_case.input))
else:
print("Test failed for input '{0}'".format(test_case.input))
print(test_output)
def run_test_cases(self):
print("No Puzzle Input for {puzzle}".format(puzzle=self.__doc__))
print("Running Test Cases...")
self._run_test_case(TestCase(['ugknbfddgicrmopn'], 1, 0))
self._run_test_case(TestCase(['aaa'], 1, 0))
self._run_test_case(TestCase(['jchzalrnumimnmhp'], 0, 0))
self._run_test_case(TestCase(['haegwjzuvuyypxyu'], 0, 0))
self._run_test_case(TestCase(['dvszwmarrgswjxmb'], 0, 0))
self._run_test_case(TestCase(['xyxy'], 0, 1))
self._run_test_case(TestCase(['aabcdefgaa'], 0, 0))
self._run_test_case(TestCase(['qjhvhtzxzqqjkmpb'], 0, 1))
self._run_test_case(TestCase(['xxyxx'], 0, 1))
self._run_test_case(TestCase(['uurcxstgmygtbstg'], 0, 0))
self._run_test_case(TestCase(['ieodomkazucvgmuy'], 0, 0))
self._run_test_case(TestCase(['aaccacc'], 1, 1))
if __name__ == '__main__':
try:
day05_solver = Advent_Of_Code_2015_Solver_Day05(sys.argv[1])
print(day05_solver.__doc__)
print(day05_solver.get_puzzle_solution())
except IndexError:
Advent_Of_Code_2015_Solver_Day05().run_test_cases()
| JDSWalker/AdventOfCode | 2015/Day05/advent_of_code_2015_day_05.py | Python | mit | 6,750 |
/**
* Test program.
*
* Copyright (c) 2015 Alex Jin (toalexjin@hotmail.com)
*/
#include "test/test.h"
#include <iostream>
namespace {
void help() {
std::cout << "Usage: testalgo -a" << std::endl;
std::cout << " testalgo <test-case-name>" << std::endl;
std::cout << std::endl;
std::cout << "Options:" << std::endl;
std::cout << " -a Run all test cases" << std::endl;
std::cout << std::endl;
std::cout << "Test Case Names:" << std::endl;
const auto names = test_manager_t::instance().get_names();
for (auto it = names.begin(); it != names.end(); ++it) {
std::cout << " " << *it << std::endl;
}
std::cout << std::endl;
}
} // unnamed namespace
int main(int argc, char* argv[]) {
if (argc != 2) {
help();
exit(1);
}
bool result = false;
std::string arg1 = argv[1];
if (arg1 == "-a") {
result = test_manager_t::instance().run();
}
else {
result = test_manager_t::instance().run(arg1);
}
return result ? 0 : 2;
}
| toalexjin/algo | test/main.cpp | C++ | mit | 974 |
function solve(args) {
function biSearch(array, searchedNumber, start, end) {
for (var i = start; i <= end; i += 1) {
if (+array[i] === searchedNumber) {
return i;
}
}
return -1;
}
var data = args[0].split('\n'),
numberN = +data.shift(),
numberX = +data.pop();
var firstIndex = 0;
var lastIndex = data.length - 1;
var resultIndex = 0;
var middle = 0;
for (var j = firstIndex; j < lastIndex; j += 1) {
middle = (lastIndex / 2) | 0;
if (+data[middle] === numberX) {
resultIndex = middle;
break;
}
if (+data[middle] < numberX) {
firstIndex = middle;
resultIndex = biSearch(data, numberX, firstIndex, lastIndex);
}
if (+data[middle] > numberX) {
lastIndex = middle;
resultIndex = biSearch(data, numberX, firstIndex, lastIndex);
}
}
if (resultIndex >= 0 && resultIndex < data.length) {
console.log(resultIndex);
} else {
console.log('-1');
}
} | jorosoft/Telerik-Academy | Homeworks/JS Fundamentals/07. Arrays/07. Binary search/binary-search.js | JavaScript | mit | 1,110 |
#!/usr/bin/env node
var pluginlist = [
];
var exec = require('child_process').exec;
function puts(error, stdout, stderr) {
console.log(stdout);
}
pluginlist.forEach(function(plug) {
exec("cordova plugin add " + plug, puts);
});
| ozsay/ionic-brackets | templates/plugins_hook.js | JavaScript | mit | 240 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.text;
import java.util.Map;
public abstract class StrLookup<V> {
public static StrLookup<?> noneLookup() {
return null;
}
public static StrLookup<String> systemPropertiesLookup() {
return null;
}
public static <V> StrLookup<V> mapLookup(final Map<String, V> map) {
return null;
}
public abstract String lookup(String key);
}
| github/codeql | java/ql/test/stubs/apache-commons-lang3-3.7/org/apache/commons/lang3/text/StrLookup.java | Java | mit | 1,213 |
const path = require('path');
require('dotenv').config();
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const { AureliaPlugin } = require('aurelia-webpack-plugin');
const { optimize: { CommonsChunkPlugin }, ProvidePlugin } = require('webpack')
const { TsConfigPathsPlugin, CheckerPlugin } = require('awesome-typescript-loader');
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
// config helpers:
const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || []
const when = (condition, config, negativeConfig) =>
condition ? ensureArray(config) : ensureArray(negativeConfig)
// primary config:
const title = 'TechRadar';
const outDir = path.resolve(__dirname, 'dist');
const srcDir = path.resolve(__dirname, 'src');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const baseUrl = '/';
const cssRules = [
{ loader: 'css-loader' },
{
loader: 'postcss-loader',
options: { plugins: () => [require('autoprefixer')({ browsers: ['last 2 versions'] })] }
}
]
module.exports = ({ production, server, extractCss, coverage } = {}) => ({
resolve: {
extensions: ['.ts', '.js'],
modules: [srcDir, 'node_modules'],
alias: {
'aurelia-binding$': path.resolve(__dirname, 'node_modules/aurelia-binding/dist/amd/aurelia-binding.js')
}
},
entry: {
app: ['./src/main']
},
output: {
path: outDir,
publicPath: baseUrl,
filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js',
sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map',
chunkFilename: production ? '[chunkhash].chunk.js' : '[hash].chunk.js',
},
devServer: {
contentBase: baseUrl,
},
module: {
rules: [
// CSS required in JS/TS files should use the style-loader that auto-injects it into the website
// only when the issuer is a .js/.ts file, so the loaders are not applied inside html templates
{
test: /\.css$/i,
issuer: [{ not: [{ test: /\.html$/i }] }],
use: extractCss ? ExtractTextPlugin.extract({
fallback: 'style-loader',
use: cssRules,
}) : ['style-loader', ...cssRules],
},
{
test: /\.css$/i,
issuer: [{ test: /\.html$/i }],
// CSS required in templates cannot be extracted safely
// because Aurelia would try to require it again in runtime
use: cssRules,
},
{ test: /\.html$/i, loader: 'html-loader' },
{ test: /\.ts$/i, loader: 'awesome-typescript-loader', exclude: nodeModulesDir },
{ test: /\.json$/i, loader: 'json-loader' },
// use Bluebird as the global Promise implementation:
{ test: /[\/\\]node_modules[\/\\]bluebird[\/\\].+\.js$/, loader: 'expose-loader?Promise' },
// exposes jQuery globally as $ and as jQuery:
{ test: require.resolve('jquery'), loader: 'expose-loader?$!expose-loader?jQuery' },
// embed small images and fonts as Data Urls and larger ones as files:
{ test: /\.(png|gif|jpg|cur)$/i, loader: 'url-loader', options: { limit: 8192 } },
{ test: /\.woff2(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff2' } },
{ test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } },
// load these fonts normally, as files:
{ test: /\.(ttf|eot|svg|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'file-loader' },
...when(coverage, {
test: /\.[jt]s$/i, loader: 'istanbul-instrumenter-loader',
include: srcDir, exclude: [/\.{spec,test}\.[jt]s$/i],
enforce: 'post', options: { esModules: true },
})
]
},
plugins: [
new BrowserSyncPlugin({
// browse to http://localhost:3000/ during development,
// ./public directory is being served
host: 'localhost',
port: 3000,
server: { baseDir: ['dist'] }
}),
new AureliaPlugin(),
new ProvidePlugin({
'Promise': 'bluebird',
'$': 'jquery',
'jQuery': 'jquery',
'window.jQuery': 'jquery',
}),
new TsConfigPathsPlugin(),
new CheckerPlugin(),
new HtmlWebpackPlugin({
template: 'index.ejs',
minify: production ? {
removeComments: true,
collapseWhitespace: true
} : undefined,
metadata: {
// available in index.ejs //
title, server, baseUrl
},
}),
// new UglifyJSPlugin(),
new CopyWebpackPlugin([
{ from: 'static/favicon.ico', to: 'favicon.ico' }
,{ from: './../tr-host/projects', to: 'projects' }
,{ from: 'img', to: 'img' }
]),
...when(extractCss, new ExtractTextPlugin({
filename: production ? '[contenthash].css' : '[id].css',
allChunks: true,
})),
...when(production, new CommonsChunkPlugin({
name: ['vendor']
})),
...when(production, new CopyWebpackPlugin([
{ from: 'static/favicon.ico', to: 'favicon.ico' }
]))
// ,
// new BundleAnalyzerPlugin({
// // Can be `server`, `static` or `disabled`.
// // In `server` mode analyzer will start HTTP server to show bundle report.
// // In `static` mode single HTML file with bundle report will be generated.
// // In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting `generateStatsFile` to `true`.
// analyzerMode: 'static',
// // Host that will be used in `server` mode to start HTTP server.
// analyzerHost: '127.0.0.1',
// // Port that will be used in `server` mode to start HTTP server.
// analyzerPort: 8888,
// // Path to bundle report file that will be generated in `static` mode.
// // Relative to bundles output directory.
// reportFilename: 'report.html',
// // Module sizes to show in report by default.
// // Should be one of `stat`, `parsed` or `gzip`.
// // See "Definitions" section for more information.
// defaultSizes: 'parsed',
// // Automatically open report in default browser
// openAnalyzer: false,
// // If `true`, Webpack Stats JSON file will be generated in bundles output directory
// generateStatsFile: false,
// // Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
// // Relative to bundles output directory.
// statsFilename: 'stats.json',
// // Options for `stats.toJson()` method.
// // For example you can exclude sources of your modules from stats file with `source: false` option.
// // See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
// statsOptions: null,
// // Log level. Can be 'info', 'warn', 'error' or 'silent'.
// logLevel: 'info'
// })
],
})
| Make-IT-TR/TechRadar | tr-app/webpack.config.js | JavaScript | mit | 7,154 |
#!/bin/env/python
# coding: utf-8
import logging
import os
import time
import uuid
from logging import Formatter
from logging.handlers import RotatingFileHandler
from multiprocessing import Queue
from time import strftime
import dill
from .commands import *
from .processing import MultiprocessingLogger
class TaskProgress(object):
"""
Holds both data and graphics-related information for a task's progress bar.
The logger will iterate over TaskProgress objects to draw progress bars on screen.
"""
def __init__(self,
total,
prefix='',
suffix='',
decimals=0,
bar_length=60,
keep_alive=False,
display_time=False):
"""
Creates a new progress bar using the given information.
:param total: The total number of iteration for this progress bar.
:param prefix: [Optional] The text that should be displayed at the left side of the
progress bar. Note that progress bars will always stay left-aligned at the
shortest possible.
:param suffix: [Optional] The text that should be displayed at the very right side of the
progress bar.
:param decimals: [Optional] The number of decimals to display for the percentage.
:param bar_length: [Optional] The graphical bar size displayed on screen. Unit is character.
:param keep_alive: [Optional] Specify whether the progress bar should stay displayed forever
once completed or if it should vanish.
:param display_time: [Optional] Specify whether the duration since the progress has begun should
be displayed. Running time will be displayed between parenthesis, whereas it
will be displayed between brackets when the progress has completed.
"""
super(TaskProgress, self).__init__()
self.progress = 0
# Minimum number of seconds at maximum completion before a progress bar is removed from display
# The progress bar may vanish at a further time as the redraw rate depends upon chrono AND method calls
self.timeout_chrono = None
self.begin_time = None
self.end_time = None
self.elapsed_time_at_end = None
# Graphics related information
self.keep_alive = keep_alive
self.display_time = display_time
self.total = total
self.prefix = prefix
self.suffix = suffix
self.decimals = decimals
self.bar_length = bar_length
def set_progress(self, progress):
"""
Defines the current progress for this progress bar in iteration units (not percent).
:param progress: Current progress in iteration units regarding its total (not percent).
:return: True if the progress has changed. If the given progress is higher than the total or lower
than 0 then it will be ignored.
"""
_progress = progress
if _progress > self.total:
_progress = self.total
elif _progress < 0:
_progress = 0
# Stop task chrono if needed
if _progress == self.total and self.display_time:
self.end_time = time.time() * 1000
# If the task has completed instantly then define its begin_time too
if not self.begin_time:
self.begin_time = self.end_time
has_changed = self.progress != _progress
if has_changed:
self.progress = _progress
return has_changed
class FancyLogger(object):
"""
Defines a multiprocess logger object. Logger uses a redraw rate because of console flickering. That means it will
not draw new messages or progress at the very time they are being logged but their timestamp will be captured at the
right time. Logger will redraw at a given time period AND when new messages or progress are logged.
If you still want to force redraw immediately (may produce flickering) then call 'flush' method.
Logger uses one file handler and then uses standard output (stdout) to draw on screen.
"""
queue = None
"Handles all messages and progress to be sent to the logger process."
default_message_number = 20
"Default value for the logger configuration."
default_exception_number = 5
"Default value for the logger configuration."
default_permanent_progressbar_slots = 0
"Default value for the logger configuration."
default_redraw_frequency_millis = 500
"Default value for the logger configuration."
default_level = logging.INFO
"Default value for the logger configuration."
default_task_millis_to_removal = 500
"Default value for the logger configuration."
default_console_format_strftime = '%d %B %Y %H:%M:%S'
"Default value for the logger configuration."
default_console_format = '{T} [{L}]'
"Default value for the logger configuration."
default_file_handlers = []
"Default value for the logger configuration. Filled in constructor."
def __init__(self,
message_number=default_message_number,
exception_number=default_exception_number,
permanent_progressbar_slots=default_permanent_progressbar_slots,
redraw_frequency_millis=default_redraw_frequency_millis,
console_level=default_level,
task_millis_to_removal=default_task_millis_to_removal,
console_format_strftime=default_console_format_strftime,
console_format=default_console_format,
file_handlers=None,
application_name=None):
"""
Initializes a new logger and starts its process immediately using given configuration.
:param message_number: [Optional] Number of simultaneously displayed messages below progress bars.
:param exception_number: [Optional] Number of simultaneously displayed exceptions below messages.
:param permanent_progressbar_slots: [Optional] The amount of vertical space (bar slots) to keep at all times,
so the message logger will not move anymore if the bar number is equal or
lower than this parameter.
:param redraw_frequency_millis: [Optional] Minimum time lapse in milliseconds between two redraws. It may be
more because the redraw rate depends upon time AND method calls.
:param console_level: [Optional] The logging level (from standard logging module).
:param task_millis_to_removal: [Optional] Minimum time lapse in milliseconds at maximum completion before
a progress bar is removed from display. The progress bar may vanish at a
further time as the redraw rate depends upon time AND method calls.
:param console_format_strftime: [Optional] Specify the time format for console log lines using python
strftime format. Defaults to format: '29 november 2016 21:52:12'.
:param console_format: [Optional] Specify the format of the console log lines. There are two
variables available: {T} for timestamp, {L} for level. Will then add some
tabulations in order to align text beginning for all levels.
Defaults to format: '{T} [{L}]'
Which will produce: '29 november 2016 21:52:12 [INFO] my log text'
'29 november 2016 21:52:13 [WARNING] my log text'
'29 november 2016 21:52:14 [DEBUG] my log text'
:param file_handlers: [Optional] Specify the file handlers to use. Each file handler will use its
own regular formatter and level. Console logging is distinct from file
logging. Console logging uses custom stdout formatting, while file logging
uses regular python logging rules. All handlers are permitted except
StreamHandler if used with stdout or stderr which are reserved by this
library for custom console output.
:param application_name: [Optional] Used only if 'file_handlers' parameter is ignored. Specifies the
application name to use to format the default file logger using format:
application_%Y-%m-%d_%H-%M-%S.log
"""
super(FancyLogger, self).__init__()
# Define default file handlers
if not file_handlers:
if not application_name:
app_name = 'application'
else:
app_name = application_name
handler = RotatingFileHandler(filename=os.path.join(os.getcwd(), '{}_{}.log'
.format(app_name, strftime('%Y-%m-%d_%H-%M-%S'))),
encoding='utf8',
maxBytes=5242880, # 5 MB
backupCount=10,
delay=True)
handler.setLevel(logging.INFO)
handler.setFormatter(fmt=Formatter(fmt='%(asctime)s [%(levelname)s]\t%(message)s',
datefmt=self.default_console_format_strftime))
self.default_file_handlers.append(handler)
file_handlers = self.default_file_handlers
if not self.queue:
self.queue = Queue()
self.process = MultiprocessingLogger(queue=self.queue,
console_level=console_level,
message_number=message_number,
exception_number=exception_number,
permanent_progressbar_slots=permanent_progressbar_slots,
redraw_frequency_millis=redraw_frequency_millis,
task_millis_to_removal=task_millis_to_removal,
console_format_strftime=console_format_strftime,
console_format=console_format,
file_handlers=file_handlers)
self.process.start()
def flush(self):
"""
Flushes the remaining messages and progress bars state by forcing redraw. Can be useful if you want to be sure
that a message or progress has been updated in display at a given moment in code, like when you are exiting an
application or doing some kind of synchronized operations.
"""
self.queue.put(dill.dumps(FlushCommand()))
def terminate(self):
"""
Tells the logger process to exit immediately. If you do not call 'flush' method before, you may lose some
messages of progresses that have not been displayed yet. This method blocks until logger process has stopped.
"""
self.queue.put(dill.dumps(ExitCommand()))
if self.process:
self.process.join()
def set_configuration(self,
message_number=default_message_number,
exception_number=default_exception_number,
permanent_progressbar_slots=default_permanent_progressbar_slots,
redraw_frequency_millis=default_redraw_frequency_millis,
console_level=default_level,
task_millis_to_removal=default_task_millis_to_removal,
console_format_strftime=default_console_format_strftime,
console_format=default_console_format,
file_handlers=default_file_handlers):
"""
Defines the current configuration of the logger. Can be used at any moment during runtime to modify the logger
behavior.
:param message_number: [Optional] Number of simultaneously displayed messages below progress bars.
:param exception_number: [Optional] Number of simultaneously displayed exceptions below messages.
:param permanent_progressbar_slots: [Optional] The amount of vertical space (bar slots) to keep at all times,
so the message logger will not move anymore if the bar number is equal or
lower than this parameter.
:param redraw_frequency_millis: [Optional] Minimum time lapse in milliseconds between two redraws. It may be
more because the redraw rate depends upon time AND method calls.
:param console_level: [Optional] The logging level (from standard logging module).
:param task_millis_to_removal: [Optional] Minimum time lapse in milliseconds at maximum completion before
a progress bar is removed from display. The progress bar may vanish at a
further time as the redraw rate depends upon time AND method calls.
:param console_format_strftime: [Optional] Specify the time format for console log lines using python
strftime format. Defaults to format: '29 november 2016 21:52:12'.
:param console_format: [Optional] Specify the format of the console log lines. There are two
variables available: {T} for timestamp, {L} for level. Will then add some
tabulations in order to align text beginning for all levels.
Defaults to format: '{T} [{L}]'
Which will produce: '29 november 2016 21:52:12 [INFO] my log text'
'29 november 2016 21:52:13 [WARNING] my log text'
'29 november 2016 21:52:14 [DEBUG] my log text'
:param file_handlers: [Optional] Specify the file handlers to use. Each file handler will use its
own regular formatter and level. Console logging is distinct from file
logging. Console logging uses custom stdout formatting, while file logging
uses regular python logging rules. All handlers are permitted except
StreamHandler if used with stdout or stderr which are reserved by this
library for custom console output.
"""
self.queue.put(dill.dumps(SetConfigurationCommand(task_millis_to_removal=task_millis_to_removal,
console_level=console_level,
permanent_progressbar_slots=permanent_progressbar_slots,
message_number=message_number,
exception_number=exception_number,
redraw_frequency_millis=redraw_frequency_millis,
console_format_strftime=console_format_strftime,
console_format=console_format,
file_handlers=file_handlers)))
def set_level(self,
level,
console_only=False):
"""
Defines the logging level (from standard logging module) for log messages.
:param level: Level of logging for the file logger.
:param console_only: [Optional] If True then the file logger will not be affected.
"""
self.queue.put(dill.dumps(SetLevelCommand(level=level,
console_only=console_only)))
def set_task_object(self,
task_id,
task_progress_object):
"""
Defines a new progress bar with the given information using a TaskProgress object.
:param task_id: Unique identifier for this progress bar. Will erase if already existing.
:param task_progress_object: TaskProgress object holding the progress bar information.
"""
self.set_task(task_id=task_id,
total=task_progress_object.total,
prefix=task_progress_object.prefix,
suffix=task_progress_object.suffix,
decimals=task_progress_object.decimals,
bar_length=task_progress_object.bar_length,
keep_alive=task_progress_object.keep_alive,
display_time=task_progress_object.display_time)
def set_task(self,
task_id,
total,
prefix,
suffix='',
decimals=0,
bar_length=60,
keep_alive=False,
display_time=False):
"""
Defines a new progress bar with the given information.
:param task_id: Unique identifier for this progress bar. Will erase if already existing.
:param total: The total number of iteration for this progress bar.
:param prefix: The text that should be displayed at the left side of the progress bar. Note that
progress bars will always stay left-aligned at the shortest possible.
:param suffix: [Optional] The text that should be displayed at the very right side of the progress bar.
:param decimals: [Optional] The number of decimals to display for the percentage.
:param bar_length: [Optional] The graphical bar size displayed on screen. Unit is character.
:param keep_alive: [Optional] Specify whether the progress bar should stay displayed forever once completed
or if it should vanish.
:param display_time: [Optional] Specify whether the duration since the progress has begun should be
displayed. Running time will be displayed between parenthesis, whereas it will be
displayed between brackets when the progress has completed.
"""
self.queue.put(dill.dumps(NewTaskCommand(task_id=task_id,
task=TaskProgress(total,
prefix,
suffix,
decimals,
bar_length,
keep_alive,
display_time))))
def update(self,
task_id,
progress):
"""
Defines the current progress for this progress bar id in iteration units (not percent).
If the given id does not exist or the given progress is identical to the current, then does nothing.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param task_id: Unique identifier for this progress bar. Will erase if already existing.
:param progress: Current progress in iteration units regarding its total (not percent).
"""
self.queue.put(dill.dumps(UpdateProgressCommand(task_id=task_id,
progress=progress)))
def debug(self, text):
"""
Posts a debug message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param text: The text to log into file and console.
"""
self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.DEBUG)))
def info(self, text):
"""
Posts an info message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param text: The text to log into file and console.
"""
self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.INFO)))
def warning(self, text):
"""
Posts a warning message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param text: The text to log into file and console.
"""
self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.WARNING)))
def error(self, text):
"""
Posts an error message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param text: The text to log into file and console.
"""
self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.ERROR)))
def critical(self, text):
"""
Posts a critical message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param text: The text to log into file and console.
"""
self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.CRITICAL)))
def throw(self, stacktrace, process_title=None):
"""
Sends an exception to the logger so it can display it as a special message. Prevents console refresh cycles from
hiding exceptions that could be thrown by processes.
:param stacktrace: Stacktrace string as returned by 'traceback.format_exc()' in an 'except' block.
:param process_title: [Optional] Define the current process title to display into the logger for this
exception.
"""
self.queue.put(dill.dumps(StacktraceCommand(pid=os.getpid(),
stacktrace=stacktrace,
process_title=process_title)))
# --------------------------------------------------------------------
# Iterator implementation
def progress(self,
enumerable,
task_progress_object=None):
"""
Enables the object to be used as an iterator. Each iteration will produce a progress update in the logger.
:param enumerable: Collection to iterate over.
:param task_progress_object: [Optional] TaskProgress object holding the progress bar information.
:return: The logger instance.
"""
self.list = enumerable
self.list_length = len(enumerable)
self.task_id = uuid.uuid4()
self.index = 0
if task_progress_object:
# Force total attribute
task_progress_object.total = self.list_length
else:
task_progress_object = TaskProgress(total=self.list_length,
display_time=True,
prefix='Progress')
# Create a task progress
self.set_task_object(task_id=self.task_id,
task_progress_object=task_progress_object)
return self
def __iter__(self):
"""
Enables the object to be used as an iterator. Each iteration will produce a progress update in the logger.
:return: The logger instance.
"""
return self
def __next__(self):
"""
Enables the object to be used as an iterator. Each iteration will produce a progress update in the logger.
:return: The current object of the iterator.
"""
if self.index >= self.list_length:
raise StopIteration
else:
self.index += 1
self.update(task_id=self.task_id,
progress=self.index)
return self.list[self.index - 1]
# ---------------------------------------------------------------------
| peepall/FancyLogger | FancyLogger/__init__.py | Python | mit | 27,844 |
package com.rebuy.consul;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.NewService;
import com.ecwid.consul.v1.catalog.model.CatalogService;
import com.rebuy.consul.exceptions.NoServiceFoundException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ConsulServiceTest
{
private ConsulClient clientMock;
private ConsulService service;
private NewService serviceMock;
@Before
public void before()
{
clientMock = mock(ConsulClient.class);
serviceMock = mock(NewService.class);
when(serviceMock.getId()).thenReturn("42");
service = new ConsulService(clientMock, serviceMock);
}
@Test
public void register_should_invoke_client()
{
when(clientMock.agentServiceRegister(Mockito.any())).thenReturn(null);
service.register();
Mockito.verify(clientMock).agentServiceRegister(serviceMock);
}
@Test
public void unregister_should_invoke_client()
{
service.unregister();
Mockito.verify(clientMock).agentServiceSetMaintenance("42", true);
}
@Test(expected = NoServiceFoundException.class)
public void findService_should_throw_exception_if_no_services_are_found()
{
Response<List<CatalogService>> response = new Response<>(new ArrayList<>(), 1L, true, 1L);
when(clientMock.getCatalogService(Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response);
service.getRandomService("service");
Mockito.verify(clientMock).getCatalogService("service", Mockito.any(QueryParams.class));
}
@Test
public void findService_should_invoke_client()
{
List<CatalogService> services = new ArrayList<>();
services.add(mock(CatalogService.class));
Response<List<CatalogService>> response = new Response<>(services, 1L, true, 1L);
when(clientMock.getCatalogService(Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response);
service.getRandomService("service");
Mockito.verify(clientMock).getCatalogService(Mockito.eq("service"), Mockito.any(QueryParams.class));
}
@Test
public void findService_should_return_one_service()
{
List<CatalogService> services = new ArrayList<>();
CatalogService service1 = mock(CatalogService.class);
when(service1.getAddress()).thenReturn("192.168.0.1");
services.add(service1);
CatalogService service2 = mock(CatalogService.class);
when(service2.getAddress()).thenReturn("192.168.0.2");
services.add(service2);
CatalogService service3 = mock(CatalogService.class);
when(service3.getAddress()).thenReturn("192.168.0.3");
services.add(service3);
Response<List<CatalogService>> response = new Response<>(services, 1L, true, 1L);
when(clientMock.getCatalogService(Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response);
Service catalogService = service.getRandomService("service");
boolean foundMatch = false;
for (CatalogService service : services) {
if (service.getAddress().equals(catalogService.getHostname()) && service.getServicePort() == catalogService.getPort()) {
foundMatch = true;
}
}
assertTrue(foundMatch);
Mockito.verify(clientMock).getCatalogService(Mockito.eq("service"), Mockito.any(QueryParams.class));
}
@Test
public void findService_should_return_one_service_with_tag()
{
List<CatalogService> services = new ArrayList<>();
CatalogService service1 = mock(CatalogService.class);
when(service1.getAddress()).thenReturn("192.168.0.1");
services.add(service1);
CatalogService service2 = mock(CatalogService.class);
when(service2.getAddress()).thenReturn("192.168.0.2");
services.add(service2);
CatalogService service3 = mock(CatalogService.class);
when(service3.getAddress()).thenReturn("192.168.0.3");
services.add(service3);
Response<List<CatalogService>> response = new Response<>(services, 1L, true, 1L);
when(clientMock.getCatalogService(Mockito.anyString(), Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response);
Service catalogService = service.getRandomService("service", "my-tag");
boolean foundMatch = false;
for (CatalogService service : services) {
if (service.getAddress().equals(catalogService.getHostname()) && service.getServicePort() == catalogService.getPort()) {
foundMatch = true;
}
}
assertTrue(foundMatch);
Mockito.verify(clientMock).getCatalogService(Mockito.eq("service"), Mockito.eq("my-tag"), Mockito.any(QueryParams.class));
}
}
| rebuy-de/consul-java-client | src/test/java/com/rebuy/consul/ConsulServiceTest.java | Java | mit | 5,239 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace XamarinFormsHello.WinPhone
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
LoadApplication(new XamarinFormsHello.App());
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
}
}
| xamarin-samples/XamarinFormsHello | XamarinFormsHello/XamarinFormsHello.WinPhone/MainPage.xaml.cs | C# | mit | 1,557 |
<?php
namespace LeadCommerce\Shopware\SDK\Query;
use LeadCommerce\Shopware\SDK\Util\Constants;
/**
* Class CustomerQuery
*
* @author Alexander Mahrt <amahrt@leadcommerce.de>
* @copyright 2016 LeadCommerce <amahrt@leadcommerce.de>
*/
class CustomerQuery extends Base
{
/**
* @var array
*/
protected $methodsAllowed = [
Constants::METHOD_CREATE,
Constants::METHOD_GET,
Constants::METHOD_GET_BATCH,
Constants::METHOD_UPDATE,
Constants::METHOD_DELETE,
];
/**
* @return mixed
*/
protected function getClass()
{
return 'LeadCommerce\\Shopware\\SDK\\Entity\\Customer';
}
/**
* Gets the query path to look for entities.
* E.G: 'variants' or 'articles'
*
* @return string
*/
protected function getQueryPath()
{
return 'customers';
}
}
| LeadCommerceDE/shopware-sdk | src/LeadCommerce/Shopware/SDK/Query/CustomerQuery.php | PHP | mit | 881 |
<?php
namespace GFire\InvoiceBundle\Entity\Interfaces;
interface InvoiceInterface{
} | jerickduguran/gfirev2 | src/GFire/InvoiceBundle/Entity/Interfaces/InvoiceInterface.php | PHP | mit | 87 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package test.thread;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Administrator
*/
public class CallableAndFutureTest {
private final ExecutorService executor = Executors.newFixedThreadPool(2);
void start() throws Exception {
final Callable<List<Integer>> task = new Callable<List<Integer>>() {
public List<Integer> call() throws Exception {
// get obj
final List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 100; i++) {
Thread.sleep(50);
list.add(i);
}
return list;
}
};
final Future<List<Integer>> future = executor.submit(task);
//do sthing others..
//example: due to show some data..
try {
final List<Integer> list = future.get(); //这个函数还可以接受超时检测http://www.javaeye.com/topic/671314
System.out.println(list);
} catch (final InterruptedException ex) {
Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex);
future.cancel(true);
} catch (final ExecutionException ex) {
Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex);
throw new ExecutionException(ex);
} finally {
executor.shutdown();
}
}
public static void main(final String args[]) {
try {
new CallableAndFutureTest().start();
} catch (final Exception ex) {
Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| atealxt/work-workspaces | Test_Java/src/test/thread/CallableAndFutureTest.java | Java | mit | 2,091 |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The interface IWorkbookFunctionsCumPrincRequestBuilder.
/// </summary>
public partial interface IWorkbookFunctionsCumPrincRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
IWorkbookFunctionsCumPrincRequest Request(IEnumerable<Option> options = null);
}
}
| garethj-msft/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsCumPrincRequestBuilder.cs | C# | mit | 997 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.eventhubs.generated;
import com.azure.core.util.Context;
/** Samples for ConsumerGroups ListByEventHub. */
public final class ConsumerGroupsListByEventHubSamples {
/*
* x-ms-original-file: specification/eventhub/resource-manager/Microsoft.EventHub/stable/2021-11-01/examples/ConsumerGroup/EHConsumerGroupListByEventHub.json
*/
/**
* Sample code: ConsumerGroupsListAll.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void consumerGroupsListAll(com.azure.resourcemanager.AzureResourceManager azure) {
azure
.eventHubs()
.manager()
.serviceClient()
.getConsumerGroups()
.listByEventHub("ArunMonocle", "sdk-Namespace-2661", "sdk-EventHub-6681", null, null, Context.NONE);
}
}
| Azure/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/eventhubs/generated/ConsumerGroupsListByEventHubSamples.java | Java | mit | 1,031 |
/** @jsx m */
import m from 'mithril';
import { linkTo, hrefTo } from '@storybook/addon-links';
const Main = {
view: vnode => (
<article
style={{
padding: 15,
lineHeight: 1.4,
fontFamily: '"Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif',
backgroundColor: '#ffffff',
}}
>
{vnode.children}
</article>
),
};
const Title = {
view: vnode => <h1>{vnode.children}</h1>,
};
const Note = {
view: vnode => (
<p
style={{
opacity: 0.5,
}}
>
{vnode.children}
</p>
),
};
const InlineCode = {
view: vnode => (
<code
style={{
fontSize: 15,
fontWeight: 600,
padding: '2px 5px',
border: '1px solid #eae9e9',
borderRadius: 4,
backgroundColor: '#f3f2f2',
color: '#3a3a3a',
}}
>
{vnode.children}
</code>
),
};
const Link = {
view: vnode => (
<a
style={{
color: '#1474f3',
textDecoration: 'none',
borderBottom: '1px solid #1474f3',
paddingBottom: 2,
}}
{...vnode.attrs}
>
{vnode.children}
</a>
),
};
const NavButton = {
view: vnode => (
<button
type="button"
style={{
borderTop: 'none',
borderRight: 'none',
borderLeft: 'none',
backgroundColor: 'transparent',
padding: 0,
cursor: 'pointer',
font: 'inherit',
}}
{...vnode.attrs}
>
{vnode.children}
</button>
),
};
const StoryLink = {
oninit: vnode => {
// eslint-disable-next-line no-param-reassign
vnode.state.href = '/';
// eslint-disable-next-line no-param-reassign
vnode.state.onclick = () => {
linkTo(vnode.attrs.kind, vnode.attrs.story)();
return false;
};
StoryLink.updateHref(vnode);
},
updateHref: async vnode => {
const href = await hrefTo(vnode.attrs.kind, vnode.attrs.story);
// eslint-disable-next-line no-param-reassign
vnode.state.href = href;
m.redraw();
},
view: vnode => (
<a
href={vnode.state.href}
style={{
color: '#1474f3',
textDecoration: 'none',
borderBottom: '1px solid #1474f3',
paddingBottom: 2,
}}
onClick={vnode.state.onclick}
>
{vnode.children}
</a>
),
};
const Welcome = {
view: vnode => (
<Main>
<Title>Welcome to storybook</Title>
<p>This is a UI component dev environment for your app.</p>
<p>
We've added some basic stories inside the <InlineCode>src/stories</InlineCode> directory.
<br />A story is a single state of one or more UI components. You can have as many stories
as you want.
<br />
(Basically a story is like a visual test case.)
</p>
<p>
See these sample
{vnode.attrs.showApp ? (
<NavButton onclick={vnode.attrs.showApp}>stories</NavButton>
) : (
<StoryLink kind={vnode.attrs.showKind} story={vnode.attrs.showStory}>
stories
</StoryLink>
)}
for a component called <InlineCode>Button</InlineCode>.
</p>
<p>
Just like that, you can add your own components as stories.
<br />
You can also edit those components and see changes right away.
<br />
(Try editing the <InlineCode>Button</InlineCode> stories located at
<InlineCode>src/stories/1-Button.stories.js</InlineCode>
.)
</p>
<p>
Usually we create stories with smaller UI components in the app.
<br />
Have a look at the
<Link
href="https://storybook.js.org/basics/writing-stories"
target="_blank"
rel="noopener noreferrer"
>
Writing Stories
</Link>
section in our documentation.
</p>
<Note>
<b>NOTE:</b>
<br />
Have a look at the <InlineCode>.storybook/webpack.config.js</InlineCode> to add webpack
loaders and plugins you are using in this project.
</Note>
</Main>
),
};
export default Welcome;
| storybooks/react-storybook | lib/cli/generators/MITHRIL/template-csf/stories/Welcome.js | JavaScript | mit | 4,185 |
from simtk.openmm import app
import simtk.openmm as mm
from simtk import unit
def findForce(system, forcetype, add=True):
""" Finds a specific force in the system force list - added if not found."""
for force in system.getForces():
if isinstance(force, forcetype):
return force
if add==True:
system.addForce(forcetype())
return findForce(system, forcetype)
return None
def setGlobalForceParameter(force, key, value):
for i in range(force.getNumGlobalParameters()):
if force.getGlobalParameterName(i)==key:
print('setting force parameter', key, '=', value)
force.setGlobalParameterDefaultValue(i, value);
def atomIndexInResidue(residue):
""" list of atom index in residue """
index=[]
for a in list(residue.atoms()):
index.append(a.index)
return index
def getResiduePositions(residue, positions):
""" Returns array w. atomic positions of residue """
ndx = atomIndexInResidue(residue)
return np.array(positions)[ndx]
def uniquePairs(index):
""" list of unique, internal pairs """
return list(combinations( range(index[0],index[-1]+1),2 ) )
def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k):
""" add harmonic bonds between pairs if distance is smaller than threshold """
print('Constraint force constant =', k)
for i,j in pairlist:
distance = unit.norm( positions[i]-positions[j] )
if distance<threshold:
harmonicforce.addBond( i,j,
distance.value_in_unit(unit.nanometer),
k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole ))
print("added harmonic bond between", i, j, 'with distance',distance)
def addExclusions(nonbondedforce, pairlist):
""" add nonbonded exclusions between pairs """
for i,j in pairlist:
nonbondedforce.addExclusion(i,j)
def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None,
threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole):
""" make residue rigid by adding constraints and nonbonded exclusions """
index = atomIndexInResidue(residue)
pairlist = uniquePairs(index)
addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k)
if nonbondedforce is not None:
for i,j in pairlist:
print('added nonbonded exclusion between', i, j)
nonbonded.addExclusion(i,j)
| mlund/pyha | pyha/openmm.py | Python | mit | 2,333 |
namespace InControl
{
using System;
// @cond nodoc
[AutoDiscover]
public class EightBitdoSNES30AndroidProfile : UnityInputDeviceProfile
{
public EightBitdoSNES30AndroidProfile()
{
Name = "8Bitdo SNES30 Controller";
Meta = "8Bitdo SNES30 Controller on Android";
// Link = "https://www.amazon.com/Wireless-Bluetooth-Controller-Classic-Joystick/dp/B014QP2H1E";
DeviceClass = InputDeviceClass.Controller;
DeviceStyle = InputDeviceStyle.NintendoSNES;
IncludePlatforms = new[] {
"Android"
};
JoystickNames = new[] {
"8Bitdo SNES30 GamePad",
};
ButtonMappings = new[] {
new InputControlMapping {
Handle = "A",
Target = InputControlType.Action2,
Source = Button( 0 ),
},
new InputControlMapping {
Handle = "B",
Target = InputControlType.Action1,
Source = Button( 1 ),
},
new InputControlMapping {
Handle = "X",
Target = InputControlType.Action4,
Source = Button( 2 ),
},
new InputControlMapping {
Handle = "Y",
Target = InputControlType.Action3,
Source = Button( 3 ),
},
new InputControlMapping {
Handle = "L",
Target = InputControlType.LeftBumper,
Source = Button( 4 ),
},
new InputControlMapping {
Handle = "R",
Target = InputControlType.RightBumper,
Source = Button( 5 ),
},
new InputControlMapping {
Handle = "Select",
Target = InputControlType.Select,
Source = Button( 11 ),
},
new InputControlMapping {
Handle = "Start",
Target = InputControlType.Start,
Source = Button( 10 ),
},
};
AnalogMappings = new[] {
new InputControlMapping {
Handle = "DPad Left",
Target = InputControlType.DPadLeft,
Source = Analog( 0 ),
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "DPad Right",
Target = InputControlType.DPadRight,
Source = Analog( 0 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "DPad Up",
Target = InputControlType.DPadUp,
Source = Analog( 1 ),
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "DPad Down",
Target = InputControlType.DPadDown,
Source = Analog( 1 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
},
};
}
}
// @endcond
}
| benthroop/Frankenweapon | Assets/InControl/Source/Unity/DeviceProfiles/EightBitdoSNES30AndroidProfile.cs | C# | mit | 2,543 |
package context
import (
"github.com/Everlane/evan/common"
"github.com/satori/go.uuid"
)
// Stores state relating to a deployment.
type Deployment struct {
uuid uuid.UUID
application common.Application
environment string
strategy common.Strategy
ref string
sha1 string
flags map[string]interface{}
store common.Store
// Internal state
currentState common.DeploymentState
currentPhase common.Phase
lastError error
}
// Create a deployment for the given application to an environment.
func NewDeployment(app common.Application, environment string, strategy common.Strategy, ref string, flags map[string]interface{}) *Deployment {
return &Deployment{
uuid: uuid.NewV1(),
application: app,
environment: environment,
strategy: strategy,
ref: ref,
flags: flags,
currentState: common.DEPLOYMENT_PENDING,
}
}
func NewBareDeployment() *Deployment {
return &Deployment{
flags: make(map[string]interface{}),
}
}
func (deployment *Deployment) UUID() uuid.UUID {
return deployment.uuid
}
func (deployment *Deployment) Application() common.Application {
return deployment.application
}
func (deployment *Deployment) Environment() string {
return deployment.environment
}
func (deployment *Deployment) Strategy() common.Strategy {
return deployment.strategy
}
func (deployment *Deployment) Ref() string {
return deployment.ref
}
func (deployment *Deployment) SHA1() string {
return deployment.sha1
}
func (deployment *Deployment) SetSHA1(sha1 string) {
deployment.sha1 = sha1
}
func (deployment *Deployment) MostPreciseRef() string {
if deployment.sha1 != "" {
return deployment.sha1
} else {
return deployment.ref
}
}
func (deployment *Deployment) SetStoreAndSave(store common.Store) error {
deployment.store = store
return store.SaveDeployment(deployment)
}
// Will panic if it is unable to save. This will be called *after*
// `SetStoreAndSave` should have been called, so we're assuming that if that
// worked then this should also work.
func (deployment *Deployment) setStateAndSave(state common.DeploymentState) {
deployment.currentState = state
err := deployment.store.SaveDeployment(deployment)
if err != nil {
panic(err)
}
}
func (deployment *Deployment) Flags() map[string]interface{} {
return deployment.flags
}
func (deployment *Deployment) HasFlag(key string) bool {
_, present := deployment.flags[key]
return present
}
func (deployment *Deployment) Flag(key string) interface{} {
return deployment.flags[key]
}
func (deployment *Deployment) SetFlag(key string, value interface{}) {
deployment.flags[key] = value
}
// Looks for the "force" boolean in the `flags`.
func (deployment *Deployment) IsForce() bool {
if force, ok := deployment.Flag("force").(bool); ok {
return force
} else {
return false
}
}
func (deployment *Deployment) Status() common.DeploymentStatus {
var phase common.Phase
if deployment.currentState == common.RUNNING_PHASE {
phase = deployment.currentPhase
}
return common.DeploymentStatus{
State: deployment.currentState,
Phase: phase,
Error: nil,
}
}
func (deployment *Deployment) CheckPreconditions() error {
deployment.setStateAndSave(common.RUNNING_PRECONDITIONS)
preconditions := deployment.strategy.Preconditions()
for _, precondition := range preconditions {
err := precondition.Status(deployment)
if err != nil {
return err
}
}
return nil
}
// Internal implementation of running phases. Manages setting
// `deployment.currentPhase` to the phase currently executing.
func (deployment *Deployment) runPhases(preloadResults PreloadResults) error {
phases := deployment.strategy.Phases()
for _, phase := range phases {
deployment.currentPhase = phase
preloadResult := preloadResults.Get(phase)
err := phase.Execute(deployment, preloadResult)
if err != nil {
return err
}
}
return nil
}
// Runs all the phases configured in the `Strategy`. Sets `currentState` and
// `currentPhase` fields as appropriate. If an error occurs it will also set
// the `lastError` field to that error.
func (deployment *Deployment) RunPhases() error {
results, err := deployment.RunPhasePreloads()
if err != nil {
deployment.lastError = err
deployment.setStateAndSave(common.DEPLOYMENT_ERROR)
return err
}
deployment.setStateAndSave(common.RUNNING_PHASE)
err = deployment.runPhases(results)
if err != nil {
deployment.lastError = err
deployment.setStateAndSave(common.DEPLOYMENT_ERROR)
return err
} else {
deployment.setStateAndSave(common.DEPLOYMENT_DONE)
return nil
}
}
type preloadResult struct {
data interface{}
err error
}
type PreloadResults map[common.Phase]interface{}
func (results PreloadResults) Get(phase common.Phase) interface{} {
return results[phase]
}
func (results PreloadResults) Set(phase common.Phase, data interface{}) {
results[phase] = data
}
// Phases can expose preloads to gather any additional information they may
// need before executing. This will run those preloads in parallel.
func (deployment *Deployment) RunPhasePreloads() (PreloadResults, error) {
preloadablePhases := make([]common.PreloadablePhase, 0)
for _, phase := range deployment.strategy.Phases() {
if phase.CanPreload() {
preloadablePhases = append(preloadablePhases, phase.(common.PreloadablePhase))
}
}
resultChan := make(chan preloadResult)
for _, phase := range preloadablePhases {
go func() {
data, err := phase.Preload(deployment)
resultChan <- preloadResult{data: data, err: err}
}()
}
results := make(PreloadResults)
for _, phase := range preloadablePhases {
result := <-resultChan
if result.err != nil {
return nil, result.err
} else {
results.Set(phase.(common.Phase), result.data)
}
}
return results, nil
}
| Everlane/evan | context/deployment.go | GO | mit | 5,804 |
window.Lunchiatto.module('Transfer', function(Transfer, App, Backbone, Marionette, $, _) {
return Transfer.Layout = Marionette.LayoutView.extend({
template: 'transfers/layout',
ui: {
receivedTransfers: '.received-transfers',
submittedTransfers: '.submitted-transfers'
},
behaviors: {
Animateable: {
types: ['fadeIn']
},
Titleable: {}
},
regions: {
receivedTransfers: '@ui.receivedTransfers',
submittedTransfers: '@ui.submittedTransfers'
},
onRender() {
this._showTransfers('received');
this._showTransfers('submitted');
},
_showTransfers(type) {
const transfers = new App.Entities.Transfers([], {type});
transfers.optionedFetch({
success: transfers => {
App.getUsers().then(() => {
const view = new App.Transfer.List({
collection: transfers});
this[`${type}Transfers`].show(view);
});
}
});
},
_htmlTitle() {
return 'Transfers';
}
});
});
| lunchiatto/web | app/assets/javascripts/modules/transfer/views/layout.js | JavaScript | mit | 1,061 |
package analytics
import (
"fmt"
elastic "gopkg.in/olivere/elastic.v3"
)
//Elasticsearch stores configuration related to the AWS elastic cache isntance.
type Elasticsearch struct {
URL string
IndexName string
DocType string
client *elastic.Client
}
//Initialize initializes the analytics engine.
func (e *Elasticsearch) Initialize() error {
client, err := elastic.NewSimpleClient(elastic.SetURL(e.URL))
if err != nil {
return err
}
e.client = client
s := e.client.IndexExists(e.IndexName)
exists, err := s.Do()
if err != nil {
return err
}
if !exists {
s := e.client.CreateIndex(e.IndexName)
_, err := s.Do()
if err != nil {
return err
}
}
return nil
}
//SendAnalytics is used to send the data to the analytics engine.
func (e *Elasticsearch) SendAnalytics(data string) error {
fmt.Println(data)
_, err := e.client.Index().Index(e.IndexName).Type(e.DocType).BodyJson(data).Do()
if err != nil {
return err
}
return nil
}
| awkhan/go-utility | analytics/elasticsearch.go | GO | mit | 979 |
'use strict';
var i18n = require('./i18n.js')
i18n.add_translation("pt-BR", {
test: 'OK',
greetings: {
hello: 'Olá',
welcome: 'Bem vindo'
}
});
i18n.locale = 'pt-BR';
console.log(i18n.t('greetings.hello'));
console.log(i18n.t('greetings.welcome'));
console.log("Hallo");
// Example 2
i18n.add_translation("pt-BR", {
greetings: {
hello: 'Olá',
welcome: 'Bem vindo'
}
});
console.log(i18n.t('greetings.hello'));
i18n.add_translation("pt-BR", {
test: 'OK',
greetings: {
hello: 'Oi',
bye: 'Tchau'
}
});
console.log(i18n.t('greetings.hello'));
console.log(i18n.t('test'));
| felipediesel/simple-i18n | node.js | JavaScript | mit | 617 |
/**
* @flow
*/
/* eslint-disable */
'use strict';
/*::
import type { ReaderFragment } from 'relay-runtime';
export type ReactionContent = "CONFUSED" | "EYES" | "HEART" | "HOORAY" | "LAUGH" | "ROCKET" | "THUMBS_DOWN" | "THUMBS_UP" | "%future added value";
import type { FragmentReference } from "relay-runtime";
declare export opaque type emojiReactionsView_reactable$ref: FragmentReference;
declare export opaque type emojiReactionsView_reactable$fragmentType: emojiReactionsView_reactable$ref;
export type emojiReactionsView_reactable = {|
+id: string,
+reactionGroups: ?$ReadOnlyArray<{|
+content: ReactionContent,
+viewerHasReacted: boolean,
+users: {|
+totalCount: number
|},
|}>,
+viewerCanReact: boolean,
+$refType: emojiReactionsView_reactable$ref,
|};
export type emojiReactionsView_reactable$data = emojiReactionsView_reactable;
export type emojiReactionsView_reactable$key = {
+$data?: emojiReactionsView_reactable$data,
+$fragmentRefs: emojiReactionsView_reactable$ref,
};
*/
const node/*: ReaderFragment*/ = {
"kind": "Fragment",
"name": "emojiReactionsView_reactable",
"type": "Reactable",
"metadata": null,
"argumentDefinitions": [],
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "id",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "reactionGroups",
"storageKey": null,
"args": null,
"concreteType": "ReactionGroup",
"plural": true,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "content",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "viewerHasReacted",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "users",
"storageKey": null,
"args": null,
"concreteType": "ReactingUserConnection",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "totalCount",
"args": null,
"storageKey": null
}
]
}
]
},
{
"kind": "ScalarField",
"alias": null,
"name": "viewerCanReact",
"args": null,
"storageKey": null
}
]
};
// prettier-ignore
(node/*: any*/).hash = 'fde156007f42d841401632fce79875d5';
module.exports = node;
| atom/github | lib/views/__generated__/emojiReactionsView_reactable.graphql.js | JavaScript | mit | 2,624 |
require 'bio-ucsc'
describe "Bio::Ucsc::Hg19::WgEncodeAffyRnaChipFiltTransfragsKeratinocyteCytosolLongnonpolya" do
describe "#find_by_interval" do
context "given range chr1:1-100,000" do
it "returns an array of results" do
Bio::Ucsc::Hg19::DBConnection.default
Bio::Ucsc::Hg19::DBConnection.connect
i = Bio::GenomicInterval.parse("chr1:1-100,000")
r = Bio::Ucsc::Hg19::WgEncodeAffyRnaChipFiltTransfragsKeratinocyteCytosolLongnonpolya.find_all_by_interval(i)
r.should have(1).items
end
it "returns an array of results with column accessors" do
Bio::Ucsc::Hg19::DBConnection.default
Bio::Ucsc::Hg19::DBConnection.connect
i = Bio::GenomicInterval.parse("chr1:1-100,000")
r = Bio::Ucsc::Hg19::WgEncodeAffyRnaChipFiltTransfragsKeratinocyteCytosolLongnonpolya.find_by_interval(i)
r.chrom.should == "chr1"
end
end
end
end
| misshie/bioruby-ucsc-api | spec/hg19/wgencodeaffyrnachipfilttransfragskeratinocytecytosollongnonpolya_spec.rb | Ruby | mit | 935 |
require File.expand_path("../../../test_helper", __FILE__)
describe Redcarpet::Render::HTMLAbbreviations do
before do
@renderer = Class.new do
include Redcarpet::Render::HTMLAbbreviations
end
end
describe "#preprocess" do
it "converts markdown abbrevations to HTML" do
markdown = <<-EOS.strip_heredoc
YOLO
*[YOLO]: You Only Live Once
EOS
@renderer.new.preprocess(markdown).must_equal <<-EOS.strip_heredoc.chomp
<abbr title="You Only Live Once">YOLO</abbr>
EOS
end
it "converts hyphenated abbrevations to HTML" do
markdown = <<-EOS.strip_heredoc
JSON-P
*[JSON-P]: JSON with Padding
EOS
@renderer.new.preprocess(markdown).must_equal <<-EOS.strip_heredoc.chomp
<abbr title="JSON with Padding">JSON-P</abbr>
EOS
end
it "converts abbrevations with numbers to HTML" do
markdown = <<-EOS.strip_heredoc
ES6
*[ES6]: ECMAScript 6
EOS
@renderer.new.preprocess(markdown).must_equal <<-EOS.strip_heredoc.chomp
<abbr title="ECMAScript 6">ES6</abbr>
EOS
end
end
describe "#acronym_regexp" do
it "matches an acronym at the beginning of a line" do
"FOO bar".must_match @renderer.new.acronym_regexp("FOO")
end
it "matches an acronym at the end of a line" do
"bar FOO".must_match @renderer.new.acronym_regexp("FOO")
end
it "matches an acronym next to punctuation" do
".FOO.".must_match @renderer.new.acronym_regexp("FOO")
end
it "matches an acronym with hyphens" do
"JSON-P".must_match @renderer.new.acronym_regexp("JSON-P")
end
it "doesn't match an acronym in the middle of a word" do
"YOLOFOOYOLO".wont_match @renderer.new.acronym_regexp("FOO")
end
it "matches numbers" do
"ES6".must_match @renderer.new.acronym_regexp("ES6")
end
end
end
| brandonweiss/redcarpet-abbreviations | test/redcarpet/render/html_abbreviations_test.rb | Ruby | mit | 1,921 |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateList extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('modelList', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('modelList');
}
}
| paufsc/Kanban | web/app/database/migrations/2014_10_24_214547_create_list.php | PHP | mit | 488 |
module Tire
module Model
module Persistence
# Provides infrastructure for storing records in _Elasticsearch_.
#
module Storage
def self.included(base)
base.class_eval do
extend ClassMethods
include InstanceMethods
end
end
module ClassMethods
def create(args={})
document = new(args)
return false unless document.valid?
if result = document.save
document
else
result
end
end
end
module InstanceMethods
def update_attribute(name, value)
__update_attributes name => value
save
end
def update_attributes(attributes={})
__update_attributes attributes
save
end
def update_index
run_callbacks :update_elasticsearch_index do
if destroyed?
response = index.remove self
else
if response = index.store( self, {:percolate => percolator} )
self.id ||= response['_id']
self._index = response['_index']
self._type = response['_type']
self._version = response['_version']
self.matches = response['matches']
end
end
response
end
end
def save
return false unless valid?
run_callbacks :save do
response = update_index
!! response['ok']
end
end
def destroy
run_callbacks :destroy do
@destroyed = true
response = update_index
! response.nil?
end
end
def destroyed? ; !!@destroyed; end
def persisted? ; !!id && !!_version; end
def new_record? ; !persisted?; end
end
end
end
end
end
| HenleyChiu/tire | lib/tire/model/persistence/storage.rb | Ruby | mit | 2,068 |
require 'googleanalytics/mobile'
| mono0x/googleanalytics-mobile | lib/googleanalytics-mobile.rb | Ruby | mit | 33 |
class ItemsController < ApplicationController
def create
item = Item.new(item_params)
item.user_id = @user.id
if item.save
render json: item, status: 201
else
render json: item.errors, status: 422
end
end
def destroy
item = find_item
item.destroy
head 204
end
def index
render json: @user.items.as_json, status: 200
end
def show
item = find_item
render json: item.as_json, status: 200
end
def update
item = find_item
if item.update(item_params)
render json: item.as_json, status: 200
end
end
def find_item
Item.find(params[:id])
end
private
def item_params
params.require(:item).permit(:type, :brand, :size, :color, :description)
end
end
| StuartPearlman/ClosetKeeperAPI | app/controllers/items_controller.rb | Ruby | mit | 701 |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Killer : MonoBehaviour {
public Transform RobotPlayer;
public GameObject Robot;
public Text GameOVER;
// Use this for initialization
void Start() {
RobotPlayer = GetComponent<Transform>();
}
void FixedUpdate()
{
if(RobotPlayer.gameObject.transform.position.y < -2)
{
GameOVER.gameObject.SetActive(true);
}
}
}
| ArcherSys/ArcherSys | C#/Unity/Capital Pursuit Alpha/Assets/Scripts/Killer.cs | C# | mit | 487 |
module S3Bear
module ViewHelpers
# def s3bear_bucket
# S3Bear.config.bucket + '.s3.amazonaws.com/upload.html'
# end
end
end
ActionView::Base.send(:include, S3Bear::ViewHelpers) | cracell/s3bear | lib/view_helpers.rb | Ruby | mit | 195 |
module Linter
class Base
def self.can_lint?(filename)
self::FILE_REGEXP === filename
end
def initialize(hound_config:, build:, repository_owner_name:)
@hound_config = hound_config
@build = build
@repository_owner_name = repository_owner_name
end
def file_review(commit_file)
attributes = build_review_job_attributes(commit_file)
file_review = FileReview.create!(
build: build,
filename: commit_file.filename,
)
enqueue_job(attributes)
file_review
end
def enabled?
config.linter_names.any? do |linter_name|
hound_config.enabled_for?(linter_name)
end
end
def file_included?(*)
true
end
def name
self.class.name.demodulize.underscore
end
private
attr_reader :hound_config, :build, :repository_owner_name
def build_review_job_attributes(commit_file)
{
commit_sha: build.commit_sha,
config: config.content,
content: commit_file.content,
filename: commit_file.filename,
patch: commit_file.patch,
pull_request_number: build.pull_request_number,
}
end
def enqueue_job(attributes)
Resque.enqueue(job_class, attributes)
end
def job_class
"#{name.classify}ReviewJob".constantize
end
def config
@config ||= ConfigBuilder.for(hound_config, name)
end
end
end
| Koronen/hound | app/models/linter/base.rb | Ruby | mit | 1,430 |
<?php
/*
* FluentDOM
*
* @link https://thomas.weinert.info/FluentDOM/
* @copyright Copyright 2009-2021 FluentDOM Contributors
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*
*/
namespace FluentDOM\Query {
use FluentDOM\Query;
use FluentDOM\TestCase;
require_once __DIR__.'/../../TestCase.php';
class TraversingParentsTest extends TestCase {
protected $_directory = __DIR__;
/**
* @group Traversing
* @group TraversingFind
* @covers \FluentDOM\Query::parents
*/
public function testParents(): void {
$fd = $this->getQueryFixtureFromFunctionName(__FUNCTION__);
$this->assertInstanceOf(Query::class, $fd);
$parents = $fd
->find('//b')
->parents()
->map(
function($node) {
return $node->tagName;
}
);
$this->assertTrue(is_array($parents));
$this->assertContains('span', $parents);
$this->assertContains('p', $parents);
$this->assertContains('div', $parents);
$this->assertContains('body', $parents);
$this->assertContains('html', $parents);
$parents = implode(', ', $parents);
$doc = $fd
->find('//b')
->append('<strong>'.htmlspecialchars($parents).'</strong>');
$this->assertInstanceOf(Query::class, $doc);
$this->assertFluentDOMQueryEqualsXMLFile(__FUNCTION__, $doc);
}
}
}
| FluentDOM/FluentDOM | tests/FluentDOM/Query/Traversing/ParentsTest.php | PHP | mit | 1,420 |
(function() {
'use strict';
angular
.module('app.match')
.run(appRun);
appRun.$inject = ['routerHelper'];
/* @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return [{
state: 'match',
config: {
url: '/match/:id',
templateUrl: 'app/match/match.html',
controller: 'MatchController',
controllerAs: 'vm',
title: 'Match',
settings: {
nav: 2,
content: '<i class="fa fa-lock"></i> Match'
}
}
}];
}
})(); | otaviosoares/f2f | src/client/app/match/match.route.js | JavaScript | mit | 593 |
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-docu',
templateUrl: './docu.component.html',
styleUrls: ['./docu.component.scss']
})
export class DocuComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
| TeoGia/http-on-fire | src/app/docu/docu.component.ts | TypeScript | mit | 262 |
using System;
using System.Linq;
using Cresce.Datasources.Sql;
using Cresce.Models;
using NUnit.Framework;
namespace Cresce.Business.Tests.Integration.Sql
{
[TestFixture]
internal class InvoiceRepositoryTests : SqlTests
{
private SqlInvoiceRepository _repository;
private Patient _patient;
public InvoiceRepositoryTests()
{
_repository = new SqlInvoiceRepository(this);
}
[SetUp]
public void CreateResources()
{
_patient = Utils.SavePatient();
}
[Test]
public void When_deleting_an_invoice_it_should_be_removed_from_the_database()
{
// Arrange
var invoice = Utils.SaveInvoice(_patient);
// Act
_repository.Delete(invoice.Id);
// Assert
var invoiceById = _repository.GetById(invoice.Id);
Assert.That(invoiceById, Is.Null);
}
[Test]
public void When_deleting_an_invoice_linked_with_an_appointment_it_should_be_removed_from_the_database()
{
// Arrange
var invoice = Utils.SaveInvoice(_patient);
Utils.SaveAppointment(Utils.SaveUser(), _patient, Utils.SaveService(), new DateTime(), invoiceId: invoice.Id);
// Act
_repository.Delete(invoice.Id);
// Assert
var invoiceById = _repository.GetById(invoice.Id);
Assert.That(invoiceById, Is.Null);
}
[Test]
public void When_getting_an_invoice_by_id_it_should_return_the_previously_saved_invoice()
{
// Arrange
var invoice = Utils.SaveInvoice(_patient);
// Act
var result = _repository.GetById(invoice.Id);
// Assert
Assert.That(result, Is.Not.Null);
}
[Test]
public void When_getting_an_invoice_by_id_it_should_return_specific_information()
{
// Arrange
var invoice = Utils.SaveInvoice(
_patient,
date: new DateTime(2017, 10, 23)
);
// Act
var result = _repository.GetById(invoice.Id);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.PatientId, Is.EqualTo(_patient.Id));
Assert.That(result.Date, Is.EqualTo(new DateTime(2017, 10, 23)));
Assert.That(result.Description, Is.EqualTo("some description"));
Assert.That(result.Value, Is.EqualTo(23.4));
}
[Test]
public void When_getting_a_non_existing_invoice_by_id_it_should_return_null()
{
// Arrange
var invoiceId = "-1";
// Act
var result = _repository.GetById(invoiceId);
// Assert
Assert.That(result, Is.Null);
}
[Test]
public void When_getting_an_invoices_for_patient_id_it_should_return_only_invoices_of_that_patient()
{
// Arrange
Utils.SaveInvoice(_patient, date: new DateTime(2017, 10, 23));
Utils.SaveInvoice(Utils.SavePatient("2"), date: new DateTime(2017, 10, 23));
// Act
var result = _repository.GetInvoices(_patient.Id).ToList();
// Assert
Assert.That(result.Count, Is.EqualTo(1));
}
[Test]
public void When_getting_all_invoices_it_should_return_all_persisted_invoices()
{
// Arrange
Utils.SaveInvoice(_patient, date: new DateTime(2017, 10, 23));
Utils.SaveInvoice(Utils.SavePatient("2"), date: new DateTime(2017, 10, 23));
// Act
var result = _repository.GetInvoices().ToList();
// Assert
Assert.That(result.Count, Is.EqualTo(2));
}
}
}
| AlienEngineer/Cresce | Cresce.Tests.Integration/Sql/InvoiceRepositoryTests.cs | C# | mit | 3,910 |
class Portal::CollaborationPolicy < ApplicationPolicy
end
| concord-consortium/rigse | rails/app/policies/portal/collaboration_policy.rb | Ruby | mit | 58 |
import { DOCUMENT } from '@angular/common';
import { ApplicationRef, ComponentFactoryResolver, Inject, Injectable, Injector } from '@angular/core';
import { BaseService } from 'ngx-weui/core';
import { ToptipsComponent, ToptipsType } from './toptips.component';
@Injectable({ providedIn: 'root' })
export class ToptipsService extends BaseService {
constructor(
protected readonly resolver: ComponentFactoryResolver,
protected readonly applicationRef: ApplicationRef,
protected readonly injector: Injector,
@Inject(DOCUMENT) protected readonly doc: any,
) {
super();
}
/**
* 构建一个Toptips并显示
*
* @param text 文本
* @param type 类型
* @param 显示时长后自动关闭(单位:ms)
*/
show(text: string, type: ToptipsType, time: number = 2000): ToptipsComponent {
const componentRef = this.build(ToptipsComponent);
if (type) {
componentRef.instance.type = type;
}
if (text) {
componentRef.instance.text = text;
}
componentRef.instance.time = time;
componentRef.instance.hide.subscribe(() => {
setTimeout(() => {
this.destroy(componentRef);
}, 100);
});
return componentRef.instance.onShow();
}
/**
* 构建一个Warn Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
warn(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'warn', time);
}
/**
* 构建一个Info Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
info(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'info', time);
}
/**
* 构建一个Primary Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
primary(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'primary', time);
}
/**
* 构建一个Success Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
success(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'primary', time);
}
/**
* 构建一个Default Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
default(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'default', time);
}
}
| cipchk/ngx-weui | components/toptips/toptips.service.ts | TypeScript | mit | 2,518 |
require 'test_helper'
class QuestionSubjectiveTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| Glastonbury/snusurvey | test/models/question_subjective_test.rb | Ruby | mit | 132 |
var loadJsons = require('../lib/loadJsons');
describe("Get a recursive directory load of JSONs", function() {
var data;
beforeEach(function(done) {
if(data) done();
else {
loadJsons("./specs")(function(d) {
data = d;
done();
});
}
});
it("Should return right number of jsons", function() {
expect(data.length).toBe(6);
});
it("Should have a @type field on all objects", function() {
data.forEach(function(d) {
expect(d['@type']).toBeDefined();
});
});
});
| polidore/dfg | specs/fileBased.spec.js | JavaScript | mit | 531 |
using System;
using System.Diagnostics;
using System.Text;
namespace BgeniiusUniversity.Logging
{
public class Logger : ILogger
{
public void Information(string message)
{
Trace.TraceInformation(message);
}
public void Information(string fmt, params object[] vars)
{
Trace.TraceInformation(fmt, vars);
}
public void Information(Exception exception, string fmt, params object[] vars)
{
Trace.TraceInformation(FormatExceptionMessage(exception, fmt, vars));
}
public void Warning(string message)
{
Trace.TraceWarning(message);
}
public void Warning(string fmt, params object[] vars)
{
Trace.TraceWarning(fmt, vars);
}
public void Warning(Exception exception, string fmt, params object[] vars)
{
Trace.TraceWarning(FormatExceptionMessage(exception, fmt, vars));
}
public void Error(string message)
{
Trace.TraceError(message);
}
public void Error(string fmt, params object[] vars)
{
Trace.TraceError(fmt, vars);
}
public void Error(Exception exception, string fmt, params object[] vars)
{
Trace.TraceError(FormatExceptionMessage(exception, fmt, vars));
}
public void TraceApi(string componentName, string method, TimeSpan timespan)
{
TraceApi(componentName, method, timespan, "");
}
public void TraceApi(string componentName, string method, TimeSpan timespan, string fmt, params object[] vars)
{
TraceApi(componentName, method, timespan, string.Format(fmt, vars));
}
public void TraceApi(string componentName, string method, TimeSpan timespan, string properties)
{
string message = String.Concat("Component:", componentName, ";Method:", method, ";Timespan:", timespan.ToString(), ";Properties:", properties);
Trace.TraceInformation(message);
}
private static string FormatExceptionMessage(Exception exception, string fmt, object[] vars)
{
// Simple exception formatting: for a more comprehensive version see
// http://code.msdn.microsoft.com/windowsazure/Fix-It-app-for-Building-cdd80df4
var sb = new StringBuilder();
sb.Append(string.Format(fmt, vars));
sb.Append(" Exception: ");
sb.Append(exception.ToString());
return sb.ToString();
}
}
} | bgeniius/bgUniversity | ContosoUniversity/Logging/Logger.cs | C# | mit | 2,619 |
<?php
/**
* Rule for required elements
*
* PHP version 5
*
* LICENSE:
*
* Copyright (c) 2006-2010, Alexey Borzov <avb@php.net>,
* Bertrand Mansion <golgote@mamasam.com>
* 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.
* * The names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category HTML
* @package HTML_QuickForm2
* @author Alexey Borzov <avb@php.net>
* @author Bertrand Mansion <golgote@mamasam.com>
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version SVN: $Id: Required.php 294057 2010-01-26 21:10:28Z avb $
* @link http://pear.php.net/package/HTML_QuickForm2
*/
/**
* Rule checking that the form field is not empty
*/
require_once 'HTML/QuickForm2/Rule/Nonempty.php';
/**
* Rule for required elements
*
* The main difference from "nonempty" Rule is that
* - elements to which this Rule is attached will be considered required
* ({@link HTML_QuickForm2_Node::isRequired()} will return true for them) and
* marked accordingly when outputting the form
* - this Rule can only be added directly to the element and other Rules can
* only be added to it via and_() method
*
* @category HTML
* @package HTML_QuickForm2
* @author Alexey Borzov <avb@php.net>
* @author Bertrand Mansion <golgote@mamasam.com>
* @version Release: 0.4.0
*/
class HTML_QuickForm2_Rule_Required extends HTML_QuickForm2_Rule_Nonempty
{
/**
* Disallows adding a rule to the chain with an "or" operator
*
* Required rules are different from all others because they affect the
* visual representation of an element ("* denotes required field").
* Therefore we cannot allow chaining other rules to these via or_(), since
* this will effectively mean that the field is not required anymore and the
* visual difference is bogus.
*
* @param HTML_QuickForm2_Rule
* @throws HTML_QuickForm2_Exception
*/
public function or_(HTML_QuickForm2_Rule $next)
{
throw new HTML_QuickForm2_Exception(
'or_(): Cannot add a rule to "required" rule'
);
}
}
?>
| N3X15/ATBBS-Plus | includes/3rdParty/HTML/QuickForm2/Rule/Required.php | PHP | mit | 3,540 |
class String
def split_on_unescaped(str)
self.split(/\s*(?<!\\)#{str}\s*/).map{|s| s.gsub(/\\(?=#{str})/, '') }
end
end
| rubysuperhero/hero-notes | lib/clitasks/split_on_unescaped.rb | Ruby | mit | 128 |
import axios from 'axios';
import { updateRadius } from './radius-reducer';
import { AddBType } from './b-type-reducer';
// import { create as createUser } from './users';
// import history from '../history';
/* ------------------ ACTIONS --------------------- */
const ADD_B_TYPE = 'ADD_B_TYPE';
const ADD_LNG_LAT = 'ADD_LNG_LAT';
const UPDATE_RADIUS = 'UPDATE_RADIUS';
const SWITCH_MEASUREMENT = 'SWITCH_MEASUREMENT';
/* -------------- ACTION CREATORS ----------------- */
export const addLngLat = (latitude, longitude) => ({
type: ADD_LNG_LAT,
latitude,
longitude
});
export const switchMeasurement = measurement => ({
type: SWITCH_MEASUREMENT,
measurement
});
/* ------------------ REDUCER --------------------- */
export default function reducer (state = {
latitude: null,
longitude: null,
radius: null,
businessType: null,
distanceMeasurement: 'miles'
}, action) {
switch (action.type) {
case ADD_B_TYPE:
state.businessType = action.typeStr;
break;
case ADD_LNG_LAT:
state.latitude = action.latitude;
state.longitude = action.longitude;
break;
case UPDATE_RADIUS:
state.radius = action.radInt;
break;
case SWITCH_MEASUREMENT:
state.distanceMeasurement = action.measurement;
break;
default:
return state;
}
return state;
}
| Bullseyed/Bullseye | app/reducers/report.js | JavaScript | mit | 1,361 |
module Softlayer
module User
class Customer
module Access
autoload :Authentication, 'softlayer/user/customer/access/authentication'
end
end
end
end
| zertico/softlayer | lib/softlayer/user/customer/access.rb | Ruby | mit | 180 |
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'module', 'skatejs'], factory);
} else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
factory(exports, module, require('skatejs'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, mod, global.skate);
global.skate = mod.exports;
}
})(this, function (exports, module, _skatejs) {
'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _skate = _interopRequireDefault(_skatejs);
var auiSkate = _skate['default'].noConflict();
module.exports = auiSkate;
});
//# sourceMappingURL=../../../js/aui/internal/skate.js.map | parambirs/aui-demos | node_modules/@atlassian/aui/lib/js/aui/internal/skate.js | JavaScript | mit | 757 |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIButton : MonoBehaviour {
[SerializeField] private GameObject targetObject;
[SerializeField] private string targetMessage;
public Color highlightColor = Color.cyan;
public void OnMouseOver() {
SpriteRenderer sprite = GetComponent<SpriteRenderer>();
if (sprite != null) {
sprite.color = highlightColor;
}
}
public void OnMouseExit() {
SpriteRenderer sprite = GetComponent<SpriteRenderer>();
if (sprite != null) {
sprite.color = Color.white;
}
}
public void OnMouseDown() {
transform.localScale *= 1.1f;
}
public void OnMouseUp() {
transform.localScale = Vector3.one;
if (targetObject != null) {
targetObject.SendMessage(targetMessage);
}
}
}
| ivanarellano/unity-in-action-book | Ch05/Assets/UIButton.cs | C# | mit | 904 |
<footer class="main-footer">
<div class="pull-right hidden-xs">
</div>
<strong>Orange TV.</strong> All rights reserved.
</footer>
<!-- Control Sidebar -->
<!-- /.control-sidebar -->
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->
<!-- jQuery 2.2.3 -->
<script src="assets/plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
$.widget.bridge('uibutton', $.ui.button);
</script>
<!-- DataTables -->
<script src="assets/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="assets/plugins/datatables/dataTables.bootstrap.min.js"></script>
<!--<script src="assets/plugins/ckeditor/adapters/jquery.js"></script>-->
<!-- Bootstrap 3.3.6 -->
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<!-- <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> -->
<!-- Morris.js charts -->
<!--
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="assets/plugins/morris/morris.min.js"></script>
-->
<!-- Sparkline -->
<script src="assets/plugins/sparkline/jquery.sparkline.min.js"></script>
<!-- jvectormap -->
<script src="assets/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="assets/plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<!-- jQuery Knob Chart -->
<script src="assets/plugins/knob/jquery.knob.js"></script>
<!-- daterangepicker -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
<script src="assets/plugins/daterangepicker/daterangepicker.js"></script>
<!-- datepicker -->
<script src="assets/plugins/datepicker/bootstrap-datepicker.js"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src="assets/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<!-- Slimscroll -->
<script src="assets/plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="assets/plugins/fastclick/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="assets/dist/js/app.min.js"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<!--<script src="assets/dist/js/pages/dashboard.js"></script>-->
<!-- AdminLTE for demo purposes -->
<script src="assets/dist/js/demo.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.flash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
<!--
<script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/pdfmake.min.js"></script>
<script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/vfs_fonts.js"></script>
-->
<script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.print.min.js"></script>
<script src="assets/dist/js/custom.js"></script>
<script>
$(function () {
/*
var table = $('#example').DataTable( {
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
]
} );
table.buttons().container()
.appendTo( $('div.eight.column:eq(0)', table.table().container()) );
$('#example2').DataTable( {
buttons: [
{
extend: 'excel',
text: 'Save current page',
exportOptions: {
modifier: {
page: 'current'
}
}
}
]
} );
*/
$('#example').DataTable( {
dom: 'Bfrtip',
pageLength: 5,
//dom : 'Bflit',
buttons: ['copy', 'csv', 'excel', 'pdf', 'print'],
responsive: true
} );
$("#example1").DataTable();
$("#example2").DataTable({
"paging": false
});
$('#example3').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false
});
$('#example30').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false
});
});
// datatable paging
$(function() {
table = $('#example2c').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php if(isset($url)) {echo $url; } ?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ 0 ], //first column / numbering column
"orderable": false, //set not orderable
},
],
});
});
</script>
</body>
</html>
| ariefstd/cdone_server_new | application/views/footer.php | PHP | mit | 5,358 |
using Newtonsoft.Json;
using System.Collections.Generic;
namespace EaToGliffy.Gliffy.Model
{
public class GliffyParentObject : GliffyObject
{
[JsonProperty(PropertyName = "children")]
public List<GliffyObject> Children { get; set; }
}
}
| vzoran/eatogliffy | eatogliffy/gliffy/model/GliffyParentObject.cs | C# | mit | 269 |
// Copyright (c) 2011-2015 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "JsonOutputStreamSerializer.h"
#include <cassert>
#include <stdexcept>
#include "Common/StringTools.h"
using Common::JsonValue;
using namespace CryptoNote;
namespace CryptoNote {
std::ostream& operator<<(std::ostream& out, const JsonOutputStreamSerializer& enumerator) {
out << enumerator.root;
return out;
}
}
namespace {
template <typename T>
void insertOrPush(JsonValue& js, Common::StringView name, const T& value) {
if (js.isArray()) {
js.pushBack(JsonValue(value));
} else {
js.insert(std::string(name), JsonValue(value));
}
}
}
JsonOutputStreamSerializer::JsonOutputStreamSerializer() : root(JsonValue::OBJECT) {
chain.push_back(&root);
}
JsonOutputStreamSerializer::~JsonOutputStreamSerializer() {
}
ISerializer::SerializerType JsonOutputStreamSerializer::type() const {
return ISerializer::OUTPUT;
}
bool JsonOutputStreamSerializer::beginObject(Common::StringView name) {
JsonValue& parent = *chain.back();
JsonValue obj(JsonValue::OBJECT);
if (parent.isObject()) {
chain.push_back(&parent.insert(std::string(name), obj));
} else {
chain.push_back(&parent.pushBack(obj));
}
return true;
}
void JsonOutputStreamSerializer::endObject() {
assert(!chain.empty());
chain.pop_back();
}
bool JsonOutputStreamSerializer::beginArray(size_t& size, Common::StringView name) {
JsonValue val(JsonValue::ARRAY);
JsonValue& res = chain.back()->insert(std::string(name), val);
chain.push_back(&res);
return true;
}
void JsonOutputStreamSerializer::endArray() {
assert(!chain.empty());
chain.pop_back();
}
bool JsonOutputStreamSerializer::operator()(uint64_t& value, Common::StringView name) {
int64_t v = static_cast<int64_t>(value);
return operator()(v, name);
}
bool JsonOutputStreamSerializer::operator()(uint16_t& value, Common::StringView name) {
uint64_t v = static_cast<uint64_t>(value);
return operator()(v, name);
}
bool JsonOutputStreamSerializer::operator()(int16_t& value, Common::StringView name) {
int64_t v = static_cast<int64_t>(value);
return operator()(v, name);
}
bool JsonOutputStreamSerializer::operator()(uint32_t& value, Common::StringView name) {
uint64_t v = static_cast<uint64_t>(value);
return operator()(v, name);
}
bool JsonOutputStreamSerializer::operator()(int32_t& value, Common::StringView name) {
int64_t v = static_cast<int64_t>(value);
return operator()(v, name);
}
bool JsonOutputStreamSerializer::operator()(int64_t& value, Common::StringView name) {
insertOrPush(*chain.back(), name, value);
return true;
}
bool JsonOutputStreamSerializer::operator()(double& value, Common::StringView name) {
insertOrPush(*chain.back(), name, value);
return true;
}
bool JsonOutputStreamSerializer::operator()(std::string& value, Common::StringView name) {
insertOrPush(*chain.back(), name, value);
return true;
}
bool JsonOutputStreamSerializer::operator()(uint8_t& value, Common::StringView name) {
insertOrPush(*chain.back(), name, static_cast<int64_t>(value));
return true;
}
bool JsonOutputStreamSerializer::operator()(bool& value, Common::StringView name) {
insertOrPush(*chain.back(), name, value);
return true;
}
bool JsonOutputStreamSerializer::binary(void* value, size_t size, Common::StringView name) {
std::string hex = Common::toHex(value, size);
return (*this)(hex, name);
}
bool JsonOutputStreamSerializer::binary(std::string& value, Common::StringView name) {
return binary(const_cast<char*>(value.data()), value.size(), name);
}
| tobeyrowe/StarKingdomCoin | src/Serialization/JsonOutputStreamSerializer.cpp | C++ | mit | 3,698 |
# Be sure to restart your server when you modify this file.
Refinery::Application.config.session_store :cookie_store, :key => '_skwarcan_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# Refinery::Application.config.session_store :active_record_store
| mskwarcan/skwarcan | config/initializers/session_store.rb | Ruby | mit | 409 |
/*
* author: Lisa
* Info: Base64 / UTF8
* 编码 & 解码
*/
function base64Encode(input) {
var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "=";
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
do {
chr1 = input[i++];
chr2 = input[i++];
chr3 = input[i++];
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
keyStr.charAt(enc1) +
keyStr.charAt(enc2) +
keyStr.charAt(enc3) +
keyStr.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
}
function base64Decode(input) {
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
var base64test = /[^A-Za-z0-9/+///=]/g;
if (base64test.exec(input)) {
alert("There were invalid base64 characters in the input text./n" +
"Valid base64 characters are A-Z, a-z, 0-9, '+', '/', and '='/n" +
"Expect errors in decoding.");
}
input = input.replace(/[^A-Za-z0-9/+///=]/g, "");
output=new Array();
do {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output.push(chr1);
if (enc3 != 64) {
output.push(chr2);
}
if (enc4 != 64) {
output.push(chr3);
}
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
}
function UTF8Encode(str){
var temp = "",rs = "";
for( var i=0 , len = str.length; i < len; i++ ){
temp = str.charCodeAt(i).toString(16);
rs += "\\u"+ new Array(5-temp.length).join("0") + temp;
}
return rs;
}
function UTF8Decode(str){
return str.replace(/(\\u)(\w{4}|\w{2})/gi, function($0,$1,$2){
return String.fromCharCode(parseInt($2,16));
});
}
exports.base64Encode = base64Encode;
exports.base64Decode = base64Decode;
exports.UTF8Encode = UTF8Encode;
exports.UTF8Decode = UTF8Decode;
| jrcjing/cbg-log | lib/Tool/base64.js | JavaScript | mit | 2,332 |
<?php namespace ShinyDeploy\Domain\Database;
use ShinyDeploy\Core\Crypto\PasswordCrypto;
use ShinyDeploy\Core\Helper\StringHelper;
use ShinyDeploy\Exceptions\DatabaseException;
use ShinyDeploy\Exceptions\MissingDataException;
use ShinyDeploy\Traits\CryptableDomain;
class ApiKeys extends DatabaseDomain
{
use CryptableDomain;
/**
* Generates new API key and stores it to database.
*
* @param int $deploymentId
* @throws DatabaseException
* @throws MissingDataException
* @throws \ShinyDeploy\Exceptions\CryptographyException
* @return array
*/
public function addApiKey(int $deploymentId): array
{
if (empty($this->encryptionKey)) {
throw new MissingDataException('Encryption key not set.');
}
if (empty($deploymentId)) {
throw new MissingDataException('Deployment id can not be empty.');
}
$apiKey = StringHelper::getRandomString(20);
$passwordForUrl = StringHelper::getRandomString(16);
$password = $passwordForUrl . $this->config->get('auth.secret');
$passwordHash = hash('sha256', $password);
$encryption = new PasswordCrypto();
$encryptionKeySave = $encryption->encrypt($this->encryptionKey, $password);
$statement = "INSERT INTO api_keys (`api_key`,`deployment_id`,`password`,`encryption_key`)"
. " VALUES (%s,%i,%s,%s)";
$result = $this->db->prepare($statement, $apiKey, $deploymentId, $passwordHash, $encryptionKeySave)->execute();
if ($result === false) {
throw new DatabaseException('Could not store API key to database.');
}
return [
'apiKey' => $apiKey,
'apiPassword' => $passwordForUrl
];
}
/**
* Deletes all existing API keys for specified deployment.
*
* @param int $deploymentId
* @throws MissingDataException
* @return bool
*/
public function deleteApiKeysByDeploymentId(int $deploymentId): bool
{
if (empty($deploymentId)) {
throw new MissingDataException('Deployment id can not be empty.');
}
try {
$statement = "DELETE FROM api_keys WHERE `deployment_id` = %i";
return $this->db->prepare($statement, $deploymentId)->execute();
} catch (DatabaseException $e) {
return false;
}
}
/**
* Fetches API key data by api-key.
*
* @param string $apiKey
* @return array
* @throws MissingDataException
* @throws DatabaseException
*/
public function getDataByApiKey(string $apiKey): array
{
if (empty($apiKey)) {
throw new MissingDataException('API key can not be empty.');
}
$statement = "SELECT * FROM api_keys WHERE `api_key` = %s";
return $this->db->prepare($statement, $apiKey)->getResult();
}
}
| nekudo/shiny_deploy | src/ShinyDeploy/Domain/Database/ApiKeys.php | PHP | mit | 2,903 |
require File.dirname(__FILE__) + '/../spec_helper'
describe "Standard Tags" do
dataset :users_and_pages, :file_not_found, :snippets
it '<r:page> should allow access to the current page' do
page(:home)
page.should render('<r:page:title />').as('Home')
page.should render(%{<r:find url="/radius"><r:title /> | <r:page:title /></r:find>}).as('Radius | Home')
end
[:breadcrumb, :slug, :title, :url].each do |attr|
it "<r:#{attr}> should render the '#{attr}' attribute" do
value = page.send(attr)
page.should render("<r:#{attr} />").as(value.to_s)
end
end
it "<r:url> with a nil relative URL root should scope to the relative root of /" do
ActionController::Base.relative_url_root = nil
page(:home).should render("<r:url />").as("/")
end
it '<r:url> with a relative URL root should scope to the relative root' do
page(:home).should render("<r:url />").with_relative_root("/foo").as("/foo/")
end
it '<r:parent> should change the local context to the parent page' do
page(:parent)
page.should render('<r:parent><r:title /></r:parent>').as(pages(:home).title)
page.should render('<r:parent><r:children:each by="title"><r:title /></r:children:each></r:parent>').as(page_eachable_children(pages(:home)).collect(&:title).join(""))
page.should render('<r:children:each><r:parent:title /></r:children:each>').as(@page.title * page.children.count)
end
it '<r:if_parent> should render the contained block if the current page has a parent page' do
page.should render('<r:if_parent>true</r:if_parent>').as('true')
page(:home).should render('<r:if_parent>true</r:if_parent>').as('')
end
it '<r:unless_parent> should render the contained block unless the current page has a parent page' do
page.should render('<r:unless_parent>true</r:unless_parent>').as('')
page(:home).should render('<r:unless_parent>true</r:unless_parent>').as('true')
end
it '<r:if_children> should render the contained block if the current page has child pages' do
page(:home).should render('<r:if_children>true</r:if_children>').as('true')
page(:childless).should render('<r:if_children>true</r:if_children>').as('')
end
it '<r:unless_children> should render the contained block if the current page has no child pages' do
page(:home).should render('<r:unless_children>true</r:unless_children>').as('')
page(:childless).should render('<r:unless_children>true</r:unless_children>').as('true')
end
describe "<r:children:each>" do
it "should iterate through the children of the current page" do
page(:parent)
page.should render('<r:children:each><r:title /> </r:children:each>').as('Child Child 2 Child 3 ')
page.should render('<r:children:each><r:page><r:slug />/<r:child:slug /> </r:page></r:children:each>').as('parent/child parent/child-2 parent/child-3 ')
page(:assorted).should render(page_children_each_tags).as('a b c d e f g h i j ')
end
it 'should not list draft pages' do
page.should render('<r:children:each by="title"><r:slug /> </r:children:each>').as('a b c d e f g h i j ')
end
it 'should include draft pages with status="all"' do
page.should render('<r:children:each status="all" by="slug"><r:slug /> </r:children:each>').as('a b c d draft e f g h i j ')
end
it "should include draft pages by default on the dev host" do
page.should render('<r:children:each by="slug"><r:slug /> </r:children:each>').as('a b c d draft e f g h i j ').on('dev.site.com')
end
it 'should not list draft pages on dev.site.com when Radiant::Config["dev.host"] is set to something else' do
Radiant::Config['dev.host'] = 'preview.site.com'
page.should render('<r:children:each by="title"><r:slug /> </r:children:each>').as('a b c d e f g h i j ').on('dev.site.com')
end
it 'should paginate results when "paginated" attribute is "true"' do
page.pagination_parameters = {:page => 1, :per_page => 10}
page.should render('<r:children:each paginated="true" per_page="10"><r:slug /> </r:children:each>').as('a b c d e f g h i j ')
page.should render('<r:children:each paginated="true" per_page="2"><r:slug /> </r:children:each>').matching(/div class="pagination"/)
end
it 'should error with invalid "limit" attribute' do
message = "`limit' attribute of `each' tag must be a positive number between 1 and 4 digits"
page.should render(page_children_each_tags(%{limit="a"})).with_error(message)
page.should render(page_children_each_tags(%{limit="-10"})).with_error(message)
page.should render(page_children_each_tags(%{limit="50000"})).with_error(message)
end
it 'should error with invalid "offset" attribute' do
message = "`offset' attribute of `each' tag must be a positive number between 1 and 4 digits"
page.should render(page_children_each_tags(%{offset="a"})).with_error(message)
page.should render(page_children_each_tags(%{offset="-10"})).with_error(message)
page.should render(page_children_each_tags(%{offset="50000"})).with_error(message)
end
it 'should error with invalid "by" attribute' do
message = "`by' attribute of `each' tag must be set to a valid field name"
page.should render(page_children_each_tags(%{by="non-existant-field"})).with_error(message)
end
it 'should error with invalid "order" attribute' do
message = %{`order' attribute of `each' tag must be set to either "asc" or "desc"}
page.should render(page_children_each_tags(%{order="asdf"})).with_error(message)
end
it "should limit the number of children when given a 'limit' attribute" do
page.should render(page_children_each_tags(%{limit="5"})).as('a b c d e ')
end
it "should limit and offset the children when given 'limit' and 'offset' attributes" do
page.should render(page_children_each_tags(%{offset="3" limit="5"})).as('d e f g h ')
end
it "should change the sort order when given an 'order' attribute" do
page.should render(page_children_each_tags(%{order="desc"})).as('j i h g f e d c b a ')
end
it "should sort by the 'by' attribute" do
page.should render(page_children_each_tags(%{by="breadcrumb"})).as('f e d c b a j i h g ')
end
it "should sort by the 'by' attribute according to the 'order' attribute" do
page.should render(page_children_each_tags(%{by="breadcrumb" order="desc"})).as('g h i j a b c d e f ')
end
describe 'with "status" attribute' do
it "set to 'all' should list all children" do
page.should render(page_children_each_tags(%{status="all"})).as("a b c d e f g h i j draft ")
end
it "set to 'draft' should list only children with 'draft' status" do
page.should render(page_children_each_tags(%{status="draft"})).as('draft ')
end
it "set to 'published' should list only children with 'draft' status" do
page.should render(page_children_each_tags(%{status="published"})).as('a b c d e f g h i j ')
end
it "set to an invalid status should render an error" do
page.should render(page_children_each_tags(%{status="askdf"})).with_error("`status' attribute of `each' tag must be set to a valid status")
end
end
end
describe "<r:children:each:if_first>" do
it "should render for the first child" do
tags = '<r:children:each><r:if_first>FIRST:</r:if_first><r:slug /> </r:children:each>'
expected = "FIRST:article article-2 article-3 article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:each:unless_first>" do
it "should render for all but the first child" do
tags = '<r:children:each><r:unless_first>NOT-FIRST:</r:unless_first><r:slug /> </r:children:each>'
expected = "article NOT-FIRST:article-2 NOT-FIRST:article-3 NOT-FIRST:article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:each:if_last>" do
it "should render for the last child" do
tags = '<r:children:each><r:if_last>LAST:</r:if_last><r:slug /> </r:children:each>'
expected = "article article-2 article-3 LAST:article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:each:unless_last>" do
it "should render for all but the last child" do
tags = '<r:children:each><r:unless_last>NOT-LAST:</r:unless_last><r:slug /> </r:children:each>'
expected = "NOT-LAST:article NOT-LAST:article-2 NOT-LAST:article-3 article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:each:header>" do
it "should render the header when it changes" do
tags = '<r:children:each><r:header>[<r:date format="%b/%y" />] </r:header><r:slug /> </r:children:each>'
expected = "[Dec/00] article [Feb/01] article-2 article-3 [Mar/01] article-4 "
page(:news).should render(tags).as(expected)
end
it 'with "name" attribute should maintain a separate header' do
tags = %{<r:children:each><r:header name="year">[<r:date format='%Y' />] </r:header><r:header name="month">(<r:date format="%b" />) </r:header><r:slug /> </r:children:each>}
expected = "[2000] (Dec) article [2001] (Feb) article-2 article-3 (Mar) article-4 "
page(:news).should render(tags).as(expected)
end
it 'with "restart" attribute set to one name should restart that header' do
tags = %{<r:children:each><r:header name="year" restart="month">[<r:date format='%Y' />] </r:header><r:header name="month">(<r:date format="%b" />) </r:header><r:slug /> </r:children:each>}
expected = "[2000] (Dec) article [2001] (Feb) article-2 article-3 (Mar) article-4 "
page(:news).should render(tags).as(expected)
end
it 'with "restart" attribute set to two names should restart both headers' do
tags = %{<r:children:each><r:header name="year" restart="month;day">[<r:date format='%Y' />] </r:header><r:header name="month" restart="day">(<r:date format="%b" />) </r:header><r:header name="day"><<r:date format='%d' />> </r:header><r:slug /> </r:children:each>}
expected = "[2000] (Dec) <01> article [2001] (Feb) <09> article-2 <24> article-3 (Mar) <06> article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:count>" do
it 'should render the number of children of the current page' do
page(:parent).should render('<r:children:count />').as('3')
end
it "should accept the same scoping conditions as <r:children:each>" do
page.should render('<r:children:count />').as('10')
page.should render('<r:children:count status="all" />').as('11')
page.should render('<r:children:count status="draft" />').as('1')
page.should render('<r:children:count status="hidden" />').as('0')
end
end
describe "<r:children:first>" do
it 'should render its contents in the context of the first child page' do
page(:parent).should render('<r:children:first:title />').as('Child')
end
it 'should accept the same scoping attributes as <r:children:each>' do
page.should render(page_children_first_tags).as('a')
page.should render(page_children_first_tags(%{limit="5"})).as('a')
page.should render(page_children_first_tags(%{offset="3" limit="5"})).as('d')
page.should render(page_children_first_tags(%{order="desc"})).as('j')
page.should render(page_children_first_tags(%{by="breadcrumb"})).as('f')
page.should render(page_children_first_tags(%{by="breadcrumb" order="desc"})).as('g')
end
it "should render nothing when no children exist" do
page(:first).should render('<r:children:first:title />').as('')
end
end
describe "<r:children:last>" do
it 'should render its contents in the context of the last child page' do
page(:parent).should render('<r:children:last:title />').as('Child 3')
end
it 'should accept the same scoping attributes as <r:children:each>' do
page.should render(page_children_last_tags).as('j')
page.should render(page_children_last_tags(%{limit="5"})).as('e')
page.should render(page_children_last_tags(%{offset="3" limit="5"})).as('h')
page.should render(page_children_last_tags(%{order="desc"})).as('a')
page.should render(page_children_last_tags(%{by="breadcrumb"})).as('g')
page.should render(page_children_last_tags(%{by="breadcrumb" order="desc"})).as('f')
end
it "should render nothing when no children exist" do
page(:first).should render('<r:children:last:title />').as('')
end
end
describe "<r:content>" do
it "should render the 'body' part by default" do
page.should render('<r:content />').as('Assorted body.')
end
it "with 'part' attribute should render the specified part" do
page(:home).should render('<r:content part="extended" />').as("Just a test.")
end
it "should prevent simple recursion" do
page(:recursive_parts).should render('<r:content />').with_error("Recursion error: already rendering the `body' part.")
end
it "should prevent deep recursion" do
page(:recursive_parts).should render('<r:content part="one"/>').with_error("Recursion error: already rendering the `one' part.")
page(:recursive_parts).should render('<r:content part="two"/>').with_error("Recursion error: already rendering the `two' part.")
end
it "should allow repetition" do
page(:recursive_parts).should render('<r:content part="repeat"/>').as('xx')
end
it "should not prevent rendering a part more than once in sequence" do
page(:home).should render('<r:content /><r:content />').as('Hello world!Hello world!')
end
describe "with inherit attribute" do
it "missing or set to 'false' should render the current page's part" do
page.should render('<r:content part="sidebar" />').as('')
page.should render('<r:content part="sidebar" inherit="false" />').as('')
end
describe "set to 'true'" do
it "should render an ancestor's part" do
page.should render('<r:content part="sidebar" inherit="true" />').as('Assorted sidebar.')
end
it "should render nothing when no ancestor has the part" do
page.should render('<r:content part="part_that_doesnt_exist" inherit="true" />').as('')
end
describe "and contextual attribute" do
it "set to 'true' should render the part in the context of the current page" do
page(:parent).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Parent sidebar.')
page(:child).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Child sidebar.')
page(:grandchild).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Grandchild sidebar.')
end
it "set to 'false' should render the part in the context of its containing page" do
page(:parent).should render('<r:content part="sidebar" inherit="true" contextual="false" />').as('Home sidebar.')
end
it "should maintain the global page" do
page(:first)
page.should render('<r:content part="titles" inherit="true" contextual="true"/>').as('First First')
page.should render('<r:content part="titles" inherit="true" contextual="false"/>').as('Home First')
end
end
end
it "set to an erroneous value should render an error" do
page.should render('<r:content part="sidebar" inherit="weird value" />').with_error(%{`inherit' attribute of `content' tag must be set to either "true" or "false"})
end
it "should render parts with respect to the current contextual page" do
expected = "Child body. Child 2 body. Child 3 body. "
page(:parent).should render('<r:children:each><r:content /> </r:children:each>').as(expected)
end
end
end
describe "<r:if_content>" do
it "without 'part' attribute should render the contained block if the 'body' part exists" do
page.should render('<r:if_content>true</r:if_content>').as('true')
end
it "should render the contained block if the specified part exists" do
page.should render('<r:if_content part="body">true</r:if_content>').as('true')
end
it "should not render the contained block if the specified part does not exist" do
page.should render('<r:if_content part="asdf">true</r:if_content>').as('')
end
describe "with more than one part given (separated by comma)" do
it "should render the contained block only if all specified parts exist" do
page(:home).should render('<r:if_content part="body, extended">true</r:if_content>').as('true')
end
it "should not render the contained block if at least one of the specified parts does not exist" do
page(:home).should render('<r:if_content part="body, madeup">true</r:if_content>').as('')
end
describe "with inherit attribute set to 'true'" do
it 'should render the contained block if the current or ancestor pages have the specified parts' do
page(:guests).should render('<r:if_content part="favors, extended" inherit="true">true</r:if_content>').as('true')
end
it 'should not render the contained block if the current or ancestor pages do not have all of the specified parts' do
page(:guests).should render('<r:if_content part="favors, madeup" inherit="true">true</r:if_content>').as('')
end
describe "with find attribute set to 'any'" do
it 'should render the contained block if the current or ancestor pages have any of the specified parts' do
page(:guests).should render('<r:if_content part="favors, madeup" inherit="true" find="any">true</r:if_content>').as('true')
end
it 'should still render the contained block if first of the specified parts has not been found' do
page(:guests).should render('<r:if_content part="madeup, favors" inherit="true" find="any">true</r:if_content>').as('true')
end
end
end
describe "with inherit attribute set to 'false'" do
it 'should render the contained block if the current page has the specified parts' do
page(:guests).should render('<r:if_content part="favors, games" inherit="false">true</r:if_content>').as('')
end
it 'should not render the contained block if the current or ancestor pages do not have all of the specified parts' do
page(:guests).should render('<r:if_content part="favors, madeup" inherit="false">true</r:if_content>').as('')
end
end
describe "with the 'find' attribute set to 'any'" do
it "should render the contained block if any of the specified parts exist" do
page.should render('<r:if_content part="body, asdf" find="any">true</r:if_content>').as('true')
end
end
describe "with the 'find' attribute set to 'all'" do
it "should render the contained block if all of the specified parts exist" do
page(:home).should render('<r:if_content part="body, sidebar" find="all">true</r:if_content>').as('true')
end
it "should not render the contained block if all of the specified parts do not exist" do
page.should render('<r:if_content part="asdf, madeup" find="all">true</r:if_content>').as('')
end
end
end
end
describe "<r:unless_content>" do
describe "with inherit attribute set to 'true'" do
it 'should not render the contained block if the current or ancestor pages have the specified parts' do
page(:guests).should render('<r:unless_content part="favors, extended" inherit="true">true</r:unless_content>').as('')
end
it 'should render the contained block if the current or ancestor pages do not have the specified parts' do
page(:guests).should render('<r:unless_content part="madeup, imaginary" inherit="true">true</r:unless_content>').as('true')
end
it "should not render the contained block if the specified part does not exist but does exist on an ancestor" do
page.should render('<r:unless_content part="sidebar" inherit="true">false</r:unless_content>').as('')
end
describe "with find attribute set to 'any'" do
it 'should not render the contained block if the current or ancestor pages have any of the specified parts' do
page(:guests).should render('<r:unless_content part="favors, madeup" inherit="true" find="any">true</r:unless_content>').as('')
end
it 'should still not render the contained block if first of the specified parts has not been found' do
page(:guests).should render('<r:unless_content part="madeup, favors" inherit="true" find="any">true</r:unless_content>').as('')
end
end
end
it "without 'part' attribute should not render the contained block if the 'body' part exists" do
page.should render('<r:unless_content>false</r:unless_content>').as('')
end
it "should not render the contained block if the specified part exists" do
page.should render('<r:unless_content part="body">false</r:unless_content>').as('')
end
it "should render the contained block if the specified part does not exist" do
page.should render('<r:unless_content part="asdf">false</r:unless_content>').as('false')
end
it "should render the contained block if the specified part does not exist but does exist on an ancestor" do
page.should render('<r:unless_content part="sidebar">false</r:unless_content>').as('false')
end
describe "with more than one part given (separated by comma)" do
it "should not render the contained block if all of the specified parts exist" do
page(:home).should render('<r:unless_content part="body, extended">true</r:unless_content>').as('')
end
it "should render the contained block if at least one of the specified parts exists" do
page(:home).should render('<r:unless_content part="body, madeup">true</r:unless_content>').as('true')
end
describe "with the 'inherit' attribute set to 'true'" do
it "should render the contained block if the current or ancestor pages have none of the specified parts" do
page.should render('<r:unless_content part="imaginary, madeup" inherit="true">true</r:unless_content>').as('true')
end
it "should not render the contained block if all of the specified parts are present on the current or ancestor pages" do
page(:party).should render('<r:unless_content part="favors, extended" inherit="true">true</r:unless_content>').as('')
end
end
describe "with the 'find' attribute set to 'all'" do
it "should not render the contained block if all of the specified parts exist" do
page(:home).should render('<r:unless_content part="body, sidebar" find="all">true</r:unless_content>').as('')
end
it "should render the contained block unless all of the specified parts exist" do
page.should render('<r:unless_content part="body, madeup" find="all">true</r:unless_content>').as('true')
end
end
describe "with the 'find' attribute set to 'any'" do
it "should not render the contained block if any of the specified parts exist" do
page.should render('<r:unless_content part="body, madeup" find="any">true</r:unless_content>').as('')
end
end
end
end
describe "<r:author>" do
it "should render the author of the current page" do
page.should render('<r:author />').as('Admin')
end
it "should render nothing when the page has no author" do
page(:no_user).should render('<r:author />').as('')
end
end
describe "<r:gravatar>" do
it "should render the Gravatar URL of author of the current page" do
page.should render('<r:gravatar />').as('http://www.gravatar.com/avatar.php?gravatar_id=e64c7d89f26bd1972efa854d13d7dd61&rating=G&size=32')
end
it "should render the Gravatar URL of the name user" do
page.should render('<r:gravatar name="Admin" />').as('http://www.gravatar.com/avatar.php?gravatar_id=e64c7d89f26bd1972efa854d13d7dd61&rating=G&size=32')
end
it "should render the default avatar when the user has not set an email address" do
page.should render('<r:gravatar name="Designer" />').as('http://testhost.tld/images/admin/avatar_32x32.png')
end
it "should render the specified size" do
page.should render('<r:gravatar name="Designer" size="96px" />').as('http://testhost.tld/images/admin/avatar_96x96.png')
end
it "should render the specified rating" do
page.should render('<r:gravatar rating="X" />').as('http://www.gravatar.com/avatar.php?gravatar_id=e64c7d89f26bd1972efa854d13d7dd61&rating=X&size=32')
end
end
describe "<r:date>" do
before :each do
page(:dated)
end
it "should render the published date of the page" do
page.should render('<r:date />').as('Wednesday, January 11, 2006')
end
it "should format the published date according to the 'format' attribute" do
page.should render('<r:date format="%d %b %Y" />').as('11 Jan 2006')
end
describe "with 'for' attribute" do
it "set to 'now' should render the current date in the current Time.zone" do
page.should render('<r:date for="now" />').as(Time.zone.now.strftime("%A, %B %d, %Y"))
end
it "set to 'created_at' should render the creation date" do
page.should render('<r:date for="created_at" />').as('Tuesday, January 10, 2006')
end
it "set to 'updated_at' should render the update date" do
page.should render('<r:date for="updated_at" />').as('Thursday, January 12, 2006')
end
it "set to 'published_at' should render the publish date" do
page.should render('<r:date for="published_at" />').as('Wednesday, January 11, 2006')
end
it "set to an invalid attribute should render an error" do
page.should render('<r:date for="blah" />').with_error("Invalid value for 'for' attribute.")
end
end
it "should use the currently set timezone" do
Time.zone = "Tokyo"
format = "%H:%m"
expected = page.published_at.in_time_zone(ActiveSupport::TimeZone['Tokyo']).strftime(format)
page.should render(%Q(<r:date format="#{format}" />) ).as(expected)
end
end
describe "<r:link>" do
it "should render a link to the current page" do
page.should render('<r:link />').as('<a href="/assorted/">Assorted</a>')
end
it "should render its contents as the text of the link" do
page.should render('<r:link>Test</r:link>').as('<a href="/assorted/">Test</a>')
end
it "should pass HTML attributes to the <a> tag" do
expected = '<a href="/assorted/" class="test" id="assorted">Assorted</a>'
page.should render('<r:link class="test" id="assorted" />').as(expected)
end
it "should add the anchor attribute to the link as a URL anchor" do
page.should render('<r:link anchor="test">Test</r:link>').as('<a href="/assorted/#test">Test</a>')
end
it "should render a link for the current contextual page" do
expected = %{<a href="/parent/child/">Child</a> <a href="/parent/child-2/">Child 2</a> <a href="/parent/child-3/">Child 3</a> }
page(:parent).should render('<r:children:each><r:link /> </r:children:each>' ).as(expected)
end
it "should scope the link within the relative URL root" do
page(:assorted).should render('<r:link />').with_relative_root('/foo').as('<a href="/foo/assorted/">Assorted</a>')
end
end
describe "<r:snippet>" do
it "should render the contents of the specified snippet" do
page.should render('<r:snippet name="first" />').as('test')
end
it "should render an error when the snippet does not exist" do
page.should render('<r:snippet name="non-existant" />').with_error('snippet not found')
end
it "should render an error when not given a 'name' attribute" do
page.should render('<r:snippet />').with_error("`snippet' tag must contain `name' attribute")
end
it "should filter the snippet with its assigned filter" do
page.should render('<r:page><r:snippet name="markdown" /></r:page>').matching(%r{<p><strong>markdown</strong></p>})
end
it "should maintain the global page inside the snippet" do
page(:parent).should render('<r:snippet name="global_page_cascade" />').as("#{@page.title} " * @page.children.count)
end
it "should maintain the global page when the snippet renders recursively" do
page(:child).should render('<r:snippet name="recursive" />').as("Great GrandchildGrandchildChild")
end
it "should render the specified snippet when called as an empty double-tag" do
page.should render('<r:snippet name="first"></r:snippet>').as('test')
end
it "should capture contents of a double tag, substituting for <r:yield/> in snippet" do
page.should render('<r:snippet name="yielding">inner</r:snippet>').
as('Before...inner...and after')
end
it "should do nothing with contents of double tag when snippet doesn't yield" do
page.should render('<r:snippet name="first">content disappears!</r:snippet>').
as('test')
end
it "should render nested yielding snippets" do
page.should render('<r:snippet name="div_wrap"><r:snippet name="yielding">Hello, World!</r:snippet></r:snippet>').
as('<div>Before...Hello, World!...and after</div>')
end
it "should render double-tag snippets called from within a snippet" do
page.should render('<r:snippet name="nested_yields">the content</r:snippet>').
as('<snippet name="div_wrap">above the content below</snippet>')
end
it "should render contents each time yield is called" do
page.should render('<r:snippet name="yielding_often">French</r:snippet>').
as('French is Frencher than French')
end
end
it "should do nothing when called from page body" do
page.should render('<r:yield/>').as("")
end
it '<r:random> should render a randomly selected contained <r:option>' do
page.should render("<r:random> <r:option>1</r:option> <r:option>2</r:option> <r:option>3</r:option> </r:random>").matching(/^(1|2|3)$/)
end
it '<r:random> should render a randomly selected, dynamically set <r:option>' do
page(:parent).should render("<r:random:children:each:option:title />").matching(/^(Child|Child\ 2|Child\ 3)$/)
end
it '<r:comment> should render nothing it contains' do
page.should render('just a <r:comment>small </r:comment>test').as('just a test')
end
describe "<r:navigation>" do
it "should render the nested <r:normal> tag by default" do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/">
<r:normal><r:title /></r:normal>
</r:navigation>}
expected = %{Home Assorted Parent}
page.should render(tags).as(expected)
end
it "should render the nested <r:selected> tag for URLs that match the current page" do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/ | Radius: /radius/">
<r:normal><r:title /></r:normal>
<r:selected><strong><r:title/></strong></r:selected>
</r:navigation>}
expected = %{<strong>Home</strong> Assorted <strong>Parent</strong> Radius}
page(:parent).should render(tags).as(expected)
end
it "should render the nested <r:here> tag for URLs that exactly match the current page" do
tags = %{<r:navigation urls="Home: Boy: / | Assorted: /assorted/ | Parent: /parent/">
<r:normal><a href="<r:url />"><r:title /></a></r:normal>
<r:here><strong><r:title /></strong></r:here>
<r:selected><strong><a href="<r:url />"><r:title /></a></strong></r:selected>
<r:between> | </r:between>
</r:navigation>}
expected = %{<strong><a href="/">Home: Boy</a></strong> | <strong>Assorted</strong> | <a href="/parent/">Parent</a>}
page.should render(tags).as(expected)
end
it "should render the nested <r:between> tag between each link" do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/">
<r:normal><r:title /></r:normal>
<r:between> :: </r:between>
</r:navigation>}
expected = %{Home :: Assorted :: Parent}
page.should render(tags).as(expected)
end
it 'without urls should render nothing' do
page.should render(%{<r:navigation><r:normal /></r:navigation>}).as('')
end
it 'without a nested <r:normal> tag should render an error' do
page.should render(%{<r:navigation urls="something:here"></r:navigation>}).with_error( "`navigation' tag must include a `normal' tag")
end
it 'with urls without trailing slashes should match corresponding pages' do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius">
<r:normal><r:title /></r:normal>
<r:here><strong><r:title /></strong></r:here>
</r:navigation>}
expected = %{Home <strong>Assorted</strong> Parent Radius}
page.should render(tags).as(expected)
end
it 'should prune empty blocks' do
tags = %{<r:navigation urls="Home: Boy: / | Archives: /archive/ | Radius: /radius/ | Docs: /documentation/">
<r:normal><a href="<r:url />"><r:title /></a></r:normal>
<r:here></r:here>
<r:selected><strong><a href="<r:url />"><r:title /></a></strong></r:selected>
<r:between> | </r:between>
</r:navigation>}
expected = %{<strong><a href="/">Home: Boy</a></strong> | <a href="/archive/">Archives</a> | <a href="/documentation/">Docs</a>}
page(:radius).should render(tags).as(expected)
end
it 'should render text under <r:if_first> and <r:if_last> only on the first and last item, respectively' do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius">
<r:normal><r:if_first>(</r:if_first><a href="<r:url />"><r:title /></a><r:if_last>)</r:if_last></r:normal>
<r:here><r:if_first>(</r:if_first><r:title /><r:if_last>)</r:if_last></r:here>
<r:selected><r:if_first>(</r:if_first><strong><a href="<r:url />"><r:title /></a></strong><r:if_last>)</r:if_last></r:selected>
</r:navigation>}
expected = %{(<strong><a href=\"/\">Home</a></strong> <a href=\"/assorted\">Assorted</a> <a href=\"/parent\">Parent</a> Radius)}
page(:radius).should render(tags).as(expected)
end
it 'should render text under <r:unless_first> on every item but the first' do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius">
<r:normal><r:unless_first>> </r:unless_first><a href="<r:url />"><r:title /></a></r:normal>
<r:here><r:unless_first>> </r:unless_first><r:title /></r:here>
<r:selected><r:unless_first>> </r:unless_first><strong><a href="<r:url />"><r:title /></a></strong></r:selected>
</r:navigation>}
expected = %{<strong><a href=\"/\">Home</a></strong> > <a href=\"/assorted\">Assorted</a> > <a href=\"/parent\">Parent</a> > Radius}
page(:radius).should render(tags).as(expected)
end
it 'should render text under <r:unless_last> on every item but the last' do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius">
<r:normal><a href="<r:url />"><r:title /></a><r:unless_last> ></r:unless_last></r:normal>
<r:here><r:title /><r:unless_last> ></r:unless_last></r:here>
<r:selected><strong><a href="<r:url />"><r:title /></a></strong><r:unless_last> ></r:unless_last></r:selected>
</r:navigation>}
expected = %{<strong><a href=\"/\">Home</a></strong> > <a href=\"/assorted\">Assorted</a> > <a href=\"/parent\">Parent</a> > Radius}
page(:radius).should render(tags).as(expected)
end
end
describe "<r:find>" do
it "should change the local page to the page specified in the 'url' attribute" do
page.should render(%{<r:find url="/parent/child/"><r:title /></r:find>}).as('Child')
end
it "should render an error without the 'url' attribute" do
page.should render(%{<r:find />}).with_error("`find' tag must contain `url' attribute")
end
it "should render nothing when the 'url' attribute does not point to a page" do
page.should render(%{<r:find url="/asdfsdf/"><r:title /></r:find>}).as('')
end
it "should render nothing when the 'url' attribute does not point to a page and a custom 404 page exists" do
page.should render(%{<r:find url="/gallery/asdfsdf/"><r:title /></r:find>}).as('')
end
it "should scope contained tags to the found page" do
page.should render(%{<r:find url="/parent/"><r:children:each><r:slug /> </r:children:each></r:find>}).as('child child-2 child-3 ')
end
it "should accept a path relative to the current page" do
page(:great_grandchild).should render(%{<r:find url="../../../child-2"><r:title/></r:find>}).as("Child 2")
end
end
it '<r:escape_html> should escape HTML-related characters into entities' do
page.should render('<r:escape_html><strong>a bold move</strong></r:escape_html>').as('<strong>a bold move</strong>')
end
it '<r:rfc1123_date> should render an RFC1123-compatible date' do
page(:dated).should render('<r:rfc1123_date />').as('Wed, 11 Jan 2006 00:00:00 GMT')
end
describe "<r:breadcrumbs>" do
it "should render a series of breadcrumb links separated by >" do
expected = %{<a href="/">Home</a> > <a href="/parent/">Parent</a> > <a href="/parent/child/">Child</a> > <a href="/parent/child/grandchild/">Grandchild</a> > Great Grandchild}
page(:great_grandchild).should render('<r:breadcrumbs />').as(expected)
end
it "with a 'separator' attribute should use the separator instead of >" do
expected = %{<a href="/">Home</a> :: Parent}
page(:parent).should render('<r:breadcrumbs separator=" :: " />').as(expected)
end
it "with a 'nolinks' attribute set to 'true' should not render links" do
expected = %{Home > Parent}
page(:parent).should render('<r:breadcrumbs nolinks="true" />').as(expected)
end
it "with a relative URL root should scope links to the relative root" do
expected = '<a href="/foo/">Home</a> > Assorted'
page(:assorted).should render('<r:breadcrumbs />').with_relative_root('/foo').as(expected)
end
end
describe "<r:if_url>" do
describe "with 'matches' attribute" do
it "should render the contained block if the page URL matches" do
page.should render('<r:if_url matches="a.sorted/$">true</r:if_url>').as('true')
end
it "should not render the contained block if the page URL does not match" do
page.should render('<r:if_url matches="fancypants">true</r:if_url>').as('')
end
it "set to a malformatted regexp should render an error" do
page.should render('<r:if_url matches="as(sorted/$">true</r:if_url>').with_error("Malformed regular expression in `matches' argument of `if_url' tag: unmatched (: /as(sorted\\/$/")
end
it "without 'ignore_case' attribute should ignore case by default" do
page.should render('<r:if_url matches="asSorted/$">true</r:if_url>').as('true')
end
describe "with 'ignore_case' attribute" do
it "set to 'true' should use a case-insensitive match" do
page.should render('<r:if_url matches="asSorted/$" ignore_case="true">true</r:if_url>').as('true')
end
it "set to 'false' should use a case-sensitive match" do
page.should render('<r:if_url matches="asSorted/$" ignore_case="false">true</r:if_url>').as('')
end
end
end
it "with no attributes should render an error" do
page.should render('<r:if_url>test</r:if_url>').with_error("`if_url' tag must contain a `matches' attribute.")
end
end
describe "<r:unless_url>" do
describe "with 'matches' attribute" do
it "should not render the contained block if the page URL matches" do
page.should render('<r:unless_url matches="a.sorted/$">true</r:unless_url>').as('')
end
it "should render the contained block if the page URL does not match" do
page.should render('<r:unless_url matches="fancypants">true</r:unless_url>').as('true')
end
it "set to a malformatted regexp should render an error" do
page.should render('<r:unless_url matches="as(sorted/$">true</r:unless_url>').with_error("Malformed regular expression in `matches' argument of `unless_url' tag: unmatched (: /as(sorted\\/$/")
end
it "without 'ignore_case' attribute should ignore case by default" do
page.should render('<r:unless_url matches="asSorted/$">true</r:unless_url>').as('')
end
describe "with 'ignore_case' attribute" do
it "set to 'true' should use a case-insensitive match" do
page.should render('<r:unless_url matches="asSorted/$">true</r:unless_url>').as('')
end
it "set to 'false' should use a case-sensitive match" do
page.should render('<r:unless_url matches="asSorted/$" ignore_case="false">true</r:unless_url>').as('true')
end
end
end
it "with no attributes should render an error" do
page.should render('<r:unless_url>test</r:unless_url>').with_error("`unless_url' tag must contain a `matches' attribute.")
end
end
describe "<r:cycle>" do
it "should render passed values in succession" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" />').as('first second')
end
it "should return to the beginning of the cycle when reaching the end" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" /> <r:cycle values="first, second" />').as('first second first')
end
it "should use a default cycle name of 'cycle'" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" name="cycle" />').as('first second')
end
it "should maintain separate cycle counters" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="one, two" name="numbers" /> <r:cycle values="first, second" /> <r:cycle values="one, two" name="numbers" />').as('first one second two')
end
it "should reset the counter" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" reset="true"/>').as('first first')
end
it "should require the values attribute" do
page.should render('<r:cycle />').with_error("`cycle' tag must contain a `values' attribute.")
end
end
describe "<r:if_dev>" do
it "should render the contained block when on the dev site" do
page.should render('-<r:if_dev>dev</r:if_dev>-').as('-dev-').on('dev.site.com')
end
it "should not render the contained block when not on the dev site" do
page.should render('-<r:if_dev>dev</r:if_dev>-').as('--')
end
describe "on an included page" do
it "should render the contained block when on the dev site" do
page.should render('-<r:find url="/devtags/"><r:content part="if_dev" /></r:find>-').as('-dev-').on('dev.site.com')
end
it "should not render the contained block when not on the dev site" do
page.should render('-<r:find url="/devtags/"><r:content part="if_dev" /></r:find>-').as('--')
end
end
end
describe "<r:unless_dev>" do
it "should not render the contained block when not on the dev site" do
page.should render('-<r:unless_dev>not dev</r:unless_dev>-').as('--').on('dev.site.com')
end
it "should render the contained block when not on the dev site" do
page.should render('-<r:unless_dev>not dev</r:unless_dev>-').as('-not dev-')
end
describe "on an included page" do
it "should not render the contained block when not on the dev site" do
page.should render('-<r:find url="/devtags/"><r:content part="unless_dev" /></r:find>-').as('--').on('dev.site.com')
end
it "should render the contained block when not on the dev site" do
page.should render('-<r:find url="/devtags/"><r:content part="unless_dev" /></r:find>-').as('-not dev-')
end
end
end
describe "<r:status>" do
it "should render the status of the current page" do
status_tag = "<r:status/>"
page(:a).should render(status_tag).as("Published")
page(:hidden).should render(status_tag).as("Hidden")
page(:draft).should render(status_tag).as("Draft")
end
describe "with the downcase attribute set to 'true'" do
it "should render the lowercased status of the current page" do
status_tag_lc = "<r:status downcase='true'/>"
page(:a).should render(status_tag_lc).as("published")
page(:hidden).should render(status_tag_lc).as("hidden")
page(:draft).should render(status_tag_lc).as("draft")
end
end
end
describe "<r:if_ancestor_or_self>" do
it "should render the tag's content when the current page is an ancestor of tag.locals.page" do
page(:radius).should render(%{<r:find url="/"><r:if_ancestor_or_self>true</r:if_ancestor_or_self></r:find>}).as('true')
end
it "should not render the tag's content when current page is not an ancestor of tag.locals.page" do
page(:parent).should render(%{<r:find url="/radius"><r:if_ancestor_or_self>true</r:if_ancestor_or_self></r:find>}).as('')
end
end
describe "<r:unless_ancestor_or_self>" do
it "should render the tag's content when the current page is not an ancestor of tag.locals.page" do
page(:parent).should render(%{<r:find url="/radius"><r:unless_ancestor_or_self>true</r:unless_ancestor_or_self></r:find>}).as('true')
end
it "should not render the tag's content when current page is an ancestor of tag.locals.page" do
page(:radius).should render(%{<r:find url="/"><r:unless_ancestor_or_self>true</r:unless_ancestor_or_self></r:find>}).as('')
end
end
describe "<r:if_self>" do
it "should render the tag's content when the current page is the same as the local contextual page" do
page(:home).should render(%{<r:find url="/"><r:if_self>true</r:if_self></r:find>}).as('true')
end
it "should not render the tag's content when the current page is not the same as the local contextual page" do
page(:radius).should render(%{<r:find url="/"><r:if_self>true</r:if_self></r:find>}).as('')
end
end
describe "<r:unless_self>" do
it "should render the tag's content when the current page is not the same as the local contextual page" do
page(:radius).should render(%{<r:find url="/"><r:unless_self>true</r:unless_self></r:find>}).as('true')
end
it "should not render the tag's content when the current page is the same as the local contextual page" do
page(:home).should render(%{<r:find url="/"><r:unless_self>true</r:unless_self></r:find>}).as('')
end
end
describe "<r:meta>" do
it "should render <meta> tags for the description and keywords" do
page(:home).should render('<r:meta/>').as(%{<meta name="description" content="The homepage" /><meta name="keywords" content="Home, Page" />})
end
it "should render <meta> tags with escaped values for the description and keywords" do
page.should render('<r:meta/>').as(%{<meta name="description" content="sweet & harmonious biscuits" /><meta name="keywords" content="sweet & harmonious biscuits" />})
end
describe "with 'tag' attribute set to 'false'" do
it "should render the contents of the description and keywords" do
page(:home).should render('<r:meta tag="false" />').as(%{The homepageHome, Page})
end
it "should escape the contents of the description and keywords" do
page.should render('<r:meta tag="false" />').as("sweet & harmonious biscuitssweet & harmonious biscuits")
end
end
end
describe "<r:meta:description>" do
it "should render a <meta> tag for the description" do
page(:home).should render('<r:meta:description/>').as(%{<meta name="description" content="The homepage" />})
end
it "should render a <meta> tag with escaped value for the description" do
page.should render('<r:meta:description />').as(%{<meta name="description" content="sweet & harmonious biscuits" />})
end
describe "with 'tag' attribute set to 'false'" do
it "should render the contents of the description" do
page(:home).should render('<r:meta:description tag="false" />').as(%{The homepage})
end
it "should escape the contents of the description" do
page.should render('<r:meta:description tag="false" />').as("sweet & harmonious biscuits")
end
end
end
describe "<r:meta:keywords>" do
it "should render a <meta> tag for the keywords" do
page(:home).should render('<r:meta:keywords/>').as(%{<meta name="keywords" content="Home, Page" />})
end
it "should render a <meta> tag with escaped value for the keywords" do
page.should render('<r:meta:keywords />').as(%{<meta name="keywords" content="sweet & harmonious biscuits" />})
end
describe "with 'tag' attribute set to 'false'" do
it "should render the contents of the keywords" do
page(:home).should render('<r:meta:keywords tag="false" />').as(%{Home, Page})
end
it "should escape the contents of the keywords" do
page.should render('<r:meta:keywords tag="false" />').as("sweet & harmonious biscuits")
end
end
end
private
def page(symbol = nil)
if symbol.nil?
@page ||= pages(:assorted)
else
@page = pages(symbol)
end
end
def page_children_each_tags(attr = nil)
attr = ' ' + attr unless attr.nil?
"<r:children:each#{attr}><r:slug /> </r:children:each>"
end
def page_children_first_tags(attr = nil)
attr = ' ' + attr unless attr.nil?
"<r:children:first#{attr}><r:slug /></r:children:first>"
end
def page_children_last_tags(attr = nil)
attr = ' ' + attr unless attr.nil?
"<r:children:last#{attr}><r:slug /></r:children:last>"
end
def page_eachable_children(page)
page.children.select(&:published?).reject(&:virtual)
end
end
| joshfrench/radiant | spec/models/standard_tags_spec.rb | Ruby | mit | 51,194 |
module ParametresHelper
end
| Henrik41/jQuery-Validation-Engine-rails | thingo2/app/helpers/parametres_helper.rb | Ruby | mit | 28 |
class CreateMappableMaps < ActiveRecord::Migration
def change
create_table :mappable_maps do |t|
t.string :subject
t.string :attr
t.string :from
t.string :to
t.timestamps
end
end
end
| mikebannister/mappable | db/migrate/20110919042052_create_mappable_maps.rb | Ruby | mit | 226 |
export function mockGlobalFile() {
// @ts-ignore
global.File = class MockFile {
name: string;
size: number;
type: string;
parts: (string | Blob | ArrayBuffer | ArrayBufferView)[];
properties?: FilePropertyBag;
lastModified: number;
constructor(
parts: (string | Blob | ArrayBuffer | ArrayBufferView)[],
name: string,
properties?: FilePropertyBag
) {
this.parts = parts;
this.name = name;
this.size = parts.join('').length;
this.type = 'txt';
this.properties = properties;
this.lastModified = 1234567890000; // Sat Feb 13 2009 23:31:30 GMT+0000.
}
};
}
export function testFile(filename: string, size: number = 42) {
return new File(['x'.repeat(size)], filename, undefined);
}
| ProtonMail/WebClient | applications/drive/src/app/helpers/test/file.ts | TypeScript | mit | 879 |
package net.talayhan.android.vibeproject.Controller;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.ipaulpro.afilechooser.utils.FileUtils;
import net.talayhan.android.vibeproject.R;
import net.talayhan.android.vibeproject.Util.Constants;
import java.io.File;
import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.pedant.SweetAlert.SweetAlertDialog;
public class MainActivity extends Activity {
@InjectView(R.id.fileChooser_bt) Button mFileChooser_bt;
@InjectView(R.id.playBack_btn) Button mPlayback_bt;
@InjectView(R.id.chart_bt) Button mChart_bt;
private String videoPath;
private String vidAddress = "https://archive.org/download/ksnn_compilation_master_the_internet/ksnn_compilation_master_the_internet_512kb.mp4";
private SweetAlertDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mFileChooser_bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/* Progress dialog */
pDialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.NORMAL_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Network Type");
pDialog.setContentText("How would you like to watch video?");
pDialog.setConfirmText("Local");
pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
// Local
// Create the ACTION_GET_CONTENT Intent
Intent getContentIntent = FileUtils.createGetContentIntent();
Intent intent = Intent.createChooser(getContentIntent, "Select a file");
startActivityForResult(intent, Constants.REQUEST_CHOOSER);
sweetAlertDialog.dismissWithAnimation();
}
});
pDialog.setCancelText("Internet");
pDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
/* check the device network state */
if (!isOnline()){
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.WARNING_TYPE)
.setContentText("Your device is now offline!\n" +
"Please open your Network.")
.setTitleText("Open Network Connection")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
showNoConnectionDialog(MainActivity.this);
sweetAlertDialog.dismissWithAnimation();
}
})
.show();
}else {
// Create the intent to start video activity
Intent i = new Intent(MainActivity.this, LocalVideoActivity.class);
i.putExtra(Constants.EXTRA_ANSWER_IS_TRUE, vidAddress);
startActivity(i);
sweetAlertDialog.dismissWithAnimation();
}
}
});
pDialog.setCancelable(true);
pDialog.show();
}
});
mPlayback_bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.NORMAL_TYPE)
.setContentText("Please first label some video!\n" +
"Later come back here!.")
.setTitleText("Playback")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.dismissWithAnimation();
}
})
.show();
}
});
mChart_bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ChartRecyclerView.class);
startActivityForResult(i, Constants.REQUEST_CHART);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Constants.REQUEST_CHOOSER:
if (resultCode == RESULT_OK) {
final Uri uri = data.getData();
// Get the File path from the Uri
String path = FileUtils.getPath(this, uri);
Toast.makeText(this, "Choosen file: " + path,Toast.LENGTH_LONG).show();
// Alternatively, use FileUtils.getFile(Context, Uri)
if (path != null && FileUtils.isLocal(path)) {
File file = new File(path);
}
// Create the intent to start video activity
Intent i = new Intent(MainActivity.this, LocalVideoActivity.class);
i.putExtra(Constants.EXTRA_ANSWER_IS_TRUE,path);
startActivity(i);
}
break;
}
}
/*
* This method checks network situation, if device is airplane mode or something went wrong on
* network stuff. Method returns false, otherwise return true.
*
* - This function inspired by below link,
* http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-timeouts
*
* @return boolean - network state
* * * */
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
/**
* Display a dialog that user has no internet connection
* @param ctx1
*
* Code from: http://osdir.com/ml/Android-Developers/2009-11/msg05044.html
*/
public static void showNoConnectionDialog(Context ctx1) {
final Context ctx = ctx1;
final SweetAlertDialog builder = new SweetAlertDialog(ctx, SweetAlertDialog.SUCCESS_TYPE);
builder.setCancelable(true);
builder.setContentText("Open internet connection");
builder.setTitle("No connection error!");
builder.setConfirmText("Open wirless.");
builder.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
ctx.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
builder.dismissWithAnimation();
}
});
builder.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}else if (id == R.id.action_search){
openSearch();
return true;
}
return super.onOptionsItemSelected(item);
}
private void openSearch() {
Toast.makeText(this,"Clicked Search button", Toast.LENGTH_SHORT).show();
}
}
| stalayhan/vibeapp | app/src/main/java/net/talayhan/android/vibeproject/Controller/MainActivity.java | Java | mit | 9,208 |