answer
stringlengths
15
1.25M
'use strict'; function valuefy(value) { if (typeof value !== 'object') { return (typeof value === 'string') ? `"${value}"` : value; } let values = []; if (Array.isArray(value)) { for (const v of value) { values.push(valuefy(v)); } values = `[${values.join(',')}]`; } else { for (let v in value) { if ({}.hasOwnProperty.call(value, v)) { values.push(`"${v}":${valuefy(value[v])}`); } } values = `{${values.join(',')}}`; } return values; } function serialize(target) { if (!target || typeof target !== 'object') { throw new TypeError('Invalid type of target'); } let values = []; for (let t in target) { if ({}.hasOwnProperty.call(target, t)) { values.push(`${t}=${valuefy(target[t])}`); } } return values; } function extract(t, outter, onlyContent) { const start = onlyContent ? 1 : 0; const pad = onlyContent ? 0 : 1; return t.slice(start, t.lastIndexOf(outter) + pad); } function objectify(v) { if (v[0] === '{') { return JSON.parse(extract(v, '}')); } else if (v[0] === '[') { const set = []; const es = extract(v, ']', true); if (es[0] === '[' || es[0] === '{') { set.push(objectify(es)); } else { for (const e of es.split(',')) { set.push(objectify(e)); } } return set; } else if (v[0] === '"') { v = extract(v, '"', true); } return v; } function deserialize(values) { if (!values) { throw new TypeError('Invalid type of values'); } else if (!Array.isArray(values)) { values = [values]; } const target = {}; for (const v of values) { const fieldValue = v.split('=', 2); target[fieldValue[0]] = objectify(fieldValue[1]); } return target; } module.exports = { pairify: serialize, parse: deserialize };
<?php namespace App\Notifications\Mship; use App\Notifications\Notification; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; class <API key> extends Notification implements ShouldQueue { use Queueable; private $token; /** * Create a new notification instance. * * @return void */ public function __construct($token) { parent::__construct(); $this->token = $token; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { return ['mail', 'database']; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $subject = 'SSO Password Reset'; return (new MailMessage) ->from(config('mail.from.address'), 'VATSIM UK Web Services') ->subject($subject) ->view('emails.mship.security.reset_confirmation', ['subject' => $subject, 'recipient' => $notifiable, 'account' => $notifiable, 'token' => route('password.reset', $this->token)]); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return ['token' => $this->token]; } }
export default class TasksService { static async fetchTasks() { const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); await delay(1000); return [ { id: 0, description: "task1", status: "Active" }, { id: 1, description: "task2", status: "Active" }, ]; } }
// GUISlider.h // GUIPlayerView #import <UIKit/UIKit.h> @interface GUISlider : UISlider - (void)setSecondaryValue:(float)value; - (void)<API key>:(UIColor *)tintColor; @property (nonatomic, retain) NSNumber * thick; @end @interface GUISlider (extra) @property(nonatomic, assign) NSNumber* thickNess; @end
#ifndef RUBY_EXT_UTILS_HPP_ #define RUBY_EXT_UTILS_HPP_ 1 #include <functional> #include <ruby.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <typeinfo> #ifdef __GNUC__ #include <cxxabi.h> #endif template <typename T> static const char * type_name() { #ifdef __GNUC__ const int buf_size = 32; static char tname[buf_size]; if (tname[0] != 0) { return tname; } const std::type_info& id = typeid(T); int status; char *name = abi::__cxa_demangle(id.name(), NULL, 0, &status); if (name != NULL) { if (status == 0) { strncpy(tname, name, buf_size - 1); } else { strncpy(tname, id.name(), buf_size - 1); } free(name); } return tname; #else return typeid(T).name(); #endif } /* * undefined reference to ... [g++ (tdm-1) 4.5.2] */ // template<typename T> // static void // tmp_obj_free(T ptr) // if (ptr) { // delete ptr; // template<typename T> // static void // tmp_ary_free(T ptr) // if (ptr) { // delete[] ptr; template<typename T> static void tmp_obj_free(void *ptr) { if (ptr) { T obj = static_cast<T>(ptr); delete obj; } } template<typename T> static void tmp_ary_free(void *ptr) { if (ptr) { T obj = static_cast<T>(ptr); delete[] obj; } } template<typename T> static inline VALUE wrap_tmp_obj(T ptr) { return Data_Wrap_Struct(rb_cObject, 0, tmp_obj_free<T>, ptr); } template<typename T> static inline VALUE wrap_tmp_ary(T ptr) { return Data_Wrap_Struct(rb_cObject, 0, tmp_ary_free<T>, ptr); } void delete_tmp_obj(volatile VALUE *store); #define delete_tmp_ary(x) delete_tmp_obj(x) extern "C" VALUE rxu_run_functor(VALUE p); #define RXU_PROTECT_FUNC(func) ((VALUE (*)(VALUE))(func)) template<typename T> static inline VALUE _rb_protect(T func, int *state) { typedef std::function<VALUE ()> func_type; func_type f = func; return rb_protect(rxu_run_functor, reinterpret_cast<VALUE>(&f), state); } template<typename T1, typename T2> static inline VALUE _rb_rescue(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2)); } #if defined(_MSC_VER) && _MSC_VER <= 1800 template<VALUE& e1, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, NULL); } template<VALUE& e1, VALUE& e2, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, NULL); } template<VALUE& e1, VALUE& e2, VALUE& e3, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, NULL); } template<VALUE& e1, VALUE& e2, VALUE& e3, VALUE& e4, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, NULL); } template<VALUE& e1, VALUE& e2, VALUE& e3, VALUE& e4, VALUE& e5, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, e5, NULL); } #else template<VALUE&... exceptions, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), exceptions..., NULL); } #endif template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, NULL); } template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, NULL); } template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2, VALUE e3) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, NULL); } template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2, VALUE e3, VALUE e4) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, NULL); } template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2, VALUE e3, VALUE e4, VALUE e5) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, e5, NULL); } template<typename T1, typename T2> static inline VALUE _rb_ensure(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_ensure( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2)); } extern "C" int <API key>(VALUE key, VALUE val, VALUE p); #define RXU_FOREACH_FUNC(func) ((int (*)(ANYARGS))(func)) template<typename T> static inline void _rb_hash_foreach(VALUE obj, T func) { typedef std::function<int (VALUE, VALUE)> func_type; func_type f = func; rb_hash_foreach(obj, RXU_FOREACH_FUNC(<API key>), reinterpret_cast<VALUE>(&f)); } #endif /* RUBY_EXT_UTILS_HPP_ */
function Message(chat, body) { this._chat = chat; this._body = body; } Message.prototype.getChat = function() { return this._chat; }; Message.prototype.getBody = function() { return this._body; }; module.exports = Message;
<?php namespace PLL\SocialBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\<API key>; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Translation\TranslatorInterface; class PostType extends AbstractType { public function buildForm(<API key> $builder, array $options) { $builder ->add('content', TextareaType::class, array( 'required' => true, 'label' => false, )) ->add('save', SubmitType::class, array( 'label' => 'timelinepost.label.post', 'translation_domain' => 'forms', 'attr' => array( 'class' => 'post-btn w3-btn w3-theme', ) )) ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'PLL\SocialBundle\Entity\Post' )); } } ?>
package septemberpack.september; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import java.util.Random; public class Asteroid { Bitmap bitmap; private int line1x; private int line1y; private int line2x; private int line2y; private int line3x; private int line3y; private Random random; public Asteroid(Bitmap bmp){ this.bitmap = bmp; random = new Random(); line1x = random.nextInt(880); line2x = random.nextInt(880); line3x = random.nextInt(880); line1y = -random.nextInt(300); line2y = -random.nextInt(300) - 400; line3y = -random.nextInt(300) - 800; } public void draw(Canvas canvas){ canvas.drawBitmap(bitmap, line1x, line1y, null); canvas.drawBitmap(bitmap, line2x, line2y, null); canvas.drawBitmap(bitmap, line3x, line3y, null); } public void update(){ if(line1y > 1400) { line1y = -80; line1x = random.nextInt(880); } else if(line2y > 1400) { line2y = -80; line2x = random.nextInt(880); } else if(line3y > 1400) { line3y = -80; line3x = random.nextInt(880); } line1y += GamePanel.speed; line2y += GamePanel.speed; line3y += GamePanel.speed; } public Rect getAsteroid1(){ return new Rect(line1x, line1y, line1x + 100, line1y + 120); } public Rect getAsteroid2(){ return new Rect(line2x, line2y, line2x + 100, line2y + 120); } public Rect getAsteroid3(){ return new Rect(line3x, line3y, line3x + 100, line3y + 120); } }
import React from 'react'; import { shallow } from 'enzyme'; import UserProfile from '../UserProfile'; import Wrapper from '../Wrapper'; describe('<UserProfile />', () => { it('should render <Wrapper />', () => { const wrapper = shallow(<UserProfile />); expect(wrapper.find(Wrapper).length).toEqual(1); }); });
class <API key> < ActiveRecord::Migration[5.1] def change create_table :<API key> do |t| t.text :name t.timestamps end end end
## Examples: **As filters:** twig {{ subject | preg_filter(pattern, replacement, limit) }} {{ subject | preg_grep(pattern) }} {{ subject | preg_match(pattern) }} {{ subject | preg_quote(delimiter) }} {{ subject | preg_replace(pattern, replacement, limit) }} {{ subject | preg_split(pattern) }} **As functions:** twig {{ preg_filter(subject, pattern, replacement, limit) }} {{ preg_grep(subject, pattern) }} {{ preg_match(subject, pattern) }} {{ preg_quote(subject, delimiter) }} {{ preg_replace(subject, pattern, replacement, limit) }} {{ preg_split(subject, pattern) }} Please read the PHP docs for a more detailed explanation of all functions. **Usage Examples:** *Simple Word Replacement* twig {{ "This is a simple example." | preg_replace('/simple/', 'beautiful') }} will output: twig This is a beautiful example. *Whitespace cleaning up (Specifically from the results of a Twig macro)* twig {% macro generateItemUrl(item, falseLink) %} {% if (falseLink) or item.url is empty %} {% else %} {{ item.url }} {% endif %} {% endmacro %} <a href="{{ _self.generateItemUrl(item, false) | preg_replace('/\\s+/', ' ') | trim | raw }}">{{ item.name }}</a>
<ul class="menu-item"> <li class="home"><a href="/">{{ site.title }}</a></li> {% for link in site.data.navigation %} {% if link.url_en contains 'http' %} {% assign domain = '' %} {% else %} {% assign domain = site.url_en %} {% endif %} <li><a href="{{ domain }}{{ link.url_en }}" {% if link.url contains 'http' %}target="_blank"{% endif %}>{{ link.title_en }}</a></li> {% endfor %} </ul>
<?php namespace Davidsneal\MaxCDN\OAuth; class OAuthDataStore { function lookup_consumer($consumer_key) { // implement me } function lookup_token($consumer, $token_type, $token) { // implement me } function lookup_nonce($consumer, $token, $nonce, $timestamp) { // implement me } function new_request_token($consumer, $callback = null) { // return a new token attached to this consumer } function new_access_token($token, $consumer, $verifier = null) { // return a new access token attached to this consumer // for the user associated with this token if the request token // is authorized // should also invalidate the request token } }
import React from 'react'; import { ActivityIndicator, StyleSheet, Image, Text, View, ListView, TouchableOpacity } from 'react-native'; import Dimensions from 'Dimensions'; const {width, height} = Dimensions.get('window'); import globalVariables from '../globalVariables.js'; import LookCell from './LookCell.js'; import User from './User.js'; import DoneFooter from './DoneFooter.js'; import Icon from '<API key>/Ionicons'; const LookDetail = React.createClass({ getInitialState() { return { dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}), comments: [], next:true, pageNo:1, animating:true }; }, getDefaultProps() { return { look:{}, navigator:"", }; }, componentWillMount() { this.queryRromServer(1); }, getDataSource(comments) { // return false; return this.state.dataSource.cloneWithRows(comments); }, renderFooter() { if (!this.state.next) { return ( <DoneFooter/> ); } return <ActivityIndicator style={styles.scrollSpinner} animating={this.state.animating}/>; }, renderHeader() { return ( <LookCell look={this.props.look} navigator={this.props.navigator} onSelect={function(){}} userCell={true} /> ); }, onEndReached() { if(this.props.look.comments_count==0){ this.setState({ next:false, }); return; } if (this.state.next && !this.state.animating) { this.setState({ animating: true }); this.queryRromServer(this.state.pageNo); } }, onSelectUser(user) { this.props.navigator.push({ component: User, title: user.name, backButtonTitle:' ', passProps: { user:user, navigator:this.props.navigator, }, }); }, // <API key>: function(nextProps, nextState) { // console.log('LookDetail.js.<API key>'); // return JSON.stringify(nextState)!=JSON.stringify(this.state); renderRow(comments) { if(!comments.comment||!comments.comment.user){ return false; } return ( <TouchableOpacity activeOpacity={0.8} onPress={()=>this.onSelectUser(comments.comment.user)} style={styles.flexContainer}> <Image source={{uri:comments.comment.user.photo}} style={styles.avatar}/> <View style={styles.commentBody}> <View style={styles.commentHeader}> <View style={{flex:1}}> <Text style={styles.userName}>{comments.comment.user.name}</Text> </View> <View style={styles.timeView}> <Icon name="ios-clock-outline" color={globalVariables.textBase} size={15}/> <Text style={styles.time}> {globalVariables.formatDateToString(comments.comment.created_at)}</Text> </View> </View> <Text style={styles.commentText}>{comments.comment.body}</Text> </View> </TouchableOpacity> ); }, render() { console.log(new Date()-0); console.log('LookDetail.js.js-render'); return ( <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} onEndReached={this.onEndReached} renderHeader={this.renderHeader} renderFooter={this.renderFooter} <API key>={10} <API key>={false} keyboardDismissMode='on-drag' <API key>={false} <API key>={true} style={styles.container} /> ); }, queryRromServer(page) { globalVariables.queryRromServer(globalVariables.apiLookServer+this.props.look.id+'/comments/'+(page||1),this.processsResults); }, processsResults(data) { if (!data||!data.comments||!data.comments.length) { this.setState({ animating: false, next:false, }); return; } var newComments= this.state.comments.concat(data.comments); var next=newComments.length>=this.props.look.comments_count?false:true; this.setState({ comments: newComments, animating: false, dataSource: this.getDataSource(newComments), pageNo: this.state.pageNo+1, next:next, }); } }); const styles = StyleSheet.create({ container: { paddingTop: 64, backgroundColor: globalVariables.background, }, flexContainer: { opacity:0.97, padding: 10, flexDirection: 'row', justifyContent: 'flex-start', }, commentBody: { flex: 1, flexDirection: "column", justifyContent: "center", }, commentHeader: { flexDirection: "row", alignItems: "flex-start" }, userName: { color:globalVariables.base, // fontSize:12, }, timeView:{ // width:50, flexDirection: "row", alignItems:'center', marginRight:5, }, time:{ color:globalVariables.textBase, fontSize:12, }, commentText: { // fontSize:12, marginTop:8, flexDirection: "row", color:globalVariables.textBase, }, avatar: { borderRadius: 18, width: 36, height: 36, marginRight: 10, marginLeft: 5, backgroundColor:globalVariables.textBase2, }, scrollSpinner: { marginVertical: 20, }, }); export default LookDetail;
#!/usr/bin/env python import sys import os from treestore import Treestore try: taxonomy = sys.argv[1] except: taxonomy = None t = Treestore() treebase_uri = 'http://purl.org/phylo/treebase/phylows/tree/%s' tree_files = [x for x in os.listdir('trees') if x.endswith('.nex')] base_uri = 'http: tree_list = set(t.list_trees()) for tree_uri in tree_list: if not 'TB2_' in tree_uri: continue tree_id = t.id_from_uri(tree_uri) tb_uri = treebase_uri % (tree_id.replace('_', ':')) print tree_id, tb_uri t.annotate(tree_uri, annotations='?tree bibo:cites <%s> .' % tb_uri)
<?php namespace Anonym\Facades; use Anonym\Patterns\Facade; /** * Class Validation * @package Anonym\Facades */ class Validation extends Facade { /** * return the validation facade * * @return string */ protected static function getFacadeClass(){ return 'validation'; } }
{% extends 'swp/base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="page-header"> <h1>{{ event.title }}</h1> </div> {% if user.is_authenticated %} <form action="{% url 'new_event' event.slug.hex %}" method="POST" enctype="multipart/form-data" class="form-inline" > {% csrf_token %} <div class="form-group"> <input type="text" name="caption" value="" placeholder="Caption" required="required" class="form-control" autocomplete="off" /> </div> <div class="form-group"> <label for="new-photo-original">Original</label> <input id="new-photo-original" type="file" name="original" required="required" class="form-control" /> </div> <div class="form-group"> <label for="new-photo-enhanced">Enhanced (optional)</label> <input id="new-photo-enhanced" type="file" name="enhanced" class="form-control" /> </div> <button type="submit" class="btn btn-primary">Upload</button> </form> {% endif %} <div class="row"> {% for photo in photos %} <div class="col-xs-12 col-md-4"> <a href="#" data-toggle="modal" data-target="#<API key>" ><img src="{% static photo.image.thumbnail_path %}" alt="{{ photo.caption }}" class="swp-thumbnail" /></a> <br/> {% if user.is_authenticated %} {% if photo.enhanced %} <div class="btn-group" role="group"> <a href="{% url 'original_file' photo.original.slug.hex %}" role="button" class="btn btn-default btn-sm" >Original</a> <a href="{% url 'original_file' photo.enhanced.slug.hex %}" role="button" class="btn btn-default btn-sm" >Full resolution</a> </div> {% else %} <a href="{% url 'original_file' photo.original.slug.hex %}" role="button" class="btn btn-default btn-sm" >Full resolution</a> {% endif %} {% endif %} </div> {% endfor %} </div> </div> <div class="modal fade" id="<API key>" tabindex="-1" role="dialog" > <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" ><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Image Slideshow</h4> </div> <div class="modal-body"> <div id="<API key>" class="carousel slide" data-ride="carousel" data-interval="false" > <!-- Indicators --> <ol class="carousel-indicators"> {% for photo in photos %} <li data-target="SWPCarousel" data-slide-to="{{ forloop.counter0 }}" {% if forloop.counter0 == 0 %} class="active" {% endif %} ></li> {% endfor %} </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> {% for photo in photos %} <div class="item {% if forloop.counter0 == 0 %}active{% endif %}" > <img src="{% static photo.image.image_path %}" class="swp-carousel-image" alt="{{ photo.caption }}" /> <div class="carousel-caption"> <h3>{{ photo.caption }}</h3> </div> </div> {% endfor %} </div> <!-- Left and right controls --> <a class="left carousel-control" href="#<API key>" role="button" data-slide="prev" > <span class="glyphicon <API key>" aria-hidden="true" ></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#<API key>" role="button" data-slide="next" > <span class="glyphicon <API key>" aria-hidden="true" ></span> <span class="sr-only">Next</span> </a> </div> </div> </div> </div> </div> {% endblock %}
package queier import ( "github.com/julienschmidt/httprouter" "net/http" "encoding/json" "fmt" "strconv" "broker-gateway/entities" "github.com/satori/go.uuid" ) type Router interface { Start(port int) } type router struct { q Querier http *httprouter.Router } func NewRouter(q Querier) Router { r := httprouter.New() rte:= &router{ q: q, http: r, } rte.register() return rte } func (rte *router)futures(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { futures := rte.q.Futures() echo(w, futures) } //func (rte *router)ordersByFirmId(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // firmId,_ := strconv.Atoi(ps.ByName("firmId")) // orders := rte.q.Orders(firmId) // res, err := json.Marshal(orders) // if err != nil { // fmt.Println(err) // w.Write(res) //func (rte *router)ordersByFirmIdAndId(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // firmId,_ := strconv.Atoi(ps.ByName("firmId")) // order := rte.q.OrderById(firmId,ps.ByName("id")) // res, err := json.Marshal(order) // if err != nil { // fmt.Println(err) // w.Write(res) //func (rte *router) consignations(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // firmId,_ := strconv.Atoi(ps.ByName("firmId")) // rtn := rte.q.Consignations(firmId) // res, err := json.Marshal(rtn) // if err != nil { // fmt.Println(err) // w.Write(res) //func (rte *router)<API key>(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // firmId,_ := strconv.Atoi(ps.ByName("firmId")) // order := rte.q.ConsignationById(firmId,ps.ByName("id")) // res, err := json.Marshal(order) // if err != nil { // fmt.Println(err) // w.Write(res) //func (rte *router)<API key>(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // futureId,_ := strconv.Atoi(ps.ByName("id")) // rtn := rte.q.Quotations(futureId) // res, err := json.Marshal(rtn) // if err != nil { // fmt.Println(err) // w.Write(res) func echo(w http.ResponseWriter, entity interface{}) { if entity == nil { w.Write([]byte("{}")) return } res, err := json.Marshal(entity) if err != nil { fmt.Println(err) } w.Header().Set("<API key>","*") w.Write(res) } func (rte *router) register() { // For firm rte.http.GET("/futures",func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { futures := rte.q.Futures() echo(w, futures) }) rte.http.GET("/futures/:id", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { id,_ := strconv.Atoi(p.ByName("id")) limit,_ := strconv.Atoi(h.URL.Query().Get("limit")) offset,_ := strconv.Atoi(h.URL.Query().Get("offset")) echo(w,rte.q.Quotations(id,limit,offset)) }) rte.http.GET("/firms/:firmId/orders", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { id,_ := strconv.Atoi(p.ByName("firmId")) limit,_ := strconv.Atoi(h.URL.Query().Get("limit")) offset,_ := strconv.Atoi(h.URL.Query().Get("offset")) res := rte.q.Orders(id,limit,offset) for i:=0;i<len(res) ;i++ { res[i] = entities.TransformForFirm(res[i],id) } echo(w,res) }) rte.http.GET("/firms/:firmId/orders/:id",func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { firmid,_ := strconv.Atoi(p.ByName("firmId")) res := rte.q.OrderById(firmid, p.ByName("id")) if uuid.Equal(res.ID,uuid.FromBytesOrNil(nil)) { echo(w, nil) } else { echo(w,res) } }) rte.http.GET("/firms/:firmId/consignations",func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { id,_ := strconv.Atoi(p.ByName("firmId")) limit,_ := strconv.Atoi(h.URL.Query().Get("limit")) offset,_ := strconv.Atoi(h.URL.Query().Get("offset")) res := rte.q.Consignations(id,limit,offset) echo(w,res) }) rte.http.GET("/firms/:firmId/consignations/:id",func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { firmid,_ := strconv.Atoi(p.ByName("firmId")) res := rte.q.ConsignationById(firmid, p.ByName("id")) if uuid.Equal(res.ID,uuid.FromBytesOrNil(nil)) { echo(w, nil) } else { echo(w,res) } }) // For admin rte.http.GET("/admin/orders", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { limit,_ := strconv.Atoi(h.URL.Query().Get("limit")) offset,_ := strconv.Atoi(h.URL.Query().Get("offset")) echo(w,rte.q.AllOrders(limit,offset)) }) rte.http.GET("/admin/consignations", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { limit,_ := strconv.Atoi(h.URL.Query().Get("limit")) offset,_ := strconv.Atoi(h.URL.Query().Get("offset")) echo(w,rte.q.AllConsignations(limit,offset)) }) rte.http.PUT("/admin/commissions/:id", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { firmId,_ :=strconv.Atoi(h.URL.Query().Get("firmId")) futureId,_ := strconv.Atoi(h.URL.Query().Get("futureId")) orderType,_ := strconv.Atoi(h.URL.Query().Get("orderType")) percent,_ := strconv.Atoi(h.URL.Query().Get("percent")) id,_ := strconv.Atoi(p.ByName("id")) comm := entities.Commission{ ID: id, FirmId: firmId, FutureId: futureId, OrderType: orderType, CommissionPercent: percent, } rte.q.Save(&comm) echo(w, comm) }) rte.http.GET("/admin/commissions", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { var res []entities.Commission rte.q.Query().Find(&res) echo(w, res) }) rte.http.POST("/admin/commissions", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { firmId,_ :=strconv.Atoi(h.URL.Query().Get("firmId")) futureId,_ := strconv.Atoi(h.URL.Query().Get("futureId")) orderType,_ := strconv.Atoi(h.URL.Query().Get("orderType")) id,_ := strconv.Atoi(p.ByName("id")) percent,_ := strconv.Atoi(h.URL.Query().Get("percent")) comm := entities.Commission{ ID: id, FirmId: firmId, FutureId: futureId, OrderType: orderType, CommissionPercent: percent, } rte.q.Save(&comm) echo(w, comm) }) rte.http.GET("/admin/firmFutures", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { var res []entities.FirmFuture rte.q.Query().Find(res) echo(w, res) }) } func (r *router) Start(port int) { http.ListenAndServe(":"+strconv.Itoa(port),r.http) }
:: Sample batch script for Post-Job Bot Event :: If you enable 'For all commands, use job details as arguments' :: some details about the just-finished job will be appended to the :: command as arguments. :: :: Argument order is as follows for render operations after each job completes :: %1 => The row index in the spreadsheet. This is always `null` when Bot is enabled. :: %2 => The value of the job's ID column if it has one, `null` if no ID value. :: %3 => The value of the job's devised output name. :: %4 => Absolute path to the final rendered file if it was rendered. :: %5 => Absolute path to the folder containing the rendered file. :: %6 => Absolute path to the processed AE project file. :: %7 => Absolute path to the folder containing the processed AE project file. :: %8 => Absolute path to a .json file containing all job's column values :: :: Provided for your personal or commercial use by Dataclay, LLC @ECHO OFF SET log=%7\post-job.log For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b) For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b) echo echo Job completed on %mydate% @ %mytime% >> %log% echo Rendered job with ID %2 to %4 >> %log% echo Job details as JSON are found in file %8 >> %log% echo( >> %log%
<?php class maPrivileges{ public static function AuthorizedAccess($sUsercase, $sType){ if(Session::CheckAuthentication()){ return (Storage::Get("user.root", false)) ? true : Storage::Get("privilege.{$sType}.{$sUsercase}", false); } else{ Output::Redirect(Storage::Join("route.root", "login")); return false; } } public static function SavePrivileges($iID){ $oDb = Db::backend(); $iID = intval($iID); $aStorage = Storage::GetList(); $aData = array(); foreach($aStorage as $sKey => $mValue){ if(substr($sKey, 0, 4) == "put.") $aData[str_replace("put.", "", $sKey)] = $mValue; } if(count($aData) > 0 && $iID > 0) $oDb->administrators->Update(array("privilegios" => json_encode($aData)), array("id" => $iID), 1); ioBackendController::ReturnAjax(true); } public static function GetPrivileges($iID){ $iID = intval($iID); if($iID){ $oDb = Db::backend(); $oDb->administrators->Select("privilegios") ->Filter("id", $iID) ->Execute(function($aData, $mError){ $aPrivileges = json_decode($aData[0]["privilegios"], true); if(count($aPrivileges) > 0) foreach($aPrivileges as $iKey => $mItem) $aPrivileges[$iKey] = ($mItem == "true"); $aPrivileges = (empty($aPrivileges)) ? json_encode(array()) : json_encode($aPrivileges); die($aPrivileges); }); } else{ die(json_encode(array())); } } public static function LoadPrivileges(){ //if(!empty(Session::Get("user.privileges", ""))){ $aPrivileges = json_decode(Session::Get("user.privileges", array()), true); if($aPrivileges != null) foreach($aPrivileges as $sKey => $sValue) Storage::Set("privilege.".str_replace("_", ".", $sKey), ($sValue == "true")); } }
var cv = require('../lib/opencv'); var COLOR = [0, 255, 0]; // default red var thickness = 2; // default 1 cv.readImage('./files/mona.png', function(err, im) { if (err) throw err; if (im.width() < 1 || im.height() < 1) throw new Error('Image has no size'); im.detectObject('../data/<API key>.xml', {}, function(err, faces) { if (err) throw err; for (var i = 0; i < faces.length; i++) { var face = faces[i]; im.rectangle([face.x, face.y], [face.width, face.height], COLOR, 2); } im.save('./tmp/<API key>.png'); console.log('Image saved to ./tmp/<API key>.png'); }); });
// SproutCore -- JavaScript Application Framework sc_require('controllers/object'); sc_require('mixins/selection_support'); sc_require('private/tree_item_observer'); /** @class A TreeController manages a tree of model objects that you might want to display in the UI using a collection view. For the most part, you should work with a TreeController much like you would an ObjectController, except that the TreeController will also provide an arrangedObjects property that can be used as the content of a CollectionView. TODO: Document More @extends SC.ObjectController @extends SC.SelectionSupport @since SproutCore 1.0 */ SC.TreeController = SC.ObjectController.extend(SC.SelectionSupport, /** @scope SC.TreeController.prototype */ { // PROPERTIES /** Set to YES if you want the top-level items in the tree to be displayed as group items in the collection view. @property {Boolean} */ treeItemIsGrouped: NO, /** If your content support expanding and collapsing of content, then set this property to the name of the key on your model that should be used to determine the expansion state of the item. The default is "treeItemIsExpanded" @property {String} */ <API key>: "treeItemIsExpanded", /** Set to the name of the property on your content object that holds the children array for each tree node. The default is "treeItemChildren". @property {String} */ treeItemChildrenKey: "treeItemChildren", /** Returns an SC.Array object that actually will represent the tree as a flat array suitable for use by a CollectionView. Other than binding this property as the content of a CollectionView, you generally should not use this property directly. Instead, work on the tree content using the TreeController like you would any other ObjectController. @property {SC.Array} */ arrangedObjects: function() { var ret, content = this.get('content'); if (content) { ret = SC.TreeItemObserver.create({ item: content, delegate: this }); } else ret = null; // empty! this.<API key> = ret ; return ret ; }.property().cacheable(), // PRIVATE /** @private Manually invalidate the arrangedObjects cache so that we can teardown any existing value. We do it via an observer so that this will fire immediately instead of waiting on some other component to get arrangedObjects again. */ <API key>: function() { this.propertyWillChange('arrangedObjects'); var ret = this.<API key>; if (ret) ret.destroy(); this.<API key> = null; this.propertyDidChange('arrangedObjects'); }.observes('content', '<API key>', 'treeItemChildrenKey', 'treeItemIsGrouped'), <API key>: function() { this.<API key>(); }.observes('*arrangedObjects.[]'), /** @private Returns the first item in arrangeObjects that is not a group. This uses a brute force approach right now; we assume you probably don't have a lot of groups up front. */ <API key>: function() { var objects = this.get('arrangedObjects'), indexes, len, idx = 0; if (!objects) return null; // fast track indexes = objects.contentGroupIndexes(null, objects); len = objects.get('length'); while(indexes.contains(idx) && (idx<len)) idx++; return idx>=len ? null : objects.objectAt(idx); }.property() });
title: Custom Login description: This tutorial will show you how to use the Auth0 Ionic SDK to add authentication and authorization to your mobile app. <%= include('../../_includes/_package', { githubUrl: 'https://github.com/auth0-samples/auth0-ionic-samples', pkgOrg: 'auth0-samples', pkgRepo: 'auth0-ionic-samples', pkgBranch: 'master', pkgPath: '02-Custom-Login', pkgFilePath: '02-Custom-Login/www/app/auth0.variables.js', pkgType: 'replace' }) %> ::: panel-info Running the Sample At any point in time you can run this sample by going to the `02-Custom-Login` folder of the sample project and running `ionic serve` ::: The previous step explained how you can log users into your application using the Lock Widget. You do not have to use Lock, and can instead create a custom login page and log the user in using a username and password they supply through a customer user interface. If you are using social logins, you can also launch the login screen for a particular social login provider directly from your Ionic application. 1. Update references The custom login uses the Auth0.js library to sign a user in, so you should therefor reference this library instead of the Lock widget in your `index.html`. Replace the existing reference to `lib/auth0-lock/build/auth0-lock.js` with `lib/auth0.js/build/auth0.js`: ${snippet(meta.snippets.referencescustom)} 2. Implement the login For the login view you must display a Username and Password field to allow the user to sign in with their email address and password, and also display a button which will allow the user to sign in with their Google account. Go ahead and update your `login.html` you did in Step 1: ${snippet(meta.snippets.loginviewcustom)} Also change the `LoginController` to sign the user in with the supplied `username` and `password` fields, or alternatively launch the Google login dialog when the user clicks on the **Login with Google** button: ${snippet(meta.snippets.logincustom)} Notice that in the `onLoginSuccess` method, which is called when a user successfully authenticates, the `profile`, `token`, `accessToken` and `refreshToken` values are saved to Local storage. These values can be retrieve from Local storage at a later stage, for example when you want to display the user's profile information which will be done in Step 3.
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using Pfz.AnimationManagement; using Pfz.AnimationManagement.Abstract; using Pfz.AnimationManagement.Animations; using Pfz.AnimationManagement.Wpf; namespace WpfSample { <summary> Interaction logic for MainWindow.xaml </summary> public partial class MainWindow : Window { private IAnimation[] _basicAnimations; private IAnimation[] <API key>; internal IAnimation _animation; private ReadOnlyCollection<BitmapFrame> _waitingCharacter; private ReadOnlyCollection<BitmapFrame> <API key>; public MainWindow() { InitializeComponent(); Pfz.AnimationManagement.Wpf.Initializer.Initialize(); tabItemBasic.<API key> += (a, b) => _SetBasicAnimation(); tabItemIntermediary.<API key> += (a, b) => <API key>(); _basicAnimations = new IAnimation[] { // Range AnimationBuilder.Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)), // Accelerating Start AnimationBuilder. <API key>(1). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). <API key>(), // Deaccelerating End AnimationBuilder. <API key>(1, 3). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). <API key>(), // Multiple time multipliers AnimationBuilder. <API key>(0.1). Add(AnimationBuilder.Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value))). MultiplySpeed(1, 1). KeepSpeed(1). MultiplySpeed(0.1, 1). <API key>(), // Color Range AnimationBuilder.Range(Colors.Black, Colors.Blue, 1, (value) => circle.Fill = new SolidColorBrush(value)), // Many Color Ranges AnimationBuilder. BeginRanges((value) => circle.Fill = new SolidColorBrush(value), Colors.Black). To(Colors.Blue, 1). To(Colors.Red, 1). To(Colors.Green, 1). To(Colors.Yellow, 1). To(Colors.Magenta, 1). To(Colors.Black, 1). EndRanges(), // Parallel Animation AnimationBuilder. BeginParallel(). BeginLoop(). BeginRanges((value) => circle.Fill = new SolidColorBrush(value), Colors.Black). To(Colors.Blue, 1). To(Colors.Red, 1). To(Colors.Green, 1). To(Colors.Yellow, 1). To(Colors.Magenta, 1). To(Colors.Black, 1). EndRanges(). EndLoop(). BeginLoop(). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). EndLoop(). EndParallel(), // Sequential Animation AnimationBuilder. BeginSequence(). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). Range(Colors.Black, Colors.Green, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(0, 450, 3, (value) => Canvas.SetTop(circle, value)). Range(Colors.Green, Colors.Red, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(450, 0, 3, (value) => Canvas.SetLeft(circle, value)). Range(Colors.Red, Colors.Blue, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(450, 0, 3, (value) => Canvas.SetTop(circle, value)). Range(Colors.Blue, Colors.Black, 1, (value) => circle.Fill = new SolidColorBrush(value)). EndSequence(), // Sequential Animation + Multiple Speeds AnimationBuilder. <API key>(). KeepSpeed(1). MultiplySpeed(2, 3). KeepSpeed(1). MultiplySpeed(0.5, 2). KeepSpeedUntilEnd(). BeginSequence(). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). Range(Colors.Black, Colors.Green, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(0, 450, 3, (value) => Canvas.SetTop(circle, value)). Range(Colors.Green, Colors.Red, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(450, 0, 3, (value) => Canvas.SetLeft(circle, value)). Range(Colors.Red, Colors.Blue, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(450, 0, 3, (value) => Canvas.SetTop(circle, value)). Range(Colors.Blue, Colors.Black, 1, (value) => circle.Fill = new SolidColorBrush(value)). EndSequence(). <API key>(), // Imperative Animation new ImperativeAnimation(<API key>()), // Frame-by-Frame Animation new ImperativeAnimation(<API key>()) }; AnimationManager.Add(new <API key>(this)); <API key>.SelectionChanged += <API key>; _SetBasicAnimation(); bool isGoing = true; _waitingCharacter = _LoadCharacter("Images\\Waiting.gif"); <API key> = _LoadCharacter("Images\\MoveForward.gif"); <API key> = new IAnimation[] { // Animate Character AnimationBuilder.RangeBySpeed(0, _waitingCharacter.Count-1, 10, (index) => imageCharacter.Source = _waitingCharacter[index]), // Move Character AnimationBuilder. BeginParallel(). BeginLoop(). RangeBySpeed(0, <API key>.Count-1, 10, (index) => imageCharacter.Source = <API key>[index]). EndLoop(). BeginLoop(). RangeBySpeed(0, 400, 70, (value) => imageCharacter.Left = value). EndLoop(). EndParallel(), // Move (Frame-by-Frame) new ImperativeAnimation(_MoveFrameByFrame(<API key>)), // Go and Return AnimationBuilder. BeginSequence(). Add(() => isGoing = true). BeginParallel(). <API key>(() => !isGoing). BeginLoop(). // we need to loop the animation or else it will do a single "full-step" and then will // only move forward without walking. But we need to end the animation sometime... we // can cound the steps (bad, as the animation does not end at an exact step) or we can // put a premature end over the entire loop (good). RangeBySpeed(0, <API key>.Count-1, 10, (index) => imageCharacter.Source = <API key>[index]). EndLoop(). <API key>(). BeginSequence(). RangeBySpeed(0, 400, 70, (value) => imageCharacter.Left = value). Add(() => isGoing = false). EndSequence(). EndParallel(). BeginParallel(). <API key>(() => isGoing). BeginLoop(). RangeBySpeed(<API key>.Count-1, 0, 10, (index) => imageCharacter.Source = <API key>[index]). EndLoop(). <API key>(). BeginSequence(). RangeBySpeed(400, 0, 70, (value) => imageCharacter.Left = value). Add(() => isGoing = true). EndSequence(). EndParallel(). EndSequence(), // Go, Turn and Return AnimationBuilder. BeginSequence(). Add(() => isGoing = true). BeginParallel(). <API key>(() => !isGoing). BeginLoop(). // we need to loop the animation or else it will do a single "full-step" and then will // only move forward without walking. But we need to end the animation sometime... we // can cound the steps (bad, as the animation does not end at an exact step) or we can // put a premature end over the entire loop (good). RangeBySpeed(0, <API key>.Count-1, 10, (index) => imageCharacter.Source = <API key>[index]). EndLoop(). <API key>(). BeginSequence(). RangeBySpeed(0, 400, 70, (value) => imageCharacter.Left = value). Add(() => isGoing = false). EndSequence(). EndParallel(). Range(1.0, -1.0, 1, (value) => imageCharacter.ScaleX = value). BeginParallel(). <API key>(() => isGoing). BeginLoop(). // Different from the last full-animation, we continue "going forward". RangeBySpeed(0, <API key>.Count-1, 10, (index) => imageCharacter.Source = <API key>[index]). EndLoop(). <API key>(). BeginSequence(). RangeBySpeed(400, 0, 70, (value) => imageCharacter.Left = value). Add(() => isGoing = true). EndSequence(). EndParallel(). Range(-1.0, 1.0, 1, (value) => imageCharacter.ScaleX = value). EndSequence(), // Go, Turn and Return (* walking while turning). // This animation is similar to the previous 2, but in this case the character is always walking, even // when the animation is "turning" to the opposite side. AnimationBuilder. BeginParallel(). BeginLoop(). RangeBySpeed(0, <API key>.Count-1, 10, (index) => imageCharacter.Source = <API key>[index]). EndLoop(). BeginLoop(). BeginSequence(). RangeBySpeed(0, 400, 70, (value) => imageCharacter.Left = value). Range(1.0, -1.0, 1, (value) => imageCharacter.ScaleX = value). RangeBySpeed(400, 0, 70, (value) => imageCharacter.Left = value). Range(-1.0, 1.0, 1, (value) => imageCharacter.ScaleX = value). EndSequence(). EndLoop(). EndParallel() }; <API key>.SelectionChanged += <API key>; } private IEnumerable<IAnimation> <API key>() { Random random = new Random(); while(true) { Point origin = new Point(Canvas.GetLeft(circle), Canvas.GetTop(circle)); Point destination = new Point(random.Next(450), random.Next(450)); yield return AnimationBuilder.RangeBySpeed(origin, destination, 150, _SetLeftAndTop); } } private void _SetLeftAndTop(Point point) { Canvas.SetLeft(circle, point.X); Canvas.SetTop(circle, point.Y); } private IEnumerable<IAnimation> <API key>() { var helper = <API key>.CreateByFps(100); while(true) { double yPosition = 0; double xPosition = 0; double ySpeed = 0.5; while(yPosition < 500) { xPosition++; yPosition += ySpeed; ySpeed += 0.1; Canvas.SetLeft(circle, xPosition); Canvas.SetTop(circle, yPosition); yield return helper.WaitNextFrame(); } } } private void <API key>(object sender, <API key> e) { _SetBasicAnimation(); } private void _SetBasicAnimation() { Canvas.SetLeft(circle, 0); Canvas.SetTop(circle, 0); circle.Fill = Brushes.Black; if (_animation != null) _animation.Reset(); _animation = _basicAnimations[<API key>.SelectedIndex]; } private void <API key>(object sender, <API key> e) { <API key>(); } private void <API key>() { imageCharacter.Left = 0; imageCharacter.Top = 0; imageCharacter.ScaleX = 1; if (_animation != null) _animation.Reset(); _animation = <API key>[<API key>.SelectedIndex]; } private ReadOnlyCollection<BitmapFrame> _LoadCharacter(string path) { using(var stream = File.OpenRead(path)) { var decoder = GifBitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); var frames = decoder.Frames; return frames; } } private IEnumerable<IAnimation> _MoveFrameByFrame(ReadOnlyCollection<BitmapFrame> character) { var helper = <API key>.CreateByFps(80); int frameCount = character.Count*7; int frameIndex = 0; imageCharacter.Top = canvasIntermediary.ActualHeight - character[0].Height; while(true) { for(int left=0; left<400; left++) { frameIndex++; if (frameIndex >= frameCount) frameIndex = 0; imageCharacter.Source = character[frameIndex/7]; imageCharacter.Left = left; yield return helper.WaitNextFrame(); } } } private void <API key>(object sender, <API key> e) { if (_animation != null) _animation.Reset(); _animation = new ImperativeAnimation(_AdvancedAnimation()); } private int _direction = 0; private bool _isUpPressed; private IEnumerable<IAnimation> _AdvancedAnimation() { var helper = <API key>.CreateByFps(80); canvasAdvanced.Focus(); var canvasChildren = canvasAdvanced.Children; double playerLeft = 0; double playerScale = 1; var playerCharacter = new ImageWithShadow(); playerCharacter.Left = playerLeft; playerCharacter.Top = 300; var otherCharacter = new ImageWithShadow(); otherCharacter.ScaleX = -1; otherCharacter.Left = 350; otherCharacter.Top = 300; var <API key> = AnimationBuilder. BeginSequence(). Add(_ShowText("This is an interactive animation.\r\nPress the Left, Up and Right arrows to Move.")). Add(_ShowText("Yet this is not a game, the other character will only flee from you.")). EndSequence(); bool ending = false; bool jumping = false; try { // This animation will run in parallel to the actual imperative animaion. // It is "subordinated" and so, if this animation is ended prematurely, such // parallel animation will also end prematurely. // This is different than adding the animation to the WpfAnimationManager directly. // Also, there is an additional difference, as time modifiers that are affecting // this animation will also affect its subordinated parallel (even if this is not // happening in this sample application). ImperativeAnimation.<API key>(<API key>); canvasChildren.Add(playerCharacter); canvasChildren.Add(otherCharacter); canvasAdvanced.PreviewKeyDown += <API key>; canvasAdvanced.PreviewKeyUp += <API key>; int actualMovingFrame = 0; int totalMovingFrames = <API key>.Count * 8; int totalWaitingFrames = _waitingCharacter.Count * 8; int actualWaitingFrame = totalWaitingFrames; bool running = true; while(running) { actualWaitingFrame++; if (actualWaitingFrame >= totalWaitingFrames) actualWaitingFrame = 0; int actualRealFrame = actualWaitingFrame / 8; otherCharacter.Source = _waitingCharacter[actualRealFrame]; if (_isUpPressed && !jumping) { jumping = true; Action<double> setTop = (value) => playerCharacter.JumpingHeight = value; var animation = AnimationBuilder.BeginSequence(). Range(0, 100, 0.3, setTop). Range(100, 0, 0.3, setTop). Add(() => jumping = false). EndSequence(); ImperativeAnimation.<API key>(animation); } if (_direction == 0) playerCharacter.Source = _waitingCharacter[actualRealFrame]; else { bool canMove = false; if (_direction < 0) { if (playerScale > -1) { playerScale -= 0.1; if (playerScale < -1) playerScale = -1; } else canMove = true; playerCharacter.ScaleX = playerScale; } else { if (playerScale < 1) { playerScale += 0.1; if (playerScale > 1) playerScale = 1; } else canMove = true; playerCharacter.ScaleX = playerScale; } if (canMove) { actualMovingFrame++; if (actualMovingFrame >= totalMovingFrames) actualMovingFrame = 0; playerCharacter.Source = <API key>[actualMovingFrame/8]; playerLeft += _direction * 1; if (playerLeft < 0) playerLeft = 0; // The typical invisible barrier in which the character // continues walking without moving. playerCharacter.Left = playerLeft; if (playerLeft > 250 && !ending) { // this is to avoid playing the ending animation more // than once. ending = true; // and this is just in case the presentation is still running, // as we don't want messages to overlap. <API key>.Dispose(); Action<double> setLeft = (value) => otherCharacter.Left = value; Action<double> setTop = (value) => otherCharacter.Top = value; var finalAnimation = AnimationBuilder. BeginSequence(). BeginParallel(). Range(350, 370, 0.10, setLeft). Range(300, 280, 0.10, setTop). EndParallel(). BeginParallel(). Range(370, 390, 0.10, setLeft). Range(280, 300, 0.10, setTop). EndParallel(). Range(-1.0, 1.0, 0.5, (value) => otherCharacter.ScaleX = value). Range(390, 510, 0.5, setLeft). Add(_ShowText("The other character fled from you...")). Add(_ShowText("... he is a COWARD!!!")). Add(() => running=false). EndSequence(); ImperativeAnimation.<API key>(finalAnimation); } } } yield return helper.WaitNextFrame(); } } finally { canvasAdvanced.PreviewKeyDown -= <API key>; canvasChildren.Remove(playerCharacter); canvasChildren.Remove(otherCharacter); } } void <API key>(object sender, KeyEventArgs e) { switch(e.Key) { case Key.Left: _direction = -1; e.Handled = true; break; case Key.Right: _direction = 1; e.Handled = true; break; case Key.Up: _isUpPressed = true; e.Handled = true; break; } } void <API key>(object sender, KeyEventArgs e) { switch(e.Key) { case Key.Left: case Key.Right: e.Handled = true; _direction = 0; break; case Key.Up: e.Handled = true; _isUpPressed = false; break; } } private IEnumerable<IAnimation> _ShowText(string message) { var textBlock = new TextBlock(); try { textBlock.Text = message; canvasAdvanced.Children.Add(textBlock); Action<double> setOpacity = (value) => textBlock.Opacity = value; yield return AnimationBuilder. BeginSequence(). Range(0.0, 1.0, 1, setOpacity). Wait(2). Range(1.0, 0.0, 1, setOpacity). EndSequence(); } finally { canvasAdvanced.Children.Remove(textBlock); } } } }
package fables.kotlin.jee.rest; import fables.kotlin.jee.business.<API key>; import fables.kotlin.jee.business.KittenEntity; import javax.inject.Inject; import javax.ws.rs.*; /** * JSON REST CRud service. * JEE will first create one noarg instance, and then injected instances. * * @author Zeljko Trogrlic */ @Path("kitten") public class KittenRestService { @Inject protected <API key> <API key>; @GET @Path("{id}") @Produces({"application/json"}) public KittenRest find( @PathParam("id") final int id ) { return <API key> .find(id) .map(kittenEntity -> new KittenRest(kittenEntity.getName(), kittenEntity.getCuteness())) .orElseThrow(() -> new NotFoundException("ID " + id + " not found")); } @POST @Produces({"application/json"}) public Integer add(KittenRest kittenRest) { KittenEntity kittenEntity = new KittenEntity(kittenRest.getName(), kittenRest.getCuteness()); return <API key>.add(kittenEntity); } }
<?php return array( 'debug' => true, 'url' => 'http://localhost/web.api', 'timezone' => 'UTC', 'locale' => 'en', 'key' => '<API key>', 'providers' => array( 'Illuminate\Foundation\Providers\<API key>', 'Illuminate\Auth\AuthServiceProvider', 'Illuminate\Cache\<API key>', 'Illuminate\Session\<API key>', 'Illuminate\Foundation\Providers\<API key>', 'Illuminate\Routing\<API key>', 'Illuminate\Cookie\<API key>', 'Illuminate\Database\<API key>', 'Illuminate\Encryption\<API key>', 'Illuminate\Filesystem\<API key>', 'Illuminate\Hashing\HashServiceProvider', 'Illuminate\Html\HtmlServiceProvider', 'Illuminate\Log\LogServiceProvider', 'Illuminate\Mail\MailServiceProvider', 'Illuminate\Database\<API key>', 'Illuminate\Pagination\<API key>', 'Illuminate\Queue\<API key>', 'Illuminate\Redis\<API key>', 'Illuminate\Remote\<API key>', 'Illuminate\Auth\Reminders\<API key>', 'Illuminate\Database\SeedServiceProvider', 'Illuminate\Session\<API key>', 'Illuminate\Translation\<API key>', 'Illuminate\Validation\<API key>', 'Illuminate\View\ViewServiceProvider', 'Illuminate\Workbench\<API key>', 'Way\Generators\<API key>', 'Aws\Laravel\AwsServiceProvider', 'Intervention\Image\<API key>', 'Twilio\Laratwilio\<API key>' ), 'manifest' => storage_path().'/meta', 'aliases' => array( 'App' => 'Illuminate\Support\Facades\App', 'Artisan' => 'Illuminate\Support\Facades\Artisan', 'Auth' => 'Illuminate\Support\Facades\Auth', 'Blade' => 'Illuminate\Support\Facades\Blade', 'Cache' => 'Illuminate\Support\Facades\Cache', 'ClassLoader' => 'Illuminate\Support\ClassLoader', 'Config' => 'Illuminate\Support\Facades\Config', 'Controller' => 'Illuminate\Routing\Controller', 'Cookie' => 'Illuminate\Support\Facades\Cookie', 'Crypt' => 'Illuminate\Support\Facades\Crypt', 'DB' => 'Illuminate\Support\Facades\DB', 'Eloquent' => 'Illuminate\Database\Eloquent\Model', 'Event' => 'Illuminate\Support\Facades\Event', 'File' => 'Illuminate\Support\Facades\File', 'Form' => 'Illuminate\Support\Facades\Form', 'Hash' => 'Illuminate\Support\Facades\Hash', 'HTML' => 'Illuminate\Support\Facades\HTML', 'Input' => 'Illuminate\Support\Facades\Input', 'Lang' => 'Illuminate\Support\Facades\Lang', 'Log' => 'Illuminate\Support\Facades\Log', 'Mail' => 'Illuminate\Support\Facades\Mail', 'Paginator' => 'Illuminate\Support\Facades\Paginator', 'Password' => 'Illuminate\Support\Facades\Password', 'Queue' => 'Illuminate\Support\Facades\Queue', 'Redirect' => 'Illuminate\Support\Facades\Redirect', 'Redis' => 'Illuminate\Support\Facades\Redis', 'Request' => 'Illuminate\Support\Facades\Request', 'Response' => 'Illuminate\Support\Facades\Response', 'Route' => 'Illuminate\Support\Facades\Route', 'Schema' => 'Illuminate\Support\Facades\Schema', 'Seeder' => 'Illuminate\Database\Seeder', 'Session' => 'Illuminate\Support\Facades\Session', 'SSH' => 'Illuminate\Support\Facades\SSH', 'Str' => 'Illuminate\Support\Str', 'URL' => 'Illuminate\Support\Facades\URL', 'Validator' => 'Illuminate\Support\Facades\Validator', 'View' => 'Illuminate\Support\Facades\View', 'AWS' => 'Aws\Laravel\AwsFacade', 'Image' => 'Intervention\Image\Facades\Image', 'Sms' => 'Twilio\Laratwilio\Facades\Laratwilio' ), );
import React, {Component} from 'react'; import PdfJS from './pdfJS'; import Contract from "../../contract"; import Event from '../../event'; import AnnotationLoader from '../../annotator/loader'; class Viewer extends Component { constructor(props) { super(props); this.state = ({ page_no: 0, pdf_url: "", scale: 0, loading: true }); } componentDidMount() { this.subscribe_zoom = Event.subscribe('zoom:change', (scale) => { this.setState({scale: scale}); }); this.updateState(this.props); } updateState(props) { var {page_no, pdf_url} = props.page; var scale = Contract.getPdfScale(); this.setState({ page_no, pdf_url, scale, loading: false }); } <API key>() { this.subscribe_zoom.remove(); } getPageID() { return 'pdf-' + this.state.page_no; } getAnnotations() { let page = []; let annotations = Contract.getAnnotations(); annotations.result.forEach(annotation=> { if (typeof annotation.shapes == 'object' && this.state.page_no == annotation.page_no) { page.push(annotation); } }); return page; } onPageRendered() { if (!this.annotator) { this.annotator = new AnnotationLoader('.pdf-annotator'); this.annotator.init(); Contract.<API key>(this.annotator); } const annotations = this.getAnnotations(); if (annotations.length > 0) { this.annotator.content.annotator("loadAnnotations", annotations); } Event.publish('annotation:loaded', 'pdf'); } <API key>(props) { this.updateState(props); } <API key>(nextProps, nextState) { return (nextProps.page.page_no !== this.state.page_no || this.state.scale !== nextState.scale); } render() { if (this.state.loading) { return ( <div className="pdf-viewer pdf-annotator"> <div className="pdf-wrapper"> Loading... </div> </div>); } return ( <div className="pdf-viewer pdf-annotator"> <div id={this.getPageID()} className="pdf-wrapper"> <PdfJS onPageRendered={this.onPageRendered.bind(this)} file={this.state.pdf_url} page={this.state.page_no} scale={this.state.scale}/> </div> <a href="#" className="change-view-icon exit-fullscreen"></a> </div> ); } } export default Viewer;
use std::collections::{HashMap}; use std::path::{Path}; use std::sync::{Arc}; use crossbeam::sync::{MsQueue}; use glium::backend::{Facade}; use debug::{gnomon, indicator}; use inverse_kinematics::{Chain}; use model::{Model}; use unlit_model::{UnlitModel}; use render::render_frame::{RenderFrame}; pub const DEPTH_DIMENSION: u32 = 2048; #[derive(Eq, PartialEq, Hash, Copy, Clone)] pub enum ModelId { Player, Scene, IKModel, // TODO: we are going to need more of these / a dynamic way to generate ids and load at a later time Tree, // DEBUG Gnomon, Indicator, } pub struct RenderContext { pub q: Arc<MsQueue<RenderFrame>>, // TODO: make private and provide minimal decent api window_size: (u32, u32), // TODO: maybe this should be a per RenderFrame parameter pub models: HashMap<ModelId, Arc<Model>>, // DEBUG pub unlit_models: HashMap<ModelId, Arc<UnlitModel>>, } impl RenderContext { pub fn new<F: Facade>(facade: &F, q: Arc<MsQueue<RenderFrame>>, window_size: (u32, u32), ik_chains: &[Chain]) -> RenderContext { let model_map = load_initial_models(facade, ik_chains); // DEBUG let mut unlit_models = HashMap::new(); unlit_models.insert(ModelId::Gnomon, Arc::new(gnomon::model(facade))); unlit_models.insert(ModelId::Indicator, Arc::new(indicator::model(facade))); RenderContext { q: q, window_size: window_size, models: model_map, // DEBUG unlit_models: unlit_models, } } pub fn aspect_ratio(&self) -> f32 { (self.window_size.0 as f32) / (self.window_size.1 as f32) } } // TODO: don't pass in chains but make something like IntoModel fn load_initial_models<F: Facade>(facade: &F, ik_chains: &[Chain]) -> HashMap<ModelId, Arc<Model>> { let mut map = HashMap::new(); const MODEL_PATH_STRINGS: [(ModelId, &'static str); 3] = [ (ModelId::Player, "./data/player.obj"), (ModelId::Scene, "./data/level.obj"), (ModelId::Tree, "./data/tree.obj") ]; for &(model_id, path) in &MODEL_PATH_STRINGS { let model = Arc::new(Model::new(facade, &Path::new(path))); map.insert(model_id, model); } for chain in ik_chains { map.insert(ModelId::IKModel, Arc::new(chain.model(facade))); } map } unsafe impl Send for RenderContext {} unsafe impl Sync for RenderContext {}
var ratio = require('ratio') function error(actual, expected) { return Math.abs(actual - expected) / expected } function approx(target, max) { max = (max || 10) // find a good approximation var best = 1, j, e, result for (var i = 1; i < max; i++) { j = Math.round(i * target) e = error(j / i, target) if (e >= best) continue best = e result = ratio(j, i) } return result } module.exports = approx
// For email, run on linux (perl v5.8.5): // perl -e 'print pack "H*","<API key>"' // Author - Sourabh S Joshi #ifndef POKER_HAND_H_ #define POKER_HAND_H_ #include <iostream> #include <array> #include <vector> #include <string> #include <sstream> using std::vector; using std::ostream; using std::pair; class Card { public: enum CardSuit { Clubs, Diamonds, Hearts, Spades, NUM_SUITS }; enum CardVal { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace, NUM_VALS }; Card(CardSuit suit, CardVal val) : suit_(suit), val_(val) {} ~Card() {} //comparison operators only compare on value of card bool operator==(const Card& rhs) const { return (val_ == rhs.val_);} bool operator<(const Card& rhs) const { return (val_ < rhs.val_);} bool operator>(const Card& rhs) const { return (val_ > rhs.val_);} CardVal GetVal() const {return val_;} CardSuit GetSuit() const {return suit_;} friend ostream& operator<<(ostream& os, const Card& cd); private: CardSuit suit_; CardVal val_; }; class Pokerhand { public: enum HandType { PHHighCard, PHPair, PHTwoPair, PHThreeOfAKind, PHStraight, PHFlush, PHFullHouse, PHFourOfAKind, PHStraightFlush, PH_NUM_TYPES }; Pokerhand(std::string istr); virtual ~Pokerhand() {} vector<Card> AllCards() const {return hand_;} vector<Card> TieBreakCards() const {return tiebreak_cards_;} HandType GetType() const {return type_;} std::string GetTypeStr() const; //comparison to compare 2 poker hands bool operator>(const Pokerhand& rhs) const {return (Compare_(rhs) == PH_GT);} bool operator<(const Pokerhand& rhs) const {return (Compare_(rhs) == PH_LT);} bool operator==(const Pokerhand& rhs) const {return (Compare_(rhs) == PH_EQ);} friend ostream& operator<<(ostream& os, const Pokerhand& ph); void ProcessPokerHand(); private: //each of these methods returns a bool, saying whether the poker hand is of that type //also returns a vector of cards in order, so that tie-breakers can be resolved Card* XOfAKind__(unsigned int num); bool XOfAKind_(unsigned int num); bool MNOfAKind_(unsigned int m, unsigned int n); bool HighCard_(); bool Pair_(); bool TwoPair_(); bool ThreeOfAKind_(); bool Straight_(); bool Flush_(); bool FullHouse_(); bool FourOfAKind_(); bool StraightFlush_(); //since C++ STL lacks an ordering type, I am forced to create one enum Ordering { PH_LT, PH_EQ, PH_GT }; Ordering Compare_(const Pokerhand& rhs) const; private: vector<Card> hand_; HandType type_; vector<Card> tiebreak_cards_; }; int PlayPokerHands(vector<std::pair<int, Pokerhand> >& hands); bool DetectCheating(vector<std::pair<int, Pokerhand> >& hands); #endif /* POKER_HAND_H_ */
.yan-github { position: fixed; bottom:0; right:0; min-width:350px; outline:1px solid rgba(0, 0, 0, 0.3); min-height:200px; background: #FFFFFF; border-radius:3px; box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); z-index: 10000 } .yan-github ul{ padding:0 } .yan-github li { list-style-type: none } .yan-header { margin: 10px; border-bottom: 1px solid #2299DD; padding-bottom: 5px; } .yan-header h2 { margin:0; } .yan-header .yan-close { float: right; font-size: 0.8em; cursor: pointer } .yan-github form { margin: 10px } .yan-github fieldset { border: 0; margin: 5px; margin-bottom: 20px } .yan-github fieldset::after { content: ""; display: block; clear: both } .yan-github legend { font-size: 1.2em; margin-bottom: 10px; border-bottom: 1px solid #e5e5e5; width: 100%; } .yan-label-block{ display: block; margin: 5px } .yan-btn { display: inline-block; padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: normal; line-height: 1.428571429; text-align: center; white-space: nowrap; vertical-align: middle; cursor: pointer; background-image: none; border: 1px solid transparent; border-radius: 4px; } .yan-btn:hover { color: #333; }
var State = require('../state'), path = require('path'), mkdirp = require('mkdirp').mkdirp, fs = require('fs'); /** * Write out the input to the destination filename. * * This can only apply to single string inputs. * * @method writeTask * @param options {Object} Write task options * @param options.name {String} Filename to write to. * @param options.encoding {String} [default='utf8'] Encoding to use when writing the file * @param options.mkdir {Boolean} [default=true] Make destination directory if it does not exist * @param options.dirmode {String} [default='0755'] Create new directories with this mode (chmod) * @param status {EventEmitter} Status object, handles 'complete' and 'failed' task exit statuses. * @param logger {winston.Logger} Logger instance, if additional logging required (other than task exit status) * @return {undefined} * @public */ function writeTask(options, status, logger) { var self = this, pathname = path.resolve(path.dirname(options.name)), name = options.name, encoding = options && options.encoding || 'utf8', mkdir = options && options.mkdir || true, dirmode = options && options.dirmode || '0755'; // Write the content to the specified file. function writeFile(filename, data) { fs.writeFile(filename, data, encoding, function(err) { if (err) { status.emit('failed', 'write', 'error writing destination file: ' + err); } else { self._state.set(State.TYPES.FILES, [ filename ]); status.emit('complete', 'write', 'wrote ' + filename); } }); } // Create the paramsified path if it does not exist. function mkdirIfNotExist(filename, callback) { path.exists(filename, function(exists) { if (!exists) { if (mkdir === true) { mkdirp(filename, dirmode, function(err) { if (err) { callback(err); } else { callback(null); } }); } else { callback('tried to write a file to a non-existing directory and mkdir is false'); } } else { callback(null); } }); } switch (this._state.get().type) { case State.TYPES.FILES: mkdirIfNotExist(pathname, function(err) { if (err) { status.emit('failed', 'write', 'error creating destination directory: ' + err); } else { writeFile(name, self._state.get().value.join("\n")); } }); break; case State.TYPES.STRING: mkdirIfNotExist(pathname, function(err) { if (err) { status.emit('failed', 'write', 'error creating destination directory: ' + err); } else { writeFile(name, self._state.get().value); } }); break; case State.TYPES.STRINGS: mkdirIfNotExist(pathname, function(err) { if (err) { status.emit('failed', 'write', 'error creating destination directory: ' + err); } else { writeFile(name, self._state.get().value.join("")); } }); break; case State.TYPES.UNDEFINED: mkdirIfNotExist(pathname, function(err) { if (err) { status.emit('failed', 'write', 'error creating destination directory: ' + err); } else { writeFile(name, ""); } }); break; default: status.emit('failed', 'write', 'unrecognised input type: ' + this._type); break; } } exports.tasks = { 'write' : { callback: writeTask } };
# <API key>: true require 'grape/router' require 'grape/api/instance' module Grape # The API class is the primary entry point for creating Grape APIs. Users # should subclass this class in order to build an API. class API # Class methods that we want to call on the API rather than on the API object NON_OVERRIDABLE = (Class.new.methods + %i[call call! configuration compile! inherited]).freeze class << self attr_accessor :base_instance, :instances # Rather than initializing an object of type Grape::API, create an object of type Instance def new(*args, &block) base_instance.new(*args, &block) end # When inherited, will create a list of all instances (times the API was mounted) # It will listen to the setup required to mount that endpoint, and replicate it on any new instance def inherited(api, <API key> = Grape::API::Instance) api.initial_setup(<API key>) api.<API key>! make_inheritable(api) end # Initialize the instance variables on the remountable class, and the base_instance # an instance that will be used to create the set up but will not be mounted def initial_setup(<API key>) @instances = [] @setup = Set.new @base_parent = <API key> @base_instance = mount_instance end # Redefines all methods so that are forwarded to add_setup and be recorded def <API key>! (base_instance.methods - NON_OVERRIDABLE).each do |method_override| <API key>(method_override) do |*args, &block| add_setup(method_override, *args, &block) end end end # Configure an API from the outside. If a block is given, it'll pass a # configuration hash to the block which you can use to configure your # API. If no block is given, returns the configuration hash. # The configuration set here is accessible from inside an API with # `configuration` as normal. def configure config = @base_instance.configuration if block_given? yield config self else config end end # This is the interface point between Rack and Grape; it accepts a request # from Rack and ultimately returns an array of three values: the status, # the headers, and the body. See [the rack specification] # NOTE: This will only be called on an API directly mounted on RACK def call(*args, &block) instance_for_rack.call(*args, &block) end # Allows an API to itself be inheritable: def make_inheritable(api) # When a child API inherits from a parent API. def api.inherited(child_api) # The instances of the child API inherit from the instances of the parent API Grape::API.inherited(child_api, base_instance) end end # Alleviates problems with autoloading by tring to search for the constant def const_missing(*args) if base_instance.const_defined?(*args) base_instance.const_get(*args) else super end end # The remountable class can have a configuration hash to provide some dynamic class-level variables. # For instance, a description could be done using: `desc configuration[:description]` if it may vary # depending on where the endpoint is mounted. Use with care, if you find yourself using configuration # too much, you may actually want to provide a new API rather than remount it. def mount_instance(**opts) instance = Class.new(@base_parent) instance.configuration = Grape::Util::<API key>.new(opts[:configuration] || {}) instance.base = self replay_setup_on(instance) instance end # Replays the set up to produce an API as defined in this class, can be called # on classes that inherit from Grape::API def replay_setup_on(instance) @setup.each do |setup_step| replay_step_on(instance, setup_step) end end def respond_to?(method, include_private = false) super(method, include_private) || base_instance.respond_to?(method, include_private) end def respond_to_missing?(method, include_private = false) base_instance.respond_to?(method, include_private) end def method_missing(method, *args, &block) # If there's a missing method, it may be defined on the base_instance instead. if respond_to_missing?(method) base_instance.send(method, *args, &block) else super end end def compile! require 'grape/eager_load' instance_for_rack.compile! # See API::Instance.compile! end private def instance_for_rack if never_mounted? base_instance else mounted_instances.first end end # Adds a new stage to the set up require to get a Grape::API up and running def add_setup(method, *args, &block) setup_step = { method: method, args: args, block: block } @setup += [setup_step] last_response = nil @instances.each do |instance| last_response = replay_step_on(instance, setup_step) end last_response end def replay_step_on(instance, setup_step) return if skip_immediate_run?(instance, setup_step[:args]) args = evaluate_arguments(instance.configuration, *setup_step[:args]) response = instance.send(setup_step[:method], *args, &setup_step[:block]) if skip_immediate_run?(instance, [response]) response else evaluate_arguments(instance.configuration, response).first end end # Skips steps that contain arguments to be lazily executed (on re-mount time) def skip_immediate_run?(instance, args) instance.base_instance? && (any_lazy?(args) || args.any? { |arg| arg.is_a?(Hash) && any_lazy?(arg.values) }) end def any_lazy?(args) args.any? { |argument| argument.respond_to?(:lazy?) && argument.lazy? } end def evaluate_arguments(configuration, *args) args.map do |argument| if argument.respond_to?(:lazy?) && argument.lazy? argument.evaluate_from(configuration) elsif argument.is_a?(Hash) argument.transform_values { |value| evaluate_arguments(configuration, value).first } elsif argument.is_a?(Array) evaluate_arguments(configuration, *argument) else argument end end end def never_mounted? mounted_instances.empty? end def mounted_instances instances - [base_instance] end end end end
(function () { "use strict"; /** * This module have an ability to contain constants. * No one can reinitialize any of already initialized constants */ var module = (function () { var constants = {}, hasOwnProperty = Object.prototype.hasOwnProperty, prefix = (Math.random() + "_").slice(2), isAllowed; /** * This private method checks if value is acceptable * @param value {String|Number|Boolean} - the value of the constant * @returns {boolean} * @private */ isAllowed = function (value) { switch (typeof value) { case "number": return true; case "string": return true; case "boolean": return true; default: return false; } }; return { /** * Constant getter * @param name {String} - the name of the constant * @returns {String|Number|Boolean|null} */ getConstant: function (name) { if (this.isDefined(name) === true) { return constants[prefix + name]; } return undefined; }, /** * Setter * @param name {String} - the name of the constant * @param value {String|Number|Boolean} - the value of the constant * @returns {boolean} */ setConstant: function (name, value) { if (isAllowed(value) !== true) { return false; } if (this.isDefined(name) === true) { return false; } constants[prefix + name] = value; return true; }, /** * This method checks if constant is already defined * @param name {String} - the name of the constant * @returns {boolean} */ isDefined: function (name) { return hasOwnProperty.call(constants, prefix + name); } }; })(); /**Testing*/ module.setConstant("test", 123); print("test == " + module.getConstant("test")); print("idDefined(\"test\") == " + module.isDefined("test")); print("test2 == " + module.getConstant("test2")); print("idDefined(\"test2\") == " + module.isDefined("test2")); print(""); module.setConstant("test", 321); print("test == " + module.getConstant("test")); print(""); module.setConstant("test3", {a: 123}); print("test3 == " + module.getConstant("test3")); })();
# <API key>: true module RuboCop module Formatter # This formatter formats report data in clang style. # The precise location of the problem is shown together with the # relevant source code. class ClangStyleFormatter < SimpleTextFormatter ELLIPSES = '...' def report_file(file, offenses) offenses.each { |offense| report_offense(file, offense) } end private def report_offense(file, offense) output.printf( "%<path>s:%<line>d:%<column>d: %<severity>s: %<message>s\n", path: cyan(smart_path(file)), line: offense.line, column: offense.real_column, severity: <API key>(offense), message: message(offense) ) begin return unless valid_line?(offense) report_line(offense.location) <API key>(offense.highlighted_area) rescue IndexError # rubocop:disable Lint/SuppressedException # range is not on a valid line; perhaps the source file is empty end end def valid_line?(offense) !offense.location.source_line.blank? end def report_line(location) source_line = location.source_line if location.first_line == location.last_line output.puts(source_line) else output.puts("#{source_line} #{yellow(ELLIPSES)}") end end def <API key>(highlighted_area) output.puts("#{' ' * highlighted_area.begin_pos}" \ "#{'^' * highlighted_area.size}") end end end end
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="An approach to developing modern web applications"> <meta name="author" content="Marc J. Greenberg"> <title>ElectricDiscoTech</title> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> <link rel="icon" href="favicon.ico" type="image/x-icon"> <link rel="stylesheet" href="css/style.min.css" type="text/css"> <script src="js/jquery.min.js"></script> <script src="js/uikit.min.js"></script> <script src="js/clipboard.min.js"></script> <script src="js/edt.min.js"></script> </head> <body class="edt-background"> <div class="inc:site/header.html"></div> <div class="uk-grid" data-uk-grid-margin> <div class="uk-width-medium-1-1"> <div class="edt-front2"></div> </div> </div> <div class="edt-middle"> <div class="uk-container uk-container-center"> <div class="uk-grid" data-uk-grid-margin> <div class="edt-sidebar uk-width-medium-1-4 uk-hidden-small"> <ul class="edt-nav uk-nav" data-uk-nav> <li class="uk-nav-header">Conceptual</li> <li><a href="readme.html">Dance Floor</a></li> <li><a href="source.html">First Steps</a></li> <li><a href="tools.html">Do the Hustle</a></li> <ul class="uk-nav uk-margin-left"> <li><a href="winivp.html"><i class="uk-icon-windows uk-margin-right"></i>Windows (ivp)</a></li> <li><a href="linuxivp.html"><i class="uk-icon-linux uk-margin-right"></i>Linux (ivp)</a></li> <li class="uk-active"><a href="osxivp.html"><i class="uk-icon-apple uk-margin-right"></i>Mac OS X (ivp)</a></li> </ul> <li><a href="bower.html">Disco Duck</a></li> <li><a href="tasks.html">Disco Pig</a></li> <li class="uk-nav-header"></li> <li><a href=""></a></li> </ul> </div> <div class="edt-main uk-width-medium-3-4"> <article class="uk-article"> <h2 id="osxivp"> <img src="img/osx.png" width="48"/> <a href="#osxivp" class="uk-link-reset">&nbsp;&nbsp;Mac OS X ivp for <i class="edt-tla2">EDT</i></a> </h2> <hr class="uk-article-divider"> <div class="uk-grid"> <div class="uk-width-medium-1-2"> <p> <a href="http: It is a common practice among dance instructors, to have the students switch partners frequently during the class in order to get them used to dancing with different partners. Using OS X as a base platform I can seamlessly run virtualized windows and/or linux on demand. </p> <p> While I mentioned this before, a good code editor is the hammer in a modern web application developers toolbox. For this project I am using one of Microsoft&apos;s latest concoctions, <a href=https://code.visualstudio.com/> Visual Studio Code</a>. It runs on windows, linux and os x. It&apos;s open source and <a href="https://github.com/Microsoft/vscode">forkable on github</a> and I really like. </p> </div> <div class="uk-width-medium-1-4"> <img src="img/discothink.png" width="80%"></a> </div> </div> </article> </div> <div class="uk-width-medium-1-4"> </div> </div> <!-- Git --> <div class="uk-grid"> <div class="uk-width-medium-1-4"> <a href="https://github.com/explore"> <img style="margin-top:2.5em;margin-left:-18px;" src="img/github-octocat.png"> </a> </div> <div class="uk-width-medium-2-4"> <hr class="uk-article-divider" style="margin-top:-48px;"> <h4><a href="http://git-scm.com/">Git</a></h4> <p>Let&apos;s start a shell and validate the ability to run git from the command prompt:</p> <button class="edt-clip" data-clipboard-text="git --version"><i class="uk-icon-clipboard"></i></button> <pre class="edt-border uk-margin-bottom">$ git --version git version 2.4.9 (Apple Git-60) </pre> <p> If for some reason you don&apos;t have git installed, you can download the <a href="http://git-scm.com/download/mac">git-osx-installer</a> from <a href="http://git-scm.com/">get-scm.com</a> If you can use use git then clone a copy of <span class="edt-tla2">EDT</span>: </p> <button class="edt-clip" data-clipboard-text="git clone https://github.com/codemarc/ElectricDiscoTech"><i class="uk-icon-clipboard"></i></button> <pre class="edt-border">$ git clone https://github.com/codemarc/ElectricDiscoTech Cloning into 'ElectricDiscoTech'... remote: Counting objects: 254, done. remote: Compressing objects: 100% (30/30), done. remote: Total 254 (delta 10), reused 0 (delta 0), pack-reused 223 Receiving objects: 100% (254/254), 5.69 MiB | 3.31 MiB/s, done. Resolving deltas: 100% (101/101), done. Checking connectivity... done. </pre> </div> </div> <!-- NODE/NPM --> <div class="uk-grid"> <div class="uk-width-medium-1-4"> <a href="https://nodejs.org/"> <img style="margin-top:3.5em" src="img/nodejs-npm.png" width="70%"> </a> </div> <div class="uk-width-medium-2-4"> <hr class="uk-article-divider"> <h4><a href="https: <p>Now let&apos;s see which version of npm is installed:</p> <button class="edt-clip" data-clipboard-text="npm -v"><i class="uk-icon-clipboard"></i></button> <pre>$ npm -v -bash: npm: command not found </pre> <p> Oops, forgot to install node. <a href="https: On the Node.js website you can quickly find the download for installable package for OS X (x64). </p> <button class="edt-clip" data-clipboard-text="npm -v"><i class="uk-icon-clipboard"></i></button> <pre class="edt-border">$ npm -v 2.14.7 </pre> <p> You can use npm to update npm. </p> <button class="edt-clip" data-clipboard-text="sudo npm install -g npm"><i class="uk-icon-clipboard"></i></button> <pre class="edt-border <API key>">$ sudo npm install -g npm &vellip; $ npm -v 3.5.0 </pre> </div> </div> <!-- BOWER --> <div class="uk-grid"> <div class="uk-width-medium-1-4"> <a href="http://bower.io/"> <img class="uk-margin-left" src="img/bower.png" width="45%"> </a> </div> <div class="uk-width-medium-2-4"> <hr class="uk-article-divider" style="margin-top:-36px;"> <h4><a href="http://bower.io/">Bower</a></h4> <p><a href="http://bower.io/">bower</a> is billed as a package manager for the web. What it saves you from is endless hours of searching for source components. If you know the name of a component and its author has created a package for it (most popular components have the by now) then all you need to do to grab a copy using: <span class="uk-margin-left uk-text-primary">bower install &lt;package&gt;</span> </p> <p>To install or update bower run:</p> <button class="edt-clip" data-clipboard-text="npm install -g bower"><i class="uk-icon-clipboard"></i></button> <pre>$ npm install -g bower &vellip; $ bower -version 1.6.5 </pre> </div> </div> </div> <div class="inc:site/footer.html"></div> </body> <script>new Clipboard('.edt-clip');</script> </html>
package me.nereo.<API key>; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.RectF; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.facebook.common.executors.<API key>; import com.facebook.common.references.CloseableReference; import com.facebook.datasource.DataSource; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.controller.<API key>; import com.facebook.drawee.drawable.ProgressBarDrawable; import com.facebook.drawee.drawable.ScalingUtils; import com.facebook.drawee.generic.<API key>; import com.facebook.drawee.generic.<API key>; import com.facebook.drawee.interfaces.DraweeController; import com.facebook.imagepipeline.core.ImagePipeline; import com.facebook.imagepipeline.datasource.<API key>; import com.facebook.imagepipeline.image.CloseableImage; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequestBuilder; import java.io.File; import me.nereo.<API key>.view.ClipImageBorderView; import me.nereo.<API key>.view.zoomable.<API key>; import me.nereo.<API key>.view.zoomable.ZoomableDraweeView; public class ClipPhotoActivity extends Activity implements OnClickListener, IBitmapShow { public static final String TAG = ClipPhotoActivity.class.getSimpleName(); private String imgUrl; private TextView mTitle; private Button mCommit; private ImageView mBack; private ZoomableDraweeView mGestureImageView; private ClipImageBorderView <API key>; float mCurrentScale; float last_x = -1; float last_y = -1; boolean move = false; public static void <API key>(Context context, String uri) { Intent targetIntent = new Intent(context, ClipPhotoActivity.class); targetIntent.putExtra(TAG, uri); context.startActivity(targetIntent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_clip_photo); setTitle(""); initIntentParams(); } @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { super.onResume(); /* new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { getBitmap(); } },100);*/ getBitmap(); } private void getBitmap() { int width = <API key>.getWidth(); int height = <API key>.getHeight(); Log.e("with", "with===" + width + "\nheight===" + height); DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); int screenWidth = displayMetrics.widthPixels; int screenHeight = displayMetrics.heightPixels; /* FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(screenWidth - 40, screenWidth - 40); layoutParams.gravity = Gravity.CENTER; mGestureImageView.setLayoutParams(layoutParams);*/ if (!TextUtils.isEmpty(imgUrl)) { // ImageLoaderUtils.load(imgUrl,mGestureImageView); ImageRequest imageRequest = ImageRequestBuilder .<API key>(Uri.parse("file://" + imgUrl)) .<API key>(true).build(); DraweeController controller = Fresco.<API key>() .setImageRequest(imageRequest) .<API key>(true) .build(); /* <API key> controller = <API key>.newInstance(); controller.setEnabled(true);*/ <API key> hierarchy = new <API key>(getResources()) .<API key>(ScalingUtils.ScaleType.FIT_CENTER) .setProgressBarImage(new ProgressBarDrawable()) .build(); mGestureImageView.setController(controller); mGestureImageView.setHierarchy(hierarchy); // getAvatarBitmap(imageRequest, controller, hierarchy, ClipPhotoActivity.this); } } @Override public void onContentChanged() { mTitle = (TextView) findViewById(R.id.photo_title); mGestureImageView = (ZoomableDraweeView) findViewById(R.id.gesture_iv); mBack = (ImageView) findViewById(R.id.btn_back); mBack.setOnClickListener(this); <API key> = (ClipImageBorderView) findViewById(R.id.<API key>); mCommit = (Button) findViewById(R.id.commit); mCommit.setOnClickListener(this); } @Override public void setTitle(CharSequence title) { mTitle.setText(title); } private void initIntentParams() { Intent mIntent = getIntent(); if (mIntent != null) { imgUrl = mIntent.getStringExtra(TAG); } } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.btn_back) { finish(); } else if (id == R.id.commit) { if (mGestureImageView != null) { Bitmap bm = mGestureImageView.clip(); Log.e("bm", "bm:" + bm.toString()); Intent resultIntent = new Intent(); Bundle mBundle = new Bundle(); mBundle.putParcelable(TAG, bm); resultIntent.putExtras(mBundle); setResult(101, resultIntent); finish(); } } } private void getAvatarBitmap(ImageRequest imageRequest, final <API key> controller, final <API key> hierarchy, final IBitmapShow callback) { ImagePipeline imagePipeline = Fresco.getImagePipeline(); DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, ClipPhotoActivity.this); dataSource.subscribe(new <API key>() { @Override protected void onNewResultImpl(@Nullable Bitmap bitmap) { if (bitmap != null) { if (callback != null) { callback.<API key>(bitmap, controller, hierarchy); } } } @Override protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) { } }, <API key>.getInstance()); } @Override public void <API key>(Bitmap bm, <API key> controller, <API key> hierarchy) { int bmWidth = bm.getWidth(); int bmHeight = bm.getHeight(); int newWidth = <API key>.getWidth() == 0 ? 200 : <API key>.getWidth(); int newHeight = <API key>.getHeight() == 0 ? 200 : <API key>.getHeight(); Log.e("bmWidth", "bmWidth:" + bmWidth + ",\nbmHeight:" + bmHeight + ",\nnewWidth:" + newWidth + ",\nnewHeight:" + newHeight); float scaleWidth = ((float) newWidth) / bmWidth; float scaleHeight = ((float) newHeight) / bmHeight; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); Bitmap newBm = Bitmap.createBitmap(bm, 0, 0, bmWidth, bmHeight, matrix, true); mGestureImageView.<API key>(controller); mGestureImageView.setHierarchy(hierarchy); mGestureImageView.setImageBitmap(newBm); mGestureImageView.setOnTouchListener(new View.OnTouchListener() { float baseValue = 0; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: float x = last_x = event.getRawX(); float y = last_y = event.getRawY(); move = false; break; case MotionEvent.ACTION_MOVE: if (event.getPointerCount() == 2) { float x1 = event.getX(0) - event.getX(1); float y1 = event.getY(0) - event.getY(1); float value = (float) Math.sqrt(x1 * x1 + y1 * y1); if (baseValue == 0) { baseValue = value; } else { if ((value - baseValue) >= 10 || (baseValue - value) >= 10) { float scale = value / baseValue; img_scale(scale); } } } else if (event.getPointerCount() == 1) { float x2 = event.getRawX(); float y2 = event.getRawY(); x2 -= last_x; y2 -= last_y; if (x2 >= 10 || y2 >= 10 || x2 <= -10 || y2 <= -10) { img_translate(x2, y2); last_x = event.getRawX(); last_y = event.getRawY(); } } break; } return false; } }); } /** * * * @param x2 * @param y2 */ private void img_translate(float x2, float y2) { if (mGestureImageView != null) mGestureImageView.img_translate(x2, y2); } /** * * * @param scale */ private void img_scale(float scale) { if (mGestureImageView != null) { mGestureImageView.img_scale(scale); } } }
Provides a Ruby wrapper for the Dutch NS API. ## Installation Add this line to your application's Gemfile: gem 'ns' And then execute: $ bundle Or install it yourself as: $ gem install ns ## Usage ns_client = Ns::Client.new(api_key, api_password) available_stations = ns_client.get_stations advice = ns_client.get_travel_advice(available_stations[0], available_stations[1]) Should return a travel advice based on the first and second available station. ## Contributing 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Added some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request
#include <onyxudp/udpclient.h> #include <stdio.h> #include <string.h> #include <assert.h> /* This test just makes sure the client library compiles and doens't crash on start. */ void on_error(udp_client_params_t *client, UDPERR code, char const *name) { fprintf(stderr, "on_error: code %d: %s\n", code, name); assert(!"should not happen"); } int main() { udp_client_params_t params; memset(&params, 0, sizeof(params)); params.app_id = 123; params.app_version = 321; params.on_error = on_error; params.on_idle = NULL; params.on_payload = NULL; params.on_disconnect = NULL; udp_client_t *client = <API key>(&params); assert(client != NULL); <API key>(client); return 0; }
<p>This is the test-route view.</p>
# alsa-switch Switching of Alsa audio devices the purpose of alsa-switch is to control the flow of multiple audio-streams going through a system while supporting priority streams You invoke audio-switch like this: auido-switch <input-device> <output-device> <control-file> for example audio-switch microphone speaker control1 This creates a named pipe named "control1", it is ready to connect "microphone" audio device to "speaker" audio device once the control pipe is telling it to do so. Writing a character to the control channel does this commands to send: '1'...'9' priority 1...9 announcement '0' end of announcement (channel muted) typical use case you have audio source1...9 you have virtual speakers 1...9 you mix virtual speaker 1...9 to physical speaker in alsa (/etc/asound.conf) you run alsa-switch and it will create control files 1...9 now all sound sources are muted if source 2 now has a level 8 priority annoucement it would write '8' into "control2" this would mute all audio streams which have no announcement or a priority announcement of level '9' 1 is the highest priority 9 is the lowest priority 0 is channel is muted At startup all channels are muted. Should a higher priority annoucement come in now on source 3, then source 2 would become muted too. Once source 3 is finished and source 2 is still in priority level 8, the audio from source 2 would be heard again.
package wanghaisheng.com.yakerweather; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
// 2016-01-21, jjuiddong #pragma once namespace cvproc { class cDetectRect { public: cDetectRect(); virtual ~cDetectRect(); bool Init(); bool Detect(const cv::Mat &src); void UpdateParam(const <API key> &recogConfig); public: bool m_show; cRectContour m_rect; int m_threshold1; int m_threshold2; int m_minArea; double m_minCos; double m_maxCos; vector<vector<cv::Point> > m_contours; cv::Mat m_gray; cv::Mat m_edges; cv::Mat m_binMat; }; }
import * as React from 'react'; import { AppliedFilter, DataTypes, GridFilters, numberWithCommas, ReactPowerTable, withInternalPaging, withInternalSorting } from '../../src/'; import { defaultColumns, partyList, sampledata } from './shared'; // //if coming in from DTO // const availDTO = [ // { fieldName: 'number', dataType: 'int' }, // { fieldName: 'president', dataType: 'string' }, // { fieldName: 'birth_year', dataType: 'int' }, // { fieldName: 'death_year', dataType: 'int', canBeNull: true }, // { fieldName: 'took_office', dataType: 'date' }, // { fieldName: 'left_office', dataType: 'date', canBeNull: true }, // { fieldName: 'party', dataType: 'string' }, // const availableFiltersMap = createKeyedMap(availDTO.map(m => new DataTypes[m.dataType](m)), m=>m.fieldName); //availableFilters.party = new DataTypes.list(availableFilters.party, partyList); const partyListOptions = partyList.map(m => ({ label: m.label, value: m.label })); //if building in JS const availableFilters = [ new DataTypes.int('number'), new DataTypes.string('president'), new DataTypes.int('birth_year'), new DataTypes.decimal({ fieldName: 'death_year', canBeNull: true }), new DataTypes.date({ fieldName: 'took_office' }), new DataTypes.date({ fieldName: 'left_office', canBeNull: true }), new DataTypes.list('party', partyListOptions), new DataTypes.boolean({ fieldName: 'assasinated', displayName: 'was assasinated' }), new DataTypes.timespan({ fieldName: 'timeBorn', displayName: 'time born' }), ]; //const columns = [...defaultColumns, { field: m => m.timeBorn, width: 80, formatter: formatTimeValue }]; const <API key> = [16, 20, 25, 35]; function padStart(str: string, targetLength: number, padString: string) { // tslint:disable-next-line:no-bitwise targetLength = targetLength >> 0; //truncate if number, or convert non-number to 0; padString = String(typeof padString !== 'undefined' ? padString : ' '); if (str.length >= targetLength) { return String(str); } else { targetLength = targetLength - str.length; if (targetLength > padString.length) { padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed } return padString.slice(0, targetLength) + str; } } const data = sampledata.map(m => ({ ...m, assasinated: <API key>.indexOf(m.number) > -1, timeBorn: padStart(Math.floor((Math.random() * 24)).toString(), 2, '0') + ':00' })); //const availableFiltersMap = createKeyedMap(availableFilters, m => m.fieldName); //availableFiltersMap.number.operations.gt.displayName = 'greater than TEST'; availableFilters.find(m => m.fieldName === 'death_year').operations['null'].displayName = 'still alive'; interface FiltersExampleState { appliedFilters: Array<AppliedFilter<any>>; } const Table = withInternalSorting(withInternalPaging(ReactPowerTable)); export class FiltersExample extends React.Component<never, FiltersExampleState> { constructor(props: never) { super(props); this.state = { appliedFilters: [] }; this.handleFiltersChange = this.handleFiltersChange.bind(this); } handleFiltersChange(newFilters: Array<AppliedFilter<any>>) { console.log('onFiltersChange', newFilters); this.setState({ appliedFilters: newFilters }); } render() { let filteredData = data; this.state.appliedFilters.forEach(m => { filteredData = m.filter.applyFilter(filteredData, m.operation, m.value); }); return ( <div className="row"> <div className="col-md-3"> <div className="grid-filters"> <div className="small"> {numberWithCommas(filteredData.length) + ' Presidents'} &nbsp; </div> <div style={{ marginTop: 10 }} /> <GridFilters availableFilters={availableFilters} appliedFilters={this.state.appliedFilters} onFiltersChange={this.handleFiltersChange} /> </div> </div> <div className="col-md-9"> <Table columns={defaultColumns} keyColumn="number" rows={filteredData} sorting={{ column: 'number' }} /> </div> </div> ); } }
<section id="content"> <!--start container <div id="breadcrumbs-wrapper" class="" style="width:100%;"> <div class="<API key> grey hide-on-large-only"> <i class="mdi-action-search active"></i> <input type="text" name="Search" class="header-search-input z-depth-2" placeholder="Explore Materialize"> </div> <div class="container"> <div class="row"> <div class="col s12 m12 l12"> <h5 class="breadcrumbs-title">New Progres perunit</h5> <ol class="breadcrumb"> <li><a href="<?php echo site_url('administrator'); ?>">Dashboard</a></li> <li><a href="<?php echo site_url('administrator/main/progres_unit');?>">Progres perUnit</a></li> <li class="active">New Progres perUnit</li> </ol> </div> </div> </div> </div> <div class="col s12 m12 l6"> <div class="card-panel"> <div class="col s12 m12 l6" style="width:100%;"> <div class="card-panel" style="width:100%;"> <h4 class="header2">New Progres perUnit</h4> <div class="row"> <div class="row"> <?=form_open('action/save_progresunit');?> <div class="input-field col s12"> <label for="spk" class="active">SPK</label> <select name="spk" id="spk"> <?php $query = $this->db->query("SELECT DISTINCT spk FROM tbl_resume"); foreach ($query->result() as $datap) { ?> <option value="<?=$datap->spk;?>"><?=$datap->spk;?></option> <?php } ?> </select> </div> </div> <div class="row"> <div class="input-field col s12"> <input type="hidden" name="nama_kavling_hidden" id="nama_kavling_hidden"> <label for="nama_kavling" class="active">Kavling</label> <select id="nama_kavling" name="nama_kavling"> <option></option> </select> </div> </div> <div class="row"> <div class="input-field col s12"> <input placeholder="" id="sdmingguini" type="text" name="sdmingguini"> <label for="sdmingguini" class="active">Progres</label> </div> </div> <div class="input-field col s12"> <button class="btn cyan waves-effect waves-light right" type="submit" name="action" style="margin-left:10px;">Submit </button> <button onclick="goBack()" class="btn cyan waves-effect waves-light right" type="submit" name="action">Cancel </button> <?=form_close();?> </div> </div> </div> </div> </div> </div> </form> <!--start container </section> <!--end container <!-- END CONTENT --> <!--end container <script> function goBack() { window.history.go(-1); } </script> <script> $("#spk").on('change', function(){ $('#spk_hidden').val($(this).val()); $("#nama_kavling").empty(); $.ajax({ url: '<?php echo site_url("action/get_rsm")?>', type: 'POST', data: {spk: $(this).val()}, dataType:'json', success : function(data){ console.log(data); for(var index in data){ $("#nama_kavling").append('<option value='+data[index].nama_kavling+'>'+data[index].nama_kavling+'</option>'); } $("#nama_kavling").material_select(); } }) .done(function(response) { $("#nama_kavling").append('<option>'+response+'</option>') }); $("#nama_kavling").on('change', function(){ $('#nama_kavling_hidden').val($(this).val()); $.ajax({ url: '<?php echo site_url("action/getdata")?>', type: 'POST', data: {nama_kavling : $(this).val()}, dataType : 'json', success : function(data){ $("#sdmingguini").val(data.sdmingguini) console.log(data); } }) }) }) $("#nama_kavling").on('change', function(){ $('#nama_kavling_hidden').val($(this).val()); $.ajax({ url: '<?php echo site_url("action/getdata")?>', type: 'POST', data: {nama_kavling : $(this).val()}, dataType : 'json', success : function(data){ $("#sdmingguini").val(data.sdmingguini) console.log(data); } }) }) </script>
foscam-android-sdk =============== Foscam Android SDK for H.264 IP Cameras (FI9821W) 05/12/2015: THIS PROJECT IS DEPRECATED. Please refer to http://foscam.us/forum/<API key>.html for future updates.
package network // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // <API key> is the network Client type <API key> struct { BaseClient } // <API key> creates an instance of the <API key> client. func <API key>(subscriptionID string) <API key> { return <API key>(DefaultBaseURI, subscriptionID) } // <API key> creates an instance of the <API key> // client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI // (sovereign clouds, Azure stack). func <API key>(baseURI string, subscriptionID string) <API key> { return <API key>{NewWithBaseURI(baseURI, subscriptionID)} } // Get retrieves the details of a <API key>. // Parameters: // resourceGroupName - the resource group name of the VirtualHub. // virtualHubName - the name of the VirtualHub. // connectionName - the name of the vpn connection. func (client <API key>) Get(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (result <API key>, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/<API key>.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetPreparer(ctx, resourceGroupName, virtualHubName, connectionName) if err != nil { err = autorest.NewErrorWithError(err, "network.<API key>", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.<API key>", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.<API key>", "Get", resp, "Failure responding to request") return } return } // GetPreparer prepares the Get request. func (client <API key>) GetPreparer(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "connectionName": autorest.Encode("path", connectionName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "virtualHubName": autorest.Encode("path", virtualHubName), } const APIVersion = "2018-11-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/<API key>/{connectionName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client <API key>) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.<API key>(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client <API key>) GetResponder(resp *http.Response) (result <API key>, err error) { err = autorest.Respond( resp, azure.<API key>(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List retrieves the details of all <API key>. // Parameters: // resourceGroupName - the resource group name of the VirtualHub. // virtualHubName - the name of the VirtualHub. func (client <API key>) List(ctx context.Context, resourceGroupName string, virtualHubName string) (result <API key>, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/<API key>.List") defer func() { sc := -1 if result.lhvncr.Response.Response != nil { sc = result.lhvncr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listNextResults req, err := client.ListPreparer(ctx, resourceGroupName, virtualHubName) if err != nil { err = autorest.NewErrorWithError(err, "network.<API key>", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.lhvncr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.<API key>", "List", resp, "Failure sending request") return } result.lhvncr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.<API key>", "List", resp, "Failure responding to request") return } if result.lhvncr.hasNextLink() && result.lhvncr.IsEmpty() { err = result.NextWithContext(ctx) return } return } // ListPreparer prepares the List request. func (client <API key>) ListPreparer(ctx context.Context, resourceGroupName string, virtualHubName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "virtualHubName": autorest.Encode("path", virtualHubName), } const APIVersion = "2018-11-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/<API key>", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client <API key>) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.<API key>(client.Client)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client <API key>) ListResponder(resp *http.Response) (result <API key>, err error) { err = autorest.Respond( resp, azure.<API key>(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client <API key>) listNextResults(ctx context.Context, lastResults <API key>) (result <API key>, err error) { req, err := lastResults.<API key>(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "network.<API key>", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "network.<API key>", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.<API key>", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client <API key>) ListComplete(ctx context.Context, resourceGroupName string, virtualHubName string) (result <API key>, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/<API key>.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx, resourceGroupName, virtualHubName) return }
var address = ''; var config = {}; var requestGroupId = 0; var readRequestsTodo = 0; var readRequestsDone = 0; var scanRequestsTodo = [0, 0, 0]; var scanRequestsDone = [0, 0, 0]; var scanResults = []; var requestSentCounter = 0; var <API key> = 0; var <API key> = 0; var requestInProgress = false; var requestQueue = []; var socket = io({ transports: ['websocket'], timeout: 10000, reconnectionDelay: 500, autoConnect: true }); socket.on('reconnect', function() { window.location.reload(); }); var <API key> = { in: <API key>, out: <API key>, anal: <API key>, func: <API key> }; $(function() { $('#config-address').on('change', function(e) { updateAddress(e.target.value); reset(); }); $('#config-scan').on('click', scan); $('#config-file').on('change', function(e) { var file = e.target.files[0]; if (!file || !/\.conf/.test(file.name)) { updateInput(''); reset(); return; } var reader = new FileReader(); reader.onload = function(e) { updateInput(e.target.result); reset(); }; reader.readAsText(file); }); $('#config-input').on('change', function(e) { $('#config-file').val(''); updateInput(e.target.value); reset(); }); $('#outputs').on('click', '.output', function(e) { toggleOutput(config[e.currentTarget.dataset.id]); }); $('#analogs') .on('change', '.form-control', function(e) { setAnalog(config[$(e.currentTarget).closest('.analog')[0].dataset.id], e.currentTarget.value); }) .on('keyup', '.form-control', function(e) { if (e.keyCode === 13) { setAnalog(config[$(e.currentTarget).closest('.analog')[0].dataset.id], e.currentTarget.value); } }); $('#functions') .on('change', '.form-control', function(e) { setFunction(config[$(e.currentTarget).closest('.function')[0].dataset.id], e.currentTarget.value); }) .on('keyup', '.form-control', function(e) { if (e.keyCode === 13) { setFunction(config[$(e.currentTarget).closest('.function')[0].dataset.id], e.currentTarget.value); } }); $(window).on('resize', resizeInput); resizeInput(); updateAddress(localStorage.ADDRESS || ''); updateInput(localStorage.INPUT || ''); reset(); }); function resizeInput() { var height = window.innerHeight - 90 - 54 - 20 - 53 - 15 - 53 - 15 - 30; $('#config-input').css('height', height + 'px'); } function updateAddress(newAddress) { newAddress = newAddress.trim(); localStorage.ADDRESS = newAddress; $('#config-address').val(newAddress); if (newAddress.length && newAddress.indexOf('.') === -1) { newAddress = '[' + newAddress + ']'; } address = newAddress; } function updateInput(newInput) { parseInput(newInput); if (!Object.keys(config).length) { newInput = 'Nieprawidłowy lub pusty plik!'; } else { localStorage.INPUT = newInput; } $('#config-input').val(newInput); } function parseInput(input) { config = {}; var re = /([A-Z0-9_-]+)\s+([0-9]+)\s+([0-9]+)\s+(in|out|anal|func)/ig; var matches; while (matches = re.exec(input)) { var name = matches[1]; config[name] = { type: matches[4], name: name, tim: parseInt(matches[2], 10), channel: parseInt(matches[3], 10), writing: false, value: null }; } } function renderIo() { var html = { inputs: [], outputs: [], analogs: [], functions: [] }; Object.keys(config).forEach(function(key) { var io = config[key]; if (io.type === 'in') { renderInput(html.inputs, io); } else if (io.type === 'out') { renderOutput(html.outputs, io); } else if (io.type === 'anal') { renderAnalog(html.analogs, io); } else if (io.type === 'func') { renderFunction(html.functions, io); } }); Object.keys(html).forEach(function(ioType) { $('#' + ioType).html(html[ioType].join('')); }); } function renderInput(html, io) { html.push( '<span class="input label label-default" data-id="', io.name, '">', io.name, '</span>' ); } function renderOutput(html, io) { html.push( '<button class="output btn btn-default" data-id="', io.name, '">', io.name, '</button>' ); } function renderAnalog(html, io) { html.push( '<div class="analog" data-id="', io.name, '"><div class="input-group"><span class="input-group-addon">', io.name, '</span><input type="number" class="form-control" min="0" max="65535" step="1"></div></div>' ); } function renderFunction(html, io) { html.push( '<div class="function" data-id="', io.name, '"><div class="input-group"><span class="input-group-addon">', io.name, '</span><input type="text" class="form-control"></div></div>' ); } function reset() { ++requestGroupId; Object.keys(config).forEach(function(key) { config[key].value = null; }); readRequestsDone = 0; readRequestsTodo = 0; requestSentCounter = 0; <API key> = 0; <API key> = 0; <API key>(); renderIo(); readAll(); } function <API key>() { $('#<API key>').text(<API key>); $('#<API key>').text(<API key>); $('#requestCounter-sent').text(requestSentCounter); } function readAll() { if (readRequestsDone !== readRequestsTodo) { return; } if (!address.length) { return; } var keys = Object.keys(config); readRequestsDone = 0; readRequestsTodo = keys.length; keys.forEach(function(key) { read(config[key]); }); requestSentCounter += readRequestsTodo; <API key>(); } function read(io) { var reqGroupId = requestGroupId; var req = { type: 'NON', code: 'GET', uri: 'coap://' + address + '/io/RD?tim=' + io.tim + '&ch=' + io.channel + '&t=' + io.type }; socket.emit('request', req, function(err, res) { if (requestGroupId !== reqGroupId) { return; } ++readRequestsDone; if (err) { ++<API key>; //console.error('Error reading %s: %s', io.name, err.message); } else if (res.payload.indexOf('0') !== 0) { ++<API key>; console.error('Error reading %s (%s): %d', io.name, res.code, res.payload.split('\n')[0]); } else { ++<API key>; <API key>[io.type](io, res); } <API key>(); if (readRequestsDone === readRequestsTodo) { setTimeout(readAll, 333); } }); } function <API key>(io, res) { var $input = $('.input[data-id="' + io.name + '"]'); if (!$input.length) { return; } $input.removeClass('label-default label-success label-danger'); io.value = res.payload.indexOf('ON') !== -1 ? true : res.payload.indexOf('OFF') !== -1 ? false : null; if (io.value === true) { $input.addClass('label-success'); } else if (io.value === false) { $input.addClass('label-danger'); } else { $input.addClass('label-default'); } } function <API key>(io, res) { if (io.writing) { return; } var $output = $('.output[data-id="' + io.name + '"]'); if (!$output.length) { return; } io.value = res.payload.indexOf('ON') !== -1 ? true : res.payload.indexOf('OFF') !== -1 ? false : null; $output .removeClass('btn-default btn-success btn-danger') .addClass(io.value === null ? 'btn-default' : io.value ? 'btn-success' : 'btn-danger'); } function <API key>(io, res) { if (io.writing) { return; } var $analog = $('.analog[data-id="' + io.name + '"]'); var $input = $analog.find('.form-control'); if (!$analog.length || document.activeElement === $input[0]) { return; } io.value = parseInt(res.payload.split('\n')[3], 10) || 0; $input.val(io.value); } function <API key>(io, res) { if (io.writing) { return; } var $function = $('.function[data-id="' + io.name + '"]'); var $input = $function.find('.form-control'); if (!$function.length || document.activeElement === $input[0]) { return; } io.value = res.payload.trim().split('\n')[3]; if (io.value === undefined) { io.value = ''; } $input.val(io.value); } function toggleOutput(io) { if (io.writing) { return; } io.writing = true; var $output = $('.output[data-id="' + io.name + '"]'); $output .removeClass('btn-default btn-success btn-danger') .addClass('btn-warning'); ++requestSentCounter; <API key>(); var reqGroupId = requestGroupId; var req = { type: 'NON', code: 'POST', uri: 'coap://' + address + '/io/WD?tim=' + io.tim + '&ch=' + io.channel + '&t=' + io.type + '&tD=' + (io.value ? 'OFF' : 'ON') }; socket.emit('request', req, function(err, res) { if (requestGroupId !== reqGroupId) { return; } io.writing = false; if (err) { ++<API key>; console.error('Error writing %s: %s', io.name, err.message); } else if (res.payload.indexOf('0') !== 0) { ++<API key>; console.error('Error writing %s (%s): %d', io.name, res.code, res.payload.split('\n')[0]); } else { ++<API key>; io.value = !io.value; } $output .removeClass('btn-warning') .addClass(io.value === null ? 'btn-default' : io.value ? 'btn-success' : 'btn-danger'); <API key>(); }); } function setAnalog(io, value) { value = parseInt(value, 10); if (io.writing || isNaN(value) || value < 0 || value > 0xFFFF) { return; } io.writing = true; var $analog = $('.analog[data-id="' + io.name + '"]'); var $input = $analog.find('.form-control'); $analog.addClass('is-writing'); $input.attr('readonly', true); ++requestSentCounter; <API key>(); var reqGroupId = requestGroupId; var req = { type: 'NON', code: 'POST', uri: 'coap://' + address + '/io/WD?tim=' + io.tim + '&ch=' + io.channel + '&t=' + io.type + '&tD=' + value }; socket.emit('request', req, function(err, res) { if (requestGroupId !== reqGroupId) { return; } $analog.removeClass('is-writing'); io.writing = false; if (err) { ++<API key>; console.error('Error writing %s: %s', io.name, err.message); } else if (res.payload.indexOf('0') !== 0) { ++<API key>; console.error('Error writing %s (%s): %d', io.name, res.code, res.payload.split('\n')[0]); } else { ++<API key>; io.value = value; $input.val(value).attr('readonly', false); } <API key>(); }); } function setFunction(io, value) { if (io.writing) { return; } io.writing = true; var $function = $('.function[data-id="' + io.name + '"]'); var $input = $function.find('.form-control'); $function.addClass('is-writing'); $input.attr('readonly', true); ++requestSentCounter; <API key>(); var reqGroupId = requestGroupId; var req = { type: 'NON', code: 'POST', uri: 'coap://' + address + '/io/WD?tim=' + io.tim + '&ch=' + io.channel + '&t=' + io.type + '&tD=' + value }; socket.emit('request', req, function(err, res) { if (requestGroupId !== reqGroupId) { return; } $function.removeClass('is-writing'); io.writing = false; if (err) { ++<API key>; console.error('Error writing %s: %s', io.name, err.message); } else if (res.payload.indexOf('0') !== 0) { ++<API key>; console.error('Error writing %s (%s): %d', io.name, res.code, res.payload.split('\n')[0]); } else { ++<API key>; io.value = value; $input.val(value).attr('readonly', false); } <API key>(); }); } function unlockAfterScan() { scanRequestsDone = [0, 0]; scanRequestsTodo = [0, 0]; scanResults = []; $('#config').find('.form-control').prop('disabled', false); } function scan() { if (!address.length || scanRequestsTodo[0] !== 0) { return; } updateInput(''); reset(); $('#config').find('.form-control').prop('disabled', true); var req = { type: 'CON', code: 'GET', uri: 'coap://' + address + '/io/TDisc' }; var options = { exchangeTimeout: 10000, transactionTimeout: 1000, maxRetransmit: 3, blockSize: 64 }; <API key>(++requestSentCounter); queueRequest(req, options, function(err, res) { if (err) { <API key>(++<API key>); unlockAfterScan(); return console.error("Error scanning: %s", err.message); } <API key>(++<API key>); var tims = res.payload.split('\n')[1].split(','); scanRequestsDone = [0, 0]; scanRequestsTodo = [tims.length, 0]; scanResults = []; tims.forEach(function(timId) { scanTim(parseInt(timId.trim(), 10)); }); }); } function scanTim(timId) { var req = { type: 'CON', code: 'GET', uri: 'coap://' + address + '/io/CDisc?tim=' + timId }; var options = { exchangeTimeout: 10000, transactionTimeout: 1000, maxRetransmit: 3, blockSize: 64 }; <API key>(++requestSentCounter); queueRequest(req, options, function(err, res) { if (err) { <API key>(++<API key>); unlockAfterScan(); return console.error("Error scanning TIM %d: %s", timId, err.message); } <API key>(++<API key>); ++scanRequestsDone[0]; var lines = res.payload.split('\n'); var channelIds = lines[2].split(','); var transducerNames = lines[3].replace(/"/g, '').split(','); scanRequestsTodo[1] += channelIds.length; channelIds.forEach(function(channelId, i) { setTimeout( scanChannel, Math.round(10 + Math.random() * 200), timId, parseInt(channelId.trim(), 10), transducerNames[i] ); }); }); } function scanChannel(timId, channelId, transducerName) { var req = { type: 'CON', code: 'GET', uri: 'coap://' + address + '/io/RTeds?tim=' + timId + '&ch=' + channelId + '&TT=4' }; var options = { exchangeTimeout: 10000, transactionTimeout: 1000, maxRetransmit: 3, blockSize: 64 }; <API key>(++requestSentCounter); queueRequest(req, options, function(err, res) { if (err) { <API key>(++<API key>); unlockAfterScan(); return console.error("Error scanning channel %d of TIM %d: %s", channelId, timId, err.message); } <API key>(++<API key>); ++scanRequestsDone[1]; var type = null; if (/Digital Input/i.test(res.payload)) { type = 'in'; } else if (/Digital Output/i.test(res.payload)) { type = 'out'; } else if (/(Digit.*?|Analog|Step g) (Input|Output)/i.test(res.payload)) { type = 'anal'; } if (type) { scanResults.push({ timId: timId, channelId: channelId, name: (transducerName || ('T_' + timId + '_' + channelId)).trim(), type: type }); } if (scanRequestsDone[1] === scanRequestsTodo[1]) { <API key>(); } }); } function <API key>() { var input = []; scanResults.sort(function(a, b) { var r = a.timId - b.timId; if (r === 0) { r = a.channelId - b.channelId; } return r; }); scanResults.forEach(function(io) { input.push(io.name + ' ' + io.timId + ' ' + io.channelId + ' ' + io.type); }); unlockAfterScan(); updateInput(input.join('\n')); renderIo(); readAll(); } function queueRequest(req, options, callback) { requestQueue.push(req, options, callback); if (!requestInProgress) { sendNextRequest(); } } function sendNextRequest() { var req = requestQueue.shift(); var options = requestQueue.shift(); var callback = requestQueue.shift(); if (!callback) { return; } requestInProgress = true; socket.emit('request', req, options, function(err, res) { requestInProgress = false; callback(err, res); sendNextRequest(); }); }
<ul class="breadcrumb"> {% for url, label in breadcrumbs %} <li> {% ifnotequal forloop.counter breadcrumbs_total %} <a href="{{ url }}">{{ label|safe }}</a> {% else %} {{ label|safe }} {% endifnotequal %} {% if not forloop.last %} <span class="divider">/</span> {% endif %} </li> {% endfor %} </ul>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>metacoq-erasure: 3 m 5 s</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file: <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif] </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.9.0 / metacoq-erasure - 1.0~alpha+8.9</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> metacoq-erasure <small> 1.0~alpha+8.9 <span class="label label-success">3 m 5 s</span> </small> </h1> <p><em><script>document.write(moment("2020-07-26 11:43:01 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-26 11:43:01 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.12 <API key> of OCaml conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.9.0 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.04.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.04.2 Official 4.04.2 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;matthieu.sozeau@inria.fr&quot; homepage: &quot;https://metacoq.github.io/metacoq&quot; dev-repo: &quot;git+https://github.com/MetaCoq/metacoq.git#coq-8.8&quot; bug-reports: &quot;https://github.com/MetaCoq/metacoq/issues&quot; authors: [&quot;Abhishek Anand &lt;aa755@cs.cornell.edu&gt;&quot; &quot;Simon Boulier &lt;simon.boulier@inria.fr&gt;&quot; &quot;Cyril Cohen &lt;cyril.cohen@inria.fr&gt;&quot; &quot;Yannick Forster &lt;forster@ps.uni-saarland.de&gt;&quot; &quot;Fabian Kunze &lt;fkunze@fakusb.de&gt;&quot; &quot;Gregory Malecha &lt;gmalecha@gmail.com&gt;&quot; &quot;Matthieu Sozeau &lt;matthieu.sozeau@inria.fr&gt;&quot; &quot;Nicolas Tabareau &lt;nicolas.tabareau@inria.fr&gt;&quot; &quot;Théo Winterhalter &lt;theo.winterhalter@inria.fr&gt;&quot; ] license: &quot;MIT&quot; build: [ [&quot;sh&quot; &quot;./configure.sh&quot;] [make &quot;-j%{jobs}%&quot; &quot;-C&quot; &quot;erasure&quot;] [make &quot;test-suite&quot;] {with-test} ] install: [ [make &quot;-C&quot; &quot;erasure&quot; &quot;install&quot;] ] depends: [ &quot;ocaml&quot; {&gt; &quot;4.02.3&quot;} &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} &quot;<API key>&quot; {= version} &quot;coq-metacoq-checker&quot; {= version} &quot;coq-metacoq-pcuic&quot; {= version} &quot;<API key>&quot; {= version} ] synopsis: &quot;Implementation and verification of an erasure procedure for Coq&quot; description: &quot;&quot;&quot; MetaCoq is a meta-programming framework for Coq. The Erasure module provides a complete specification of Coq&#39;s so-called \&quot;extraction\&quot; procedure, starting from the PCUIC calculus and targeting untyped call-by-value lambda-calculus. The `erasure` function translates types and proofs in well-typed terms into a dummy `tBox` constructor, following closely P. Letouzey&#39;s PhD thesis. &quot;&quot;&quot; url { src: &quot;https://github.com/MetaCoq/metacoq/archive/1.0-alpha+8.9.tar.gz&quot; checksum: &quot;sha256=<SHA256-like>&quot; }</pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-metacoq-erasure.1.0~alpha+8.9 coq.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 2h opam install -y --deps-only coq-metacoq-erasure.1.0~alpha+8.9 coq.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>25 m 27 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 2h opam install -y -v coq-metacoq-erasure.1.0~alpha+8.9 coq.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>3 m 5 s</dd> </dl> <h2>Installation size</h2> <p>Total: 13 M</p> <ul> <li>3 M <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/ErasureFunction.vo</code></li> <li>1 M <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/ErasureCorrectness.vo</code></li> <li>1 M <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/SafeErasureFunction.vo</code></li> <li>980 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/ESubstitution.vo</code></li> <li>897 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/<API key>.cmxs</code></li> <li>866 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/SafeTemplateErasure.vo</code></li> <li>824 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/Prelim.vo</code></li> <li>794 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EArities.vo</code></li> <li>793 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/Extraction.vo</code></li> <li>756 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EInversion.vo</code></li> <li>364 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/ELiftSubst.vo</code></li> <li>177 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/<API key>.cmi</code></li> <li>172 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/Extract.vo</code></li> <li>158 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/ErasureCorrectness.glob</code></li> <li>123 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/ELiftSubst.glob</code></li> <li>114 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EAll.vo</code></li> <li>114 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EWcbvEval.vo</code></li> <li>108 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/ErasureFunction.glob</code></li> <li>97 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EAstUtils.vo</code></li> <li>79 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EArities.glob</code></li> <li>77 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/SafeErasureFunction.glob</code></li> <li>70 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/<API key>.cmx</code></li> <li>68 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EWcbvEval.glob</code></li> <li>66 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/ESubstitution.glob</code></li> <li>63 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EAst.vo</code></li> <li>63 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EPretty.vo</code></li> <li>53 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/ETyping.vo</code></li> <li>49 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/Prelim.glob</code></li> <li>49 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/ErasureCorrectness.v</code></li> <li>42 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EInduction.vo</code></li> <li>38 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/Extract.glob</code></li> <li>37 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EAstUtils.glob</code></li> <li>36 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EWndEval.vo</code></li> <li>34 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/Loader.vo</code></li> <li>30 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/ErasureFunction.v</code></li> <li>26 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/SafeErasureFunction.v</code></li> <li>26 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/SafeTemplateErasure.glob</code></li> <li>26 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EPretty.glob</code></li> <li>23 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EWcbvEval.v</code></li> <li>22 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EArities.v</code></li> <li>22 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EInversion.glob</code></li> <li>17 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/ELiftSubst.v</code></li> <li>15 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/ESubstitution.v</code></li> <li>13 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EAst.glob</code></li> <li>12 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/Prelim.v</code></li> <li>11 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/ETyping.glob</code></li> <li>9 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/SafeTemplateErasure.v</code></li> <li>8 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EAstUtils.v</code></li> <li>8 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EInduction.glob</code></li> <li>7 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/Extract.v</code></li> <li>6 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EPretty.v</code></li> <li>6 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/<API key>.cmxa</code></li> <li>6 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EAst.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/ETyping.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EWndEval.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EInversion.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EInduction.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EWndEval.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/Extraction.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/Extraction.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EAll.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/Loader.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/Loader.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/MetaCoq/Erasure/EAll.v</code></li> </ul> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq-metacoq-erasure.1.0~alpha+8.9</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https: </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Matrix { public class Matrix<T> where T : struct { private T[,] matrix; public Matrix(int x, int y) { matrix = new T[x, y]; } public int LengthX { get { return this.matrix.GetLength(0); } } public int LengthY { get { return this.matrix.GetLength(1); } } public T this [int x, int y] { get { if (matrix.GetLength(0) > x && matrix.GetLength(1) > y) { return this.matrix[x, y]; } else { throw new <API key>(); } } set { if (matrix.GetLength(0) > x && matrix.GetLength(1) > y) { this.matrix[x, y] = value; } else { throw new <API key>(); } } } private static bool <API key>(Matrix<T> matrix1, Matrix<T> matrix2) { if (matrix1.matrix.GetLength(0) == matrix2.matrix.GetLength(0) && matrix1.matrix.GetLength(1) == matrix2.matrix.GetLength(1)) { return true; } else { return false; } } private static bool <API key>(Matrix<T> matrix1, Matrix<T> matrix2) { if (matrix1.LengthX == matrix2.LengthY && matrix1.LengthY == matrix2.LengthX) { return true; } else { return false; } } public static Matrix<T> operator +(Matrix<T> matrix1, Matrix<T> matrix2) { Matrix<T> newMatrix = new Matrix<T>(matrix1.LengthX, matrix1.LengthY); dynamic matrice1 = matrix1; dynamic matrice2 = matrix2; if (Matrix<T>.<API key>(matrix1, matrix2)) { for (int i = 0; i < matrix1.LengthX; i++) { for (int j = 0; j < matrix1.LengthY; j++) { newMatrix[i, j] = matrice1[i, j] + matrice2[i, j]; } } } else { throw new <API key>(); } return newMatrix; } public static Matrix<T> operator -(Matrix<T> matrix1, Matrix<T> matrix2) { Matrix<T> newMatrix = new Matrix<T>(matrix1.LengthX, matrix1.LengthY); dynamic matrice1 = matrix1; dynamic matrice2 = matrix2; if (Matrix<T>.<API key>(matrix1, matrix2)) { for (int i = 0; i < matrix1.LengthX; i++) { for (int j = 0; j < matrix1.LengthY; j++) { newMatrix[i, j] = matrice1[i, j] - matrice2[i, j]; } } } else { throw new <API key>(); } return newMatrix; } public static Matrix<T> operator *(Matrix<T> matrix1, Matrix<T> matrix2) { Matrix<T> newMatrix = new Matrix<T>(matrix1.LengthX, matrix2.LengthY); dynamic matrice1 = matrix1; dynamic matrice2 = matrix2; if (Matrix<T>.<API key>(matrix1, matrix2)) { for (int i = 0; i < matrix1.LengthX; i++) { for (int j = 0; j < matrix1.LengthY; j++) { newMatrix[i, j] = matrice1[i, j] * matrice2[j, i]; } } } else { throw new <API key>(); } return newMatrix; } public static bool operator true(T elementOfMetrix) { return elementOfMetrix.Equals(default(T)); } } }
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Kategori extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('Kategori_model'); } public function index($page = 0){ if(!$this->session->userdata('sesilogin')) { redirect('login','refresh'); } else { // cek if page isset if(isset($page)) { if(is_numeric($page)) { $start = $page; } else { $start = 0; } } if($this->input->post('cari')) { $search = $this->input->post('cari'); $kategori = $this->Kategori_model->get_search_kategori($search, 0, <API key>); $jumlah = $kategori['jumlah']; $cari = $search; } else { $kategori = $this->Kategori_model->get_semua_kategori($start); $semua_kategori = $this->Kategori_model->get_semua_kategori(0, <API key>); $jumlah = $semua_kategori['jumlah']; $cari = ''; } $this->load->library('pagination'); $config['base_url'] = base_url('kategori/list'); $config['total_rows'] = $jumlah; $config['per_page'] = 10; $config['uri_segment'] = 3; $config['num_links'] = 3; $config['full_tag_open'] = '<ul class="pagination">'; $config['full_tag_close'] = '</ul>'; $config['next_link'] = '»'; $config['next_tag_open'] = '<li>'; $config['next_tag_close'] = '</li>'; $config['prev_link'] = '«'; $config['prev_tag_open'] = '<li>'; $config['prev_tag_close'] = '</li>'; $config['cur_tag_open'] = '<li class="active"><a href=" $config['cur_tag_close'] = '</a></li>'; $config['num_tag_open'] = '<li>'; $config['num_tag_close'] = '</li>'; $this->pagination->initialize($config); if($cari != '') { $paginasi = ''; } else { $paginasi = $this->pagination->create_links(); } $_data = array( 'sesilogin' => $this->session->userdata('sesilogin'), 'halaman' => 'kategori', 'kategori' => $kategori['hasil'], 'page' => $start + 1, 'paginasi' => $paginasi, 'jumlah' => $jumlah, 'cari' => $cari ); $_views['title'] = 'Daftar kategori'; $_views['sidemenu'] = $this->load->view('include/menu/side_menu', $_data, TRUE); $_views['header'] = $this->load->view('include/header/header', $_data, TRUE); $_views['content'] = $this->load->view('include/content/kategori/kategori_list', $_data, TRUE); $_views['modal'] = $this->load->view('include/modal/modal_content', $_data, TRUE); $_views['footer'] = $this->load->view('include/footer/footer', $_data, TRUE); $_views['jscript'] = $this->load->view('include/ekstensi/javascript', $_data, TRUE); $this->load->view('template/cms_template', $_views); } } public function add(){ if(!$this->session->userdata('sesilogin')) { redirect('login','refresh'); } else { $_data = array( 'sesilogin' => $this->session->userdata('sesilogin'), 'halaman' => 'kategori' ); $_views['title'] = 'Tambah kategori'; $_views['sidemenu'] = $this->load->view('include/menu/side_menu', $_data, TRUE); $_views['header'] = $this->load->view('include/header/header', $_data, TRUE); $_views['content'] = $this->load->view('include/content/kategori/kategori_add', $_data, TRUE); $_views['modal'] = $this->load->view('include/modal/modal_content', $_data, TRUE); $_views['footer'] = $this->load->view('include/footer/footer', $_data, TRUE); $_views['jscript'] = $this->load->view('include/ekstensi/javascript', $_data, TRUE); $this->load->view('template/cms_template', $_views); } } public function add_save(){ if(!$this->session->userdata('sesilogin')) { redirect('login','refresh'); } else { if (!empty($this->input->post('nama'))) { $nama = $this->input->post('nama'); } else { $nama = ""; }; $_data = array( 'kategori_nama' => $nama, '<API key>' => tanggalhariini(), '<API key>' => tanggalhariini(), 'kategori_updateoleh' => sesilogin('id') ); $masukan_kategori = $this->Kategori_model->insert_kategori($_data); if($masukan_kategori['status'] == "success") { $pesannya = " <script type='text/javascript'> successtoastr('" .$masukan_kategori['hasil']. "'); </script> "; $this->session->set_flashdata('success', $pesannya); redirect(base_url('kategori/list'),'refresh'); } else { $pesannya = " <script type='text/javascript'> errortoastr('" .$masukan_kategori['hasil']. "'); </script> "; $this->session->set_flashdata('error', $pesannya); redirect(base_url('kategori/tambah'),'refresh'); } } } public function update($id){ if(!$this->session->userdata('sesilogin')) { redirect('login','refresh'); } else { // get data kategori $kategori = $this->Kategori_model-><API key>($id); $_data = array( 'sesilogin' => $this->session->userdata('sesilogin'), 'halaman' => 'kategori', 'kategori' => $kategori['hasil'] ); $_views['title'] = 'Edit kategori'; $_views['sidemenu'] = $this->load->view('include/menu/side_menu', $_data, TRUE); $_views['header'] = $this->load->view('include/header/header', $_data, TRUE); $_views['content'] = $this->load->view('include/content/kategori/kategori_edit', $_data, TRUE); $_views['modal'] = $this->load->view('include/modal/modal_content', $_data, TRUE); $_views['footer'] = $this->load->view('include/footer/footer', $_data, TRUE); $_views['jscript'] = $this->load->view('include/ekstensi/javascript', $_data, TRUE); $this->load->view('template/cms_template', $_views); } } public function update_save(){ if(!$this->session->userdata('sesilogin')) { redirect('login','refresh'); } else { $id = $this->input->post('id'); if (!empty($this->input->post('nama'))) { $nama = $this->input->post('nama'); } else { $nama = ""; }; $_data = array( 'kategori_nama' => $nama, '<API key>' => tanggalhariini(), 'kategori_updateoleh' => sesilogin('id') ); $updatean_kategori = $this->Kategori_model->update_kategori($id, $_data); if($updatean_kategori['status'] == "success") { $pesannya = " <script type='text/javascript'> successtoastr('" .$updatean_kategori['hasil']. "'); </script> "; $this->session->set_flashdata('success', $pesannya); redirect(base_url('kategori/list'),'refresh'); } else { $pesannya = " <script type='text/javascript'> errortoastr('" .$updatean_kategori['hasil']. "'); </script> "; $this->session->set_flashdata('error', $pesannya); redirect(base_url('kategori/tambah'),'refresh'); } } } public function view($id){ if(!$this->session->userdata('sesilogin')) { redirect('login','refresh'); } else { // get data kategori $kategori = $this->Kategori_model-><API key>($id); $_data = array( 'sesilogin' => $this->session->userdata('sesilogin'), 'halaman' => 'kategori', 'kategori' => $kategori['hasil'] ); $_views['title'] = 'Dashboard'; $_views['sidemenu'] = $this->load->view('include/menu/side_menu', $_data, TRUE); $_views['header'] = $this->load->view('include/header/header', $_data, TRUE); $_views['content'] = $this->load->view('include/content/kategori/kategori_view', $_data, TRUE); $_views['modal'] = $this->load->view('include/modal/modal_content', $_data, TRUE); $_views['footer'] = $this->load->view('include/footer/footer', $_data, TRUE); $_views['jscript'] = $this->load->view('include/ekstensi/javascript', $_data, TRUE); $this->load->view('template/cms_template', $_views); } } public function delete($id){ if(!$this->session->userdata('sesilogin')) { redirect('login','refresh'); } else { $hapus_kategori = $this->Kategori_model->delete_kategori($id); if($hapus_kategori['status'] == "success") { $pesannya = " <script type='text/javascript'> successtoastr('" .$hapus_kategori['hasil']. "'); </script> "; $this->session->set_flashdata('success', $pesannya); redirect(base_url('kategori/list'),'refresh'); } else { $pesannya = " <script type='text/javascript'> errortoastr('" .$hapus_kategori['hasil']. "'); </script> "; $this->session->set_flashdata('error', $pesannya); redirect(base_url('kategori/list'),'refresh'); } } } } /* End of file Kategori.php */ /* Location: ./application/controllers/Kategori.php */
from .stats_view_base import StatsViewSwagger, <API key> from .<API key> import <API key> class <API key>(<API key>): """API View - Dataverse counts by Month.""" # Define the swagger attributes # Note: api_path must match the path in urls.py api_path = '/dataverses/count/monthly' summary = ('Number of published Dataverses by' ' the month they were created*. (*' ' Not month published)') description = ('Returns a list of counts and' ' cumulative counts of all Dataverses added in a month') description_200 = 'A list of Dataverse counts by month' param_names = StatsViewSwagger.PARAM_DV_API_KEY +\ StatsViewSwagger.BASIC_DATE_PARAMS +\ StatsViewSwagger.PUBLISH_PARAMS +\ StatsViewSwagger.PRETTY_JSON_PARAM +\ StatsViewSwagger.PARAM_AS_CSV tags = [StatsViewSwagger.TAG_DATAVERSES] def get_stats_result(self, request): """Return the StatsResult object for this statistic""" stats_datasets = <API key>(**request.GET.dict()) pub_state = self.get_pub_state(request) if pub_state == self.PUB_STATE_ALL: stats_result = stats_datasets.<API key>() elif pub_state == self.<API key>: stats_result = stats_datasets.<API key>() else: stats_result = stats_datasets.<API key>() return stats_result class <API key>(<API key>): """API View - Total count of all Dataverses""" # Define the swagger attributes # Note: api_path must match the path in urls.py api_path = '/dataverses/count' summary = ('Simple count of published Dataverses') description = ('Returns number of published Dataverses') description_200 = 'Number of published Dataverses' param_names = StatsViewSwagger.PARAM_DV_API_KEY + StatsViewSwagger.PUBLISH_PARAMS + StatsViewSwagger.PRETTY_JSON_PARAM tags = [StatsViewSwagger.TAG_DATAVERSES] result_name = StatsViewSwagger.<API key> def get_stats_result(self, request): """Return the StatsResult object for this statistic""" stats_datasets = <API key>(**request.GET.dict()) pub_state = self.get_pub_state(request) if pub_state == self.PUB_STATE_ALL: stats_result = stats_datasets.get_dataverse_count() elif pub_state == self.<API key>: stats_result = stats_datasets.<API key>() else: stats_result = stats_datasets.<API key>() return stats_result class <API key>(<API key>): """API View - Number of Dataverses by Affiliation""" # Define the swagger attributes # Note: api_path must match the path in urls.py api_path = '/dataverses/count/by-affiliation' summary = ('Number of Dataverses by Affiliation') description = ('Number of Dataverses by Affiliation.') description_200 = 'Number of published Dataverses by Affiliation.' param_names = StatsViewSwagger.PARAM_DV_API_KEY\ + StatsViewSwagger.PUBLISH_PARAMS\ + StatsViewSwagger.PRETTY_JSON_PARAM\ + StatsViewSwagger.PARAM_AS_CSV result_name = StatsViewSwagger.<API key> tags = [StatsViewSwagger.TAG_DATAVERSES] def get_stats_result(self, request): """Return the StatsResult object for this statistic""" stats_datasets = <API key>(**request.GET.dict()) pub_state = self.get_pub_state(request) if pub_state == self.PUB_STATE_ALL: stats_result = stats_datasets.<API key>() elif pub_state == self.<API key>: stats_result = stats_datasets.<API key>() else: stats_result = stats_datasets.<API key>() return stats_result class DataverseTypeCounts(<API key>): # Define the swagger attributes # Note: api_path must match the path in urls.py api_path = '/dataverses/count/by-type' summary = ('Number of Dataverses by Type') description = ('Number of Dataverses by Type.') description_200 = 'Number of published Dataverses by Type.' param_names = StatsViewSwagger.PARAM_DV_API_KEY + StatsViewSwagger.PUBLISH_PARAMS +\ StatsViewSwagger.PRETTY_JSON_PARAM +\ StatsViewSwagger.<API key> +\ StatsViewSwagger.PARAM_AS_CSV result_name = StatsViewSwagger.<API key> tags = [StatsViewSwagger.TAG_DATAVERSES] def <API key>(self, request): """Return the result of the "?show_uncategorized" query string param""" show_uncategorized = request.GET.get('show_uncategorized', False) if show_uncategorized is True or show_uncategorized == 'true': return True return False def get_stats_result(self, request): """Return the StatsResult object for this statistic""" stats_datasets = <API key>(**request.GET.dict()) if self.<API key>(request): <API key> = False else: <API key> = True pub_state = self.get_pub_state(request) if pub_state == self.PUB_STATE_ALL: stats_result = stats_datasets.<API key>(<API key>) elif pub_state == self.<API key>: stats_result = stats_datasets.<API key>(<API key>) else: stats_result = stats_datasets.<API key>(<API key>) return stats_result
// Generated by class-dump 3.5 (64 bit). #import "CDStructures.h" #import <IDEKit/<API key>.h> @interface <API key> : <API key> { } + (id)<API key>:(id)arg1; @end
package goldrush; /** * @author Reina Michele cl418656 * @author Bonissone Davidecl427113 */ public class BoniMichele extends GoldDigger{ int t=0; int j=99; @Override public int chooseDiggingSite(int[] distances) { for (int i=0; i<distances.length; i++){ if (t==0){ if (distances[i]==140) { j=i; t++; } } else if (t<3) { if (distances[i]== 30) { j=i; t=0; } } else { if (distances[i]== 200) { j=i; t=0; } } } return j; } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace Paradix { public sealed class KeyboardController : IController { // TODO : List of keys UP / DOWN / PRESSED / RELEASED public PlayerIndex Player { get; set; } = PlayerIndex.One; public KeyboardState CurrentState { get; private set; } public KeyboardState PreviousState { get; private set; } public KeyboardController (PlayerIndex player = PlayerIndex.One) { Player = player; CurrentState = Keyboard.GetState (Player); PreviousState = CurrentState; } public bool IsKeyDown (Keys key) { return CurrentState.IsKeyDown (key); } public bool IsKeyUp (Keys key) { return CurrentState.IsKeyUp (key); } public bool IsKeyPressed (Keys key) { return CurrentState.IsKeyDown (key) && PreviousState.IsKeyUp (key); } public bool IsKeyReleased (Keys key) { return PreviousState.IsKeyDown (key) && CurrentState.IsKeyUp (key); } public void Flush (GameTime gameTime) { PreviousState = CurrentState; CurrentState = Keyboard.GetState (Player); } } }
module.exports = { parserOptions: { sourceType: 'script', }, };
package com.docuware.dev.Extensions; import java.io.Closeable; import java.io.InputStream; /** * * @author Patrick */ public class EasyCheckoutResult implements Closeable { private String EncodedFileName; public String getEncodedFileName() { return EncodedFileName; } void setEncodedFileName(String data) { EncodedFileName = data; } private <API key><InputStream> response; public <API key><InputStream> getResponse() { return response; } void setResponse(<API key><InputStream> data) { response = data; } @Override public void close() { this.response.close(); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CharacterModelLib.Models { public class CharacterProject : NotifyableBase { public CharacterProject() { characterCollection = new <API key><Character>(); } void <API key>(object sender, System.Collections.Specialized.<API key> e) { <API key>("CharacterCollection"); } Character selectedCharacter; public Character SelectedCharacter { get { return selectedCharacter; } set { if (selectedCharacter != null) { selectedCharacter.PropertyChanged -= <API key>; } selectedCharacter = value; if (selectedCharacter != null) { selectedCharacter.PropertyChanged += <API key>; } <API key>("SelectedCharacter"); <API key>("NextCharacter"); <API key>("PreviousCharacter"); } } public Character NextCharacter { get { if (selectedCharacter == null) { return CharacterCollection[0]; } int index = CharacterCollection.IndexOf(selectedCharacter); if (index >= CharacterCollection.Count - 1) { return CharacterCollection[0]; } else { return CharacterCollection[index + 1]; } } } public Character PreviousCharacter { get { if (selectedCharacter == null) { return CharacterCollection[CharacterCollection.Count - 1]; } int index = CharacterCollection.IndexOf(selectedCharacter); if (index <= 0) { return CharacterCollection[CharacterCollection.Count - 1]; } else { return CharacterCollection[index - 1]; } } } private void <API key>(object sender, System.ComponentModel.<API key> e) { <API key>("SelectedCharacter." + e.PropertyName); //<API key>(e.PropertyName); //<API key>("SelectedCharacter"); } private <API key><Character> characterCollection; public <API key><Character> CharacterCollection { get { return characterCollection; } set { if (characterCollection != null) { characterCollection.CollectionChanged -= <API key>; } characterCollection = value; if (characterCollection != null) { characterCollection.CollectionChanged += <API key>; } <API key>("CharacterCollection"); } } private string name; public string Name { get { return name; } set { name = value; <API key>("Name"); } } private string projectPath; public string ProjectPath { get { return projectPath; } set { projectPath = value; <API key>("ProjectPath"); } } public override string ToString() { return base.ToString() + ": Name=" + Name; } public override bool Equals(object obj) { if (obj.GetType() == this.GetType()) { return ((obj as CharacterProject).Name == this.Name); } return false; } public override int GetHashCode() { return base.GetHashCode(); } } }
import uuid from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import BaseUserManager from django.utils import timezone from <API key>.models import BaseUserRole from <API key>.models.base_base_profile import EXPERT_USER_TYPE MAX_USERNAME_LENGTH = 30 class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): """ Creates and saves an User with the given email and password. """ now = timezone.now() if not email: raise ValueError('An email address must be provided.') email = self.normalize_email(email) if "is_active" not in extra_fields: extra_fields["is_active"] = True if "username" not in extra_fields: # For now we need to have a unique id that is at # most 30 characters long. Using uuid and truncating. # Ideally username goes away entirely at some point # since we're really using email. If we have to keep # username for some reason then we could switch over # to a string version of the pk which is guaranteed # be unique. extra_fields["username"] = str(uuid.uuid4())[:MAX_USERNAME_LENGTH] user = self.model(email=email, is_staff=is_staff, is_superuser=is_superuser, last_login=None, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email=None, password=None, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): return self._create_user(email, password, True, True, **extra_fields) class User(AbstractUser): # Override the parent email field to add uniqueness constraint email = models.EmailField(blank=True, unique=True) objects = UserManager() class Meta: db_table = 'auth_user' managed = settings.<API key> def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) self.startup = None self.team_member = None self.profile = None self.user_finalist_roles = None class <API key>(Exception): pass def __str__(self): return self.email def full_name(self): fn = self.first_name ln = self.last_name if fn and ln: name = u"%s %s" % (fn, ln) else: name = str(self.email) return name def user_phone(self): return self._get_profile().phone def image_url(self): return self._get_profile().image_url() def team_member_id(self): return self.team_member.id if self._get_member() else '' def user_title(self): return self.<API key>()['title'] def user_twitter_handle(self): return self._get_profile().twitter_handle def user_linked_in_url(self): return self._get_profile().linked_in_url def user_facebook_url(self): return self._get_profile().facebook_url def <API key>(self): return self._get_profile().<API key> def type(self): return self._get_profile().user_type def startup_name(self): return self.<API key>()['company'] def <API key>(self): if self._is_expert() and self._has_expert_details(): profile = self._get_profile() title = profile.title company = profile.company return { "title": title, "company": company } self._get_member() title = self.team_member.title if self.team_member else "" company = self.startup.name if self._get_startup() else None return { "title": title, "company": company } def _has_expert_details(self): if self._is_expert(): profile = self._get_profile() return True if profile.title or profile.company else False def startup_industry(self): return self.startup.primary_industry if self._get_startup() else None def <API key>(self): industry = ( self.startup.primary_industry if self._get_startup() else None) return industry.parent if industry and industry.parent else industry def <API key>(self): if self._get_startup(): return [startup_status.<API key>.startup_status for startup_status in self.startup.startupstatus_set.all()] def finalist_user_roles(self): if not self.user_finalist_roles: finalist_roles = BaseUserRole.FINALIST_USER_ROLES self.user_finalist_roles = self.<API key>.filter( <API key>=finalist_roles ).values_list('program_role__name', flat=True).distinct() return list(self.user_finalist_roles) def program(self): return self.startup.current_program() if self._get_startup() else None def location(self): program = self.program() return program.program_family.name if program else None def year(self): program = self.program() return program.start_date.year if program else None def is_team_member(self): return True if self._get_member() else False def _get_startup(self): if not self.startup: self._get_member() if self.team_member: self.startup = self.team_member.startup return self.startup def _get_member(self): if not self.team_member: self.team_member = self.<API key>.last() return self.team_member def _get_profile(self): if self.profile: return self.profile self.profile = self.get_profile() return self.profile def has_a_finalist_role(self): return len(self.finalist_user_roles()) > 0 def _is_expert(self): profile = self._get_profile() return profile.user_type == EXPERT_USER_TYPE.lower()
package experiments; import java.io.File; import java.util.Arrays; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import data.StateImpl; import datahandler.word2vec.<API key>; import state2vec.State2Vec; public class State2VecTest { protected static final Logger logger = LoggerFactory.getLogger(State2VecTest.class); public State2VecTest(File file, String run) throws Exception { List<Integer> windowSizes; List<Double> learningRates; if(run.equals("0")){ logger.info("Run 0"); windowSizes = Arrays.asList(5); learningRates = Arrays.asList(0.025, 0.1); } else if(run.equals("1")) { logger.info("Run 1"); windowSizes = Arrays.asList(5); learningRates = Arrays.asList(0.1); } else if(run.equals("2")) { logger.info("Run 2"); windowSizes = Arrays.asList(10); learningRates = Arrays.asList(0.025); } else if(run.equals("3")) { logger.info("Run 3"); windowSizes = Arrays.asList(10); learningRates = Arrays.asList(0.1); } else if(run.equals("4")) { logger.info("Run 4"); windowSizes = Arrays.asList(15); learningRates = Arrays.asList(0.025); } else { logger.info("Run " + run); windowSizes = Arrays.asList(15); learningRates = Arrays.asList(0.1); } //List<Integer> windowSizes = Arrays.asList(5, 10, 15); //List<Double> learningRates = Arrays.asList(0.025, 0.1); List<Integer> vectorLengths = Arrays.asList(50, 100); List<Integer> minWordFreqs = Arrays.asList(5, 10); int batchsize = 500; int epoch = 1; <API key><StateImpl> sequenceIterator = new <API key><StateImpl>(file, false); for(int windowSize: windowSizes) { for(double learningRate: learningRates) { for(int vectorLength: vectorLengths) { for(int minWordFreq: minWordFreqs) { logger.info("STATE2VEC - EXPERIMENT"); logger.info(""); logger.info("==PARAMETERS=="); logger.info("windowSize: " + windowSize); logger.info("learningRate: " + learningRate); logger.info("vectorLength: " + vectorLength); logger.info("batchSize: " + batchsize); logger.info("epoch: " + epoch); logger.info("minWordFreq: " + minWordFreq); logger.info(""); sequenceIterator.reset(); State2Vec state2vec = new State2Vec(); state2vec.<API key>(sequenceIterator, windowSize, learningRate, vectorLength, batchsize, epoch, minWordFreq); List<Integer> ks = Arrays.asList(100, 1000, 5000); ClusterSeqTest clusterTest = new ClusterSeqTest(); for(int k: ks) { ResultWriter writer1 = new ResultWriter("State2Vec - ", "Cluster1Test"); writer1.writeLine("STATE2VEC - EXPERIMENT"); writer1.writeLine(""); writer1.writeLine("==PARAMETERS=="); writer1.writeLine("windowSize: " + windowSize); writer1.writeLine("learningRate: " + learningRate); writer1.writeLine("vectorLength: " + vectorLength); writer1.writeLine("batchSize: " + batchsize); writer1.writeLine("epoch: " + epoch); writer1.writeLine("minWordFreq: " + minWordFreq); writer1.writeLine(""); clusterTest.checkClusters1(state2vec.getTrainedModel(), k, writer1); ResultWriter writer2 = new ResultWriter("State2Vec - ", "Cluster2Test"); writer2.writeLine("STATE2VEC - EXPERIMENT"); writer2.writeLine(""); writer2.writeLine("==PARAMETERS=="); writer2.writeLine("windowSize: " + windowSize); writer2.writeLine("learningRate: " + learningRate); writer2.writeLine("vectorLength: " + vectorLength); writer2.writeLine("batchSize: " + batchsize); writer2.writeLine("epoch: " + epoch); writer2.writeLine("minWordFreq: " + minWordFreq); writer2.writeLine(""); clusterTest.checkClusters2(state2vec.getTrainedModel(), k, writer2); } } } } } } }
#ifndef AC_GEGBLABB_H #define AC_GEGBLABB_H // object code form for any purpose and without fee is hereby granted, // restricted rights notice below appear in all supporting // documentation. // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // (Rights in Technical Data and Computer Software), as applicable. // DESCRIPTION: // Using the fully qualified names from the `AcGe' struct can be // cumbersome. If there are no global name conflicts use the // following synonyms for convenience. // Note: All interface descriptions must use fully qualified names. // That is, header files MUST NOT include this file and MUST // NOT use these abbreviations. // Note: If any of the following abbreviations cause conflicts and // this file cannot be included, then the acceptable abbreviations // (those that do not cause conflicts) will have to be manually // introduced, or another abbreviation header file will have to // be created containing only the acceptable abbreviations. // Note: When this file is included in a source file, it MUST BE // included AFTER all other include files (except possibly // other abbreviation include files). // For example: // #include "foo.h" // #include "bar.h" // #include "gegblabb.h" // <- Must be last! #include "gegbl.h" const int eGood = AcGe::eGood; const int eBad = AcGe::eBad; typedef AcGe::EntityId EntityId; const AcGe::EntityId kEntity2d = AcGe::kEntity2d; const AcGe::EntityId kEntity3d = AcGe::kEntity3d; const AcGe::EntityId kPointEnt2d = AcGe::kPointEnt2d; const AcGe::EntityId kPointEnt3d = AcGe::kPointEnt3d; const AcGe::EntityId kPosition2d = AcGe::kPosition2d; const AcGe::EntityId kPosition3d = AcGe::kPosition3d; const AcGe::EntityId kPointOnCurve2d = AcGe::kPointOnCurve2d; const AcGe::EntityId kPointOnCurve3d = AcGe::kPointOnCurve3d; const AcGe::EntityId kBoundedPlane = AcGe::kBoundedPlane; const AcGe::EntityId kCircArc2d = AcGe::kCircArc2d; const AcGe::EntityId kCircArc3d = AcGe::kCircArc3d; const AcGe::EntityId kConic2d = AcGe::kConic2d; const AcGe::EntityId kConic3d = AcGe::kConic3d; const AcGe::EntityId kCurve2d = AcGe::kCurve2d; const AcGe::EntityId kCurve3d = AcGe::kCurve3d; const AcGe::EntityId kEllipArc2d = AcGe::kEllipArc2d; const AcGe::EntityId kEllipArc3d = AcGe::kEllipArc3d; const AcGe::EntityId kHelix = AcGe::kHelix; const AcGe::EntityId kLine2d = AcGe::kLine2d; const AcGe::EntityId kLine3d = AcGe::kLine3d; const AcGe::EntityId kLinearEnt2d = AcGe::kLinearEnt2d; const AcGe::EntityId kLinearEnt3d = AcGe::kLinearEnt3d; const AcGe::EntityId kLineSeg2d = AcGe::kLineSeg2d; const AcGe::EntityId kLineSeg3d = AcGe::kLineSeg3d; const AcGe::EntityId kPlanarEnt = AcGe::kPlanarEnt; const AcGe::EntityId kExternalCurve3d = AcGe::kExternalCurve3d; const AcGe::EntityId kExternalCurve2d = AcGe::kExternalCurve2d; const AcGe::EntityId kPlane = AcGe::kPlane; const AcGe::EntityId kRay2d = AcGe::kRay2d; const AcGe::EntityId kRay3d = AcGe::kRay3d; const AcGe::EntityId kSurface = AcGe::kSurface; const AcGe::EntityId kSphere = AcGe::kSphere; const AcGe::EntityId kCone = AcGe::kCone; const AcGe::EntityId kTorus = AcGe::kTorus; const AcGe::EntityId kCylinder = AcGe::kCylinder; const AcGe::EntityId kSplineEnt2d = AcGe::kSplineEnt2d; const AcGe::EntityId kSurfaceCurve2dTo3d = AcGe::kSurfaceCurve2dTo3d; const AcGe::EntityId kSurfaceCurve3dTo2d = AcGe::kSurfaceCurve3dTo2d; const AcGe::EntityId kPolyline2d = AcGe::kPolyline2d; const AcGe::EntityId kAugPolyline2d = AcGe::kAugPolyline2d; const AcGe::EntityId kNurbCurve2d = AcGe::kNurbCurve2d; const AcGe::EntityId kDSpline2d = AcGe::kDSpline2d; const AcGe::EntityId kCubicSplineCurve2d = AcGe::kCubicSplineCurve2d; const AcGe::EntityId kSplineEnt3d = AcGe::kSplineEnt3d; const AcGe::EntityId kPolyline3d = AcGe::kPolyline3d; const AcGe::EntityId kAugPolyline3d = AcGe::kAugPolyline3d; const AcGe::EntityId kNurbCurve3d = AcGe::kNurbCurve3d; const AcGe::EntityId kDSpline3d = AcGe::kDSpline3d; const AcGe::EntityId kCubicSplineCurve3d = AcGe::kCubicSplineCurve3d; const AcGe::EntityId kTrimmedCrv2d = AcGe::kTrimmedCrv2d; const AcGe::EntityId kCompositeCrv2d = AcGe::kCompositeCrv2d; const AcGe::EntityId kCompositeCrv3d = AcGe::kCompositeCrv3d; const AcGe::EntityId kEnvelope2d = AcGe::kEnvelope2d; const AcGe::EntityId kExternalSurface = AcGe::kExternalSurface; const AcGe::EntityId kNurbSurface = AcGe::kNurbSurface; const AcGe::EntityId kOffsetSurface = AcGe::kOffsetSurface; const AcGe::EntityId kTrimmedSurface = AcGe::kTrimmedSurface; const AcGe::EntityId <API key> = AcGe::<API key>; const AcGe::EntityId kPointOnSurface = AcGe::kPointOnSurface; const AcGe::EntityId <API key> = AcGe::<API key>; const AcGe::EntityId kCurveCurveInt2d = AcGe::kCurveCurveInt2d; const AcGe::EntityId kCurveCurveInt3d = AcGe::kCurveCurveInt3d; const AcGe::EntityId kBoundBlock2d = AcGe::kBoundBlock2d; const AcGe::EntityId kBoundBlock3d = AcGe::kBoundBlock3d; const AcGe::EntityId kOffsetCurve2d = AcGe::kOffsetCurve2d; const AcGe::EntityId kOffsetCurve3d = AcGe::kOffsetCurve3d; const AcGe::EntityId kPolynomCurve3d = AcGe::kPolynomCurve3d; const AcGe::EntityId kBezierCurve3d = AcGe::kBezierCurve3d; const AcGe::EntityId kObject = AcGe::kObject; const AcGe::EntityId kFitData3d = AcGe::kFitData3d; const AcGe::EntityId kHatch = AcGe::kHatch; const AcGe::EntityId kTrimmedCurve2d = AcGe::kTrimmedCurve2d; const AcGe::EntityId kTrimmedCurve3d = AcGe::kTrimmedCurve3d; const AcGe::EntityId kCurveSampleData = AcGe::kCurveSampleData; const AcGe::EntityId kEllipCone = AcGe::kEllipCone; const AcGe::EntityId kEllipCylinder = AcGe::kEllipCylinder; const AcGe::EntityId kIntervalBoundBlock = AcGe::kIntervalBoundBlock; const AcGe::EntityId kClipBoundary2d = AcGe::kClipBoundary2d; const AcGe::EntityId kExternalObject = AcGe::kExternalObject; const AcGe::EntityId kCurveSurfaceInt = AcGe::kCurveSurfaceInt; const AcGe::EntityId kSurfaceSurfaceInt = AcGe::kSurfaceSurfaceInt; typedef AcGe::ExternalEntityKind ExternalEntityKind; const AcGe::ExternalEntityKind kAcisEntity = AcGe::kAcisEntity; const AcGe::ExternalEntityKind <API key> = AcGe::<API key>; typedef AcGe::<API key> <API key>; const AcGe::<API key> kOpen = AcGe::kOpen; const AcGe::<API key> kClosed = AcGe::kClosed; const AcGe::<API key> kPeriodic = AcGe::kPeriodic; const AcGe::<API key> kRational = AcGe::kRational; const AcGe::<API key> kNoPoles= AcGe::kNoPoles; const AcGe::<API key> kPoleAtMin = AcGe::kPoleAtMin; const AcGe::<API key> kPoleAtMax = AcGe::kPoleAtMax; const AcGe::<API key> kPoleAtBoth = AcGe::kPoleAtBoth; typedef AcGe::PointContainment PointContainment; const AcGe::PointContainment kInside = AcGe::kInside; const AcGe::PointContainment kOutside = AcGe::kOutside; const AcGe::PointContainment kOnBoundary = AcGe::kOnBoundary; typedef AcGe::AcGeXConfig AcGeXConfig; const AcGe::AcGeXConfig kNotDefined = AcGe::kNotDefined; const AcGe::AcGeXConfig kUnknown = AcGe::kUnknown; const AcGe::AcGeXConfig kLeftRight = AcGe::kLeftRight; const AcGe::AcGeXConfig kRightLeft = AcGe::kRightLeft; const AcGe::AcGeXConfig kLeftLeft = AcGe::kLeftLeft; const AcGe::AcGeXConfig kRightRight = AcGe::kRightRight; const AcGe::AcGeXConfig kPointLeft = AcGe::kPointLeft; const AcGe::AcGeXConfig kPointRight = AcGe::kPointRight; const AcGe::AcGeXConfig kLeftOverlap = AcGe::kLeftOverlap; const AcGe::AcGeXConfig kOverlapLeft = AcGe::kOverlapLeft; const AcGe::AcGeXConfig kRightOverlap = AcGe::kRightOverlap; const AcGe::AcGeXConfig kOverlapRight = AcGe::kOverlapRight; const AcGe::AcGeXConfig kOverlapStart = AcGe::kOverlapStart; const AcGe::AcGeXConfig kOverlapEnd = AcGe::kOverlapEnd; const AcGe::AcGeXConfig kOverlapOverlap = AcGe::kOverlapOverlap; typedef AcGe::ErrorCondition AcGeError; const AcGe::ErrorCondition kOk = AcGe::kOk; const AcGe::ErrorCondition k0This = AcGe::k0This; const AcGe::ErrorCondition k0Arg1 = AcGe::k0Arg1; const AcGe::ErrorCondition k0Arg2 = AcGe::k0Arg2; const AcGe::ErrorCondition <API key> = AcGe::<API key>; const AcGe::ErrorCondition kEqualArg1Arg2 = AcGe::kEqualArg1Arg2; const AcGe::ErrorCondition kEqualArg1Arg3 = AcGe::kEqualArg1Arg3; const AcGe::ErrorCondition kEqualArg2Arg3 = AcGe::kEqualArg2Arg3; const AcGe::ErrorCondition <API key> = AcGe::<API key>; const AcGe::ErrorCondition kArg1TooBig = AcGe::kArg1TooBig; const AcGe::ErrorCondition kArg1OnThis = AcGe::kArg1OnThis; const AcGe::ErrorCondition kArg1InsideThis = AcGe::kArg1InsideThis; typedef AcGe::AcGeIntersectError AcGeIntersectError; const AcGe::AcGeIntersectError kXXOk = AcGe::kXXOk; const AcGe::AcGeIntersectError kXXIndexOutOfRange = AcGe::kXXIndexOutOfRange; const AcGe::AcGeIntersectError <API key> = AcGe::<API key>; const AcGe::AcGeIntersectError kXXUnknown = AcGe::kXXUnknown; typedef AcGe::<API key> <API key>; const AcGe::<API key> kChord = AcGe::kChord; const AcGe::<API key> kSqrtChord = AcGe::kSqrtChord; const AcGe::<API key> kUniform = AcGe::kUniform; const AcGe::<API key> <API key> = AcGe::<API key>; #endif
<?php namespace Doctrine\ODM\MongoDB\Mapping\Annotations; use Doctrine\Common\Annotations\Annotation; abstract class AbstractDocument extends Annotation { }
// Generated by class-dump 3.5 (64 bit). #import "NSObject.h" @class KFContact; @protocol IKFContactExt <NSObject> @optional - (void)<API key>:(KFContact *)arg1; - (void)onModifyKFContact:(KFContact *)arg1; @end
package lv.emes.libraries.utilities.validation; /** * Actions for error that occur in validation process. * * @author eMeS * @version 1.2. */ public interface MS_ValidationError<T> { MS_ValidationError <API key>(<API key> action); /** * Returns message of validation error using pre-defined method to form message. * @return formatted message describing essence of this particular validation error. */ String getMessage(); Integer getNumber(); T getObject(); /** * @param object an object to validate. * @return reference to validation error itself. */ MS_ValidationError withObject(T object); }
#ifndef _absnodeaction_h_ #define _absnodeaction_h_ #include "cocos2d.h" using namespace cocos2d; #include <string> #include <iostream> #include <vector> using namespace std; namespace uilib { class TouchNode; enum EaseType { EaseNone, EaseIn, EaseOut, EaseInOut, EaseExponentialIn, EaseExponentialOut, <API key>, EaseSineIn, EaseSineOut, EaseSineInOut, EaseElastic, EaseElasticIn, EaseElasticOut, EaseElasticInOut, EaseBounce, EaseBounceIn, EaseBounceOut, EaseBounceInOut, EaseBackIn, EaseBackOut, EaseBackInOut }; enum MoveInType{ HorizontalRightIn, HorizontalLeftIn, HorizontalBothIn, VerticalTopIn, VerticalBottomIn, VerticalBothin, ScaleIn, ScaleXIn, ScaleYIn, SwayIn, RotateIn, BlinkIn, ReelIn, FireIn, DropScaleIn }; enum MoveOutType{ HorizontalRightOut, HorizontalLeftOut, HorizontalBothOut, VerticalTopOut, VerticalBottomOut, VerticalBothOut, ScaleOut, ScaleXOut, ScaleYOut, SwayOut, RotateOut, BlinkOut, ReelOut, FireOut }; enum RunningEffectType { ShineEffect, SwayEffect, ScaleEffect, AnimEffect }; class BasNodeEffectAction : public CCNode { public: BasNodeEffectAction(); virtual ~BasNodeEffectAction(); virtual void finished(); virtual void doAction(TouchNode *node,bool enable) = 0; inline void setEaseType(EaseType type) { m_easeType = type;} inline EaseType getEaseType() { return m_easeType;} inline void setActionTime(float time) { m_actionTime = time;} inline float getActionTime() { return m_actionTime;} inline void setStartTime(float time) { m_startTime = time;} inline float getStartTime() { return m_startTime;} void setFinishCB(CCNode *listener,SEL_CallFuncN func); inline bool isRunning() { return m_running;} protected: EaseType m_easeType; float m_actionTime; float m_startTime; protected: bool m_running; protected: SEL_CallFuncN m_finishFunc; CCNode *m_listener; }; class BasNodeAction : public CCNode { public: BasNodeAction(); virtual ~BasNodeAction(); virtual void finished(); virtual void doAction(const std::vector<TouchNode*> &nodes) = 0; void setDelayTime(float delay) { m_delayTime = delay;} float getDelayTime() { return m_delayTime;} inline void setEaseType(EaseType type) { m_easeType = type;} inline EaseType getEaseType() { return m_easeType;} inline void setMoveInType(MoveInType type) { m_inType = type;} inline MoveInType getMoveInType() { return m_inType;} inline void setMoveOutType(MoveOutType type) { m_outType = type;} inline MoveOutType getMoveOutType() { return m_outType;} inline void setActionTime(float time) { m_actionTime = time;} inline float getActionTime() { return m_actionTime;} inline void setStartTime(float time) { m_startTime = time;} inline float getStartTime() { return m_startTime;} inline void setRate(float rate) { m_rate = rate;} inline float getRate() { return m_rate;} void setFinishCB(CCNode *listener,SEL_CallFuncN func,CCNode *actionNode = 0); protected: CCActionEase *createEaseAction(); protected: int m_actionRunNum; float m_delayTime; EaseType m_easeType; MoveInType m_inType; MoveOutType m_outType; float m_actionTime; float m_rate; float m_startTime; protected: SEL_CallFuncN m_finishFunc; CCNode *m_listener; CCNode *m_actionNode; }; class UiNodeActionFactory { UiNodeActionFactory(); ~UiNodeActionFactory(); static UiNodeActionFactory *m_instance; public: static UiNodeActionFactory *getInstance(); BasNodeAction *getMoveActionByName(const std::string &name); BasNodeEffectAction *<API key>(const std::string &name); protected: }; } #endif
window.ImageViewer = function(url, alt, title){ var img = $('<img />').attr('src', url).attr('alt', title).css({ display: 'inline-block', 'max-width': '90vw', 'max-height': '90vh' }); var a = $('<a></a>').attr('target', '_blank') .attr('title', title) .attr('href', url) .css({ display: 'inline-block', height: '100%' }) .append(img); var close_it = function(){ overlay.remove(); container.remove(); }; var closeBtn = $('<a class="icon-remove-sign"></a>').css({ color: 'red', 'font-size': 'x-large', 'margin-left': '-0.1em' }).bind('click', close_it); var closeWrapper = $('<div></div>').css({ height: '100%', width: '2em', 'text-align': 'left', 'display': 'inline-block', 'vertical-algin': 'top', 'margin-top': '-0.6em', 'float': 'right' }).append(closeBtn); var container = $('<div></div>').append( $('<div></div>').css({ margin: '5vh 1vw', display: 'inline-block', 'vertical-align': 'top' }).append(a).append(closeWrapper)) .css({ 'z-index': 30000000, 'position': 'fixed', 'padding': 0, 'margin': 0, 'width': '100vw', 'height': '100vh', 'top': 0, 'left': 0, 'text-align': 'center', 'cursor': 'default', 'vertical-align': 'middle' }) .bind('click',close_it) .appendTo('body'); var overlay = $('<div class="blockUI blockMsg blockPage">').css({ 'z-index': 9999, 'position': 'fixed', padding: 0, margin: 0, width: '100vw', height: '100vh', top: '0vh', left: '0vw', 'text-align': 'center', 'cursor': 'default', 'vertical-align': 'middle', 'background-color': 'gray', 'opacity': '0.4' }).bind('click', close_it).appendTo('body'); this.close = close_it; return this; }
layout: post.html title: "Fundraising for PyLadies for PyCon 2015" tag: [PyCon] author: Lynn Root author_link: http://twitter.com/roguelynn **TL;DR**: [Donate](#ways-to-donate) to PyLadies for PyCon! It's that time again! With [PyCon 2015][0] planning in high gear, PyLadies is revving up to raise funds to help women attend the biggest Python conference of the year. Last year, we raised **$40,000**. We're hoping to do that again to help women attend PyCon. Here's the breakdown: Our numbers * In addition to registration, it will take about $500-1000 per woman in North America to attend PyCon 2015 in Montreal * In addition to registration, it will take about $1000-2000 per woman outside of North America to attend PyCon 2015 in Montreal Why PyLadies? Our effect on the community _(percentages are not at all accurate, and are roughly estimated based on guessing names-to-gender scripts):_ * PyCon 2011 had less than 10% women attendees (speaker % unknown) * PyLadies started in late 2011 * PyCon 2012 had about 11% women attendees, and about the same in speakers. * This included giving PyLadies and [Women Who Code][8] booths to help promote our messages * At the time of PyCon 2014, PyLadies had over [35 chapters][7], doing stuff like: * hosts events like learning python, learning git/github, * providing space for study groups, * enriching members with speaker series (like Guido van Rossum!), * events to help think up of talks to submit for PyCon (as well as DjangoCon), * hold events for folks to practice their talk, etc * PyLadies work showed: * PyCon 2013 had over 20% women attendees, and about 22% women speakers. * PyCon 2014 had over 30% women attendees, and about a third of the speakers were women. * No overhead - we're all volunteers! ;-) * Lastly, donations tax deductible since PyLadies is under the financial enclave of the Python Software Foundation What we're actively doing: * We're using all of the $12k that PyLadies raised at last year's PyCon auction to increase the aid pool - something that we were hoping to actually use towards growing PyLadies locations (but it's okay! $10k for more women friends at PyCon!) * We're bugging companies and individuals do donate (hence this blog post!). What you will get in return * Unless you explicitly choose to be anonymous (though the [online donation site][5] or in private discussions), we will profusely thank you via our public channels (Twitter, this blog, and at our PyCon booth) * Provide a detailed write-up and financial introspection of how many women we've helped because of this campaign * Visibility! It shows the PyCon/Python community that your company/you are serious about women in tech - which can directly benefit sponsors with increased hiring pool of female Pythonistas. Ways to donate All of the following methods are tax-deductible with funds going to the [Python Software Foundation][1], a 501(c)3 charitable organization. * Through our [donation page][4] (ideal for individuals) * Email me at [lynn@lynnroot.com][2] (ideal for companies or anyone needing a proper invoice, or individualized solutions) * Become a [sponsor][6] for PyCon (this is more indirect and less potent, but overall helpful to PyCon) More information is available on the [PyCon Financial Aid][5] site if you would like to apply for financial aid for PyCon, whether you are a PyLady or PyGent. [0]: http://us.pycon.org/2015 [1]: http://python.org/psf [2]: mailto:lynn@lynnroot.com?subject=PyLadies%20Donation [3]: http://pyladies.com/blog [4]: https://psfmember.org/civicrm/contribute/transact?reset=1&id=6 [5]: https://us.pycon.org/2014/assistance/ [6]: https://us.pycon.org/2014/sponsors/prospectus/ [7]: https://github.com/pyladies/pyladies/tree/master/www/locations [8]: http: [9]: http:
#ifndef <API key> #define <API key> #include "amount.h" #include <stdint.h> #include <vector> class CBlockIndex; class CCoinsViewCache; class CTransaction; class CValidationState; /** Transaction validation functions */ /** Context-independent validity checks */ bool CheckTransaction(const CTransaction& tx, CValidationState& state); namespace Consensus { /** * Check whether all inputs of this transaction are valid (no double spends and amounts) * This does not modify the UTXO set. This does not check scripts and sigs. * @param[out] txfee Set to the transaction fee if successful. * Preconditions: tx.IsCoinBase() is false. */ bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, CAmount& txfee); } // namespace Consensus /** Auxiliary functions for transaction validation (ideally should not be exposed) */ /** * Count ECDSA signature operations the old-fashioned (pre-0.6) way * @return number of sigops this transaction's outputs will produce when spent * @see CTransaction::FetchInputs */ unsigned int GetLegacySigOpCount(const CTransaction& tx); /** * Count ECDSA signature operations in pay-to-script-hash inputs. * * @param[in] mapInputs Map of previous transactions that have outputs we're spending * @return maximum number of sigops required to validate this transaction's inputs * @see CTransaction::FetchInputs */ unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs); /** * Count total signature operations for a transaction. * @param[in] tx Transaction for which we are counting sigops * @param[in] inputs Map of previous transactions that have outputs we're spending * @param[out] flags Script verification flags * @return Total signature operation count for a tx */ unsigned int <API key>(const CTransaction& tx, const CCoinsViewCache& inputs, int flags); /** * Check if transaction is final and can be included in a block with the * specified height and time. Consensus critical. */ bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime); /** * Calculates the block height and previous block's median time past at * which the transaction will be considered final in the context of BIP 68. * Also removes from the vector of input heights any entries which did not * correspond to sequence locked inputs as they do not affect the calculation. */ std::pair<int, int64_t> <API key>(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block); bool <API key>(const CBlockIndex& block, std::pair<int, int64_t> lockPair); /** * Check if transaction is final per BIP 68 sequence numbers and can be included in a block. * Consensus critical. Takes as input a list of heights at which tx's inputs (in order) confirmed. */ bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block); #endif // <API key>
layout: post title: Week three and implementing twig template The week three of coding period has ended and this time I learnt about something very new to me, Twig template. In Drupal 8 Twig has replaced PHPTemplate as default templating engine which meant that the theming of module had to be done from beginning. Also since my module deals with creation of printer friendly version of nodes so it makes it even more important that theming should be paid more importance. The reference material present on drupal.org are good but still the things were not getting clear to me so I browsed more and more and finally found this small <a href="http://drewpull.drupalgardens.com/blog/<API key>" target="_blank">blog </a>on Twig which helped me understand. In the process of learning theming I learnt about concept of rendering in Drupal and most importantly about invalidating catching while rendering, I mainly used getListCacheTags() to serve my purpose. Also knowing the that I can use <API key>() to create temporary variables and then rendering them in my templates was very helpful. In the present week I managed to develop a partial working prototype of module with not all but many configurations completed like links for printer friendly version are being shown in blocks as well as below the entities. Ofcourse the user can disable and re-enable these links. I have created view modes for the print version and hence generated core.entity_view_mode.$entity_type.$view_mode.yml file. I was impressed by the fact that I had to import configuration for this file becuase it was something very new to me. Next week I will mainly be working on completing the configuration of module and try to rectify the problem which I have found in this week. The progress of module develpoment can be viewed over <a href="https://github.com/zealfire/printable" style="text-decoration:none;" target="_blank">here</a>.
#include <compiler.h> #if defined(CPUCORE_IA32) && defined(SUPPORT_MEMDBG32) #include <common/strres.h> #include <cpucore.h> #include <pccore.h> #include <io/iocore.h> #include <generic/memdbg32.h> #define MEMDBG32_MAXMEM 16 #define <API key> 128 #define MEMDBG32_LEFTMARGIN 8 typedef struct { UINT mode; int width; int height; int bpp; CMNPAL pal[MEMDBG32_PALS]; } MEMDBG32; static MEMDBG32 memdbg32; static const char _mode0[] = "Real Mode"; static const char _mode1[] = "Protected Mode"; static const char _mode2[] = "Virtual86"; static const char *modestr[3] = {_mode0, _mode1, _mode2}; static const RGB32 md32pal[MEMDBG32_PALS] = { RGB32D(0x33, 0x33, 0x33), RGB32D(0x00, 0x00, 0x00), RGB32D(0xff, 0xaa, 0x00), RGB32D(0xff, 0x00, 0x00), RGB32D(0x11, 0x88, 0x11), RGB32D(0x00, 0xff, 0x00), RGB32D(0xff, 0xff, 0xff)}; void memdbg32_initialize(void) { ZeroMemory(&memdbg32, sizeof(memdbg32)); memdbg32.width = (MEMDBG32_BLOCKW * <API key>) + MEMDBG32_LEFTMARGIN; memdbg32.height = (MEMDBG32_BLOCKH * 2 * MEMDBG32_MAXMEM) + 8; } void memdbg32_getsize(int *width, int *height) { if (width) { *width = memdbg32.width; } if (height) { *height = memdbg32.height; } } REG8 memdbg32_process(void) { return(MEMDBG32_FLAGDRAW); } BOOL memdbg32_paint(CMNVRAM *vram, CMNPALCNV cnv, BOOL redraw) { UINT mode; UINT8 use[MEMDBG32_MAXMEM*<API key>*2 + 256]; UINT32 pd[1024]; UINT pdmax; UINT i, j; UINT32 pde; UINT32 pdea; UINT32 pte; char str[4]; mode = 0; if (CPU_STAT_PM) { mode = 1; } if (CPU_STAT_VM86) { mode = 2; } if (memdbg32.mode != mode) { memdbg32.mode = mode; redraw = TRUE; } if ((!redraw) && (!CPU_STAT_PAGING)) { return(FALSE); } if (vram == NULL) { return(FALSE); } if ((memdbg32.bpp != vram->bpp) || (redraw)) { if (cnv == NULL) { return(FALSE); } (*cnv)(memdbg32.pal, md32pal, MEMDBG32_PALS, vram->bpp); memdbg32.bpp = vram->bpp; } cmndraw_fill(vram, 0, 0, memdbg32.width, memdbg32.height, memdbg32.pal[MEMDBG32_PALBDR]); ZeroMemory(use, sizeof(use)); if (CPU_STAT_PAGING) { pdmax = 0; for (i=0; i<1024; i++) { pde = cpu_memoryread_d(CPU_STAT_PDE_BASE + (i * 4)); if (pde & CPU_PDE_PRESENT) { for (j=0; j<pdmax; j++) { if (!((pde ^ pd[j]) & <API key>)) { break; } } if (j < pdmax) { pd[j] |= pde & CPU_PDE_ACCESS; } else { pd[pdmax++] = pde; } } } for (i=0; i<pdmax; i++) { pde = pd[i]; pdea = pde & <API key>; for (j=0; j<1024; j++) { pte = cpu_memoryread_d(pdea + (j * 4)); if ((pte & CPU_PTE_PRESENT) && (pte < 0x1000000/16*MEMDBG32_MAXMEM/128*<API key>)) { if ((pde & CPU_PDE_ACCESS) && (pte & CPU_PTE_ACCESS)) { use[pte >> 12] = MEMDBG32_PALPAGE1; } else if (!use[pte >> 12]) { use[pte >> 12] = MEMDBG32_PALPAGE0; } } } } } else { FillMemory(use, 256, MEMDBG32_PALREAL); FillMemory(use + (0xfa0000 >> 12), (0x60000 >> 12), MEMDBG32_PALREAL); if ((CPU_STAT_PM) && (pccore.extmem)) { FillMemory(use + 256, MIN(<API key> * 2 * pccore.extmem, sizeof(use) - 256), MEMDBG32_PALPM); } } for (i=0; i<MEMDBG32_MAXMEM*2; i++) { for (j=0; j<<API key>; j++) { cmndraw_fill(vram, MEMDBG32_LEFTMARGIN + j * MEMDBG32_BLOCKW, i * MEMDBG32_BLOCKH, MEMDBG32_BLOCKW - 1, MEMDBG32_BLOCKH - 1, memdbg32.pal[use[(i * <API key>) + j]]); } } for (i=0; i<MEMDBG32_MAXMEM; i++) { SPRINTF(str, "%x", i); cmddraw_text8(vram, 0, i * MEMDBG32_BLOCKH * 2, str, memdbg32.pal[MEMDBG32_PALTXT]); } cmddraw_text8(vram, 0, memdbg32.height - 8, modestr[mode], memdbg32.pal[MEMDBG32_PALTXT]); return(TRUE); } #endif
// opjlib.h // opjlib #import <Foundation/Foundation.h> @interface opjlib : NSObject @end
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-11-01 20:02 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('phone_numbers', '0001_initial'), ('sims', '0001_initial'), ] operations = [ migrations.AddField( model_name='phonenumber', name='related_sim', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='phone_numbers', to='sims.Sim'), ), ]
package ch.spacebase.openclassic.api; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.<API key>; import java.net.HttpURLConnection; import java.net.<API key>; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import ch.spacebase.openclassic.api.util.Constants; /** * Manages the server's web heartbeats. */ public final class HeartbeatManager { private static final long salt = new SecureRandom().nextLong(); private static final Map<String, Runnable> customBeats = new HashMap<String, Runnable>(); private static String url = ""; /** * Gets the server's current salt. * @return The server's salt. */ public static long getSalt() { return salt; } /** * Gets the server's minecraft.net url. * @return The url. */ public static String getURL() { return url; } /** * Sets the server's known minecraft.net url. * @param url The url. */ public static void setURL(String url) { HeartbeatManager.url = url; } /** * Triggers a heartbeat. */ public static void beat() { mineBeat(); womBeat(); for(String id : customBeats.keySet()) { try { customBeats.get(id).run(); } catch(Exception e) { OpenClassic.getLogger().severe("Exception while running a custom heartbeat with the ID \"" + id + "\"!"); e.printStackTrace(); } } } /** * Adds a custom heartbeat to run when {@link beat()} is called. * @param id ID of the custom heartbeat. * @param run Runnable to call when beating. */ public static void addBeat(String id, Runnable run) { customBeats.put(id, run); } /** * Removes a custom heartbeat. * @param id ID of the heartbeat. */ public static void removeBeat(String id) { customBeats.remove(id); } /** * Clears the custom heartbeat list. */ public static void clearBeats() { customBeats.clear(); } private static void mineBeat() { URL url = null; try { url = new URL("https://minecraft.net/heartbeat.jsp?port=" + OpenClassic.getServer().getPort() + "&max=" + OpenClassic.getServer().getMaxPlayers() + "&name=" + URLEncoder.encode(Color.stripColor(OpenClassic.getServer().getServerName()), "UTF-8") + "&public=" + OpenClassic.getServer().isPublic() + "&version=" + Constants.PROTOCOL_VERSION + "&salt=" + salt + "&users=" + OpenClassic.getServer().getPlayers().size()); } catch(<API key> e) { OpenClassic.getLogger().severe("Malformed URL while attempting minecraft.net heartbeat?"); return; } catch(<API key> e) { OpenClassic.getLogger().severe("UTF-8 URL encoding is unsupported on your system."); return; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); try { conn.setRequestMethod("GET"); } catch (ProtocolException e) { OpenClassic.getLogger().severe("Exception while performing minecraft.net heartbeat: Connection doesn't support GET...?"); return; } conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.<API key>(false); conn.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); InputStream input = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String result = reader.readLine(); reader.close(); input.close(); if(!HeartbeatManager.url.equals(result)) { HeartbeatManager.url = result; OpenClassic.getLogger().info(Color.GREEN + "The server's URL is now \"" + getURL() + "\"."); try { File file = new File(OpenClassic.getGame().getDirectory(), "server-address.txt"); if(!file.exists()) file.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(result); writer.close(); } catch(IOException e) { OpenClassic.getLogger().severe("Failed to save server address!"); e.printStackTrace(); } } } catch (IOException e) { OpenClassic.getLogger().severe("Exception while performing minecraft.net heartbeat!"); e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } } private static void womBeat() { URL url = null; try { url = new URL("http://direct.worldofminecraft.com/hb.php?port=" + OpenClassic.getServer().getPort() + "&max=" + OpenClassic.getServer().getMaxPlayers() + "&name=" + URLEncoder.encode(Color.stripColor(OpenClassic.getServer().getServerName()), "UTF-8") + "&public=" + OpenClassic.getServer().isPublic() + "&version=" + Constants.PROTOCOL_VERSION + "&salt=" + salt + "&users=" + OpenClassic.getServer().getPlayers().size() + "&noforward=1"); } catch(<API key> e) { OpenClassic.getLogger().severe("Malformed URL while attempting WOM heartbeat?"); return; } catch(<API key> e) { OpenClassic.getLogger().severe("UTF-8 URL encoding is unsupported on your system."); return; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(false); conn.setDoInput(false); conn.setUseCaches(false); conn.<API key>(false); conn.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); } catch (IOException e) { OpenClassic.getLogger().severe("Exception while performing WOM heartbeat!"); e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } } }
#! /bin/bash BASHRC="$HOME/.bashrc" echo "# java setting" >> $BASHRC echo "export JAVA_HOME=\$(/usr/libexec/java_home)" >> $BASHRC echo "" >> $BASHRC
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace <API key> { public class ParkingRamp : ParkingConstruct { [Newtonsoft.Json.JsonIgnore] public List<ParkingFloor> Floors { get; private set; } public override bool IsFull { get { return OpenLocations < 1; } } public override int OpenLocations { get { return Floors.Sum(r => r.OpenLocations) - InQueue.Count; } } public override int TotalLocations { get { return Floors.Sum(r => r.TotalLocations); } } public ParkingRamp(ParkingConstruct parent, string name, int floorCount, int locationCount) : base(parent, name) { Name = name; Floors = new List<ParkingFloor>(); for (int i = 0; i < floorCount; i++) { Floors.Add(new ParkingFloor(this, string.Format("{0}-{1}", Name, i.ToString()), locationCount)); } } public override void Tick() { var openCount = Floors.Count(r => !r.IsFull); if (openCount > 0) { var gateCapacity = (int)(Simulator.Interval.TotalSeconds / 10.0); for (int i = 0; i < gateCapacity; i++) { var floorsWithRoom = Floors.Where(r => !r.IsFull).ToList(); if (InQueue.Count > 0 && floorsWithRoom.Count > 0) { var floor = Simulator.Random.Next(floorsWithRoom.Count); floorsWithRoom[floor].InQueue.Enqueue(InQueue.Dequeue()); } } } foreach (var item in Floors) item.Tick(); base.Tick(); while (OutQueue.Count > 0) Parent.OutQueue.Enqueue(OutQueue.Dequeue()); } } }
package org.gojul.gojulutils.data; /** * Class {@code GojulPair} is a simple stupid pair class. This class is notably necessary * when emulating JOIN in database and such a class does not exist natively in the JDK. * This object is immutable as long as the object it contains are immutable. Since * this object is not serializable it should not be stored in objects which could be serialized, * especially Java HttpSession objects. * * @param <S> the type of the first object of the pair. * @param <T> the type of the second object of the pair. * @author jaubin */ public final class GojulPair<S, T> { private final S first; private final T second; /** * Constructor. Both parameters are nullable. Note that this constructor * does not perform any defensive copy as it is not possible there. * * @param first the first object. * @param second the second object. */ public GojulPair(final S first, final T second) { this.first = first; this.second = second; } /** * Return the first object. * * @return the first object. */ public S getFirst() { return first; } /** * Return the second object. * * @return the second object. */ public T getSecond() { return second; } /** * {@inheritDoc} */ @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GojulPair<?, ?> pair = (GojulPair<?, ?>) o; if (getFirst() != null ? !getFirst().equals(pair.getFirst()) : pair.getFirst() != null) return false; return getSecond() != null ? getSecond().equals(pair.getSecond()) : pair.getSecond() == null; } /** * {@inheritDoc} */ @Override public int hashCode() { int result = getFirst() != null ? getFirst().hashCode() : 0; result = 31 * result + (getSecond() != null ? getSecond().hashCode() : 0); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "GojulPair{" + "first=" + first + ", second=" + second + '}'; } }
using System.Collections.Generic; using System.Diagnostics.Contracts; using Microsoft.CodeAnalysis; namespace ErrorProne.NET.Extensions { public static class <API key> { public static IEnumerable<SyntaxNode> EnumerateParents(this SyntaxNode node) { Contract.Requires(node != null); while (node.Parent != null) { yield return node.Parent; node = node.Parent; } } } }
#include "elements.h" #include "mpi_compat.h" #include "gcmc.h" #include "memory.h" #include "random.h" #include "neighbor.h" #include "ff_md.h" #include "MAPP.h" #include "atoms_md.h" #include "comm.h" #include "dynamic_md.h" using namespace MAPP_NS; GCMC::GCMC(AtomsMD*& __atoms,ForceFieldMD*&__ff,DynamicMD*& __dynamic,elem_type __gas_type,type0 __mu,type0 __T,int seed): gas_type(__gas_type), T(__T), mu(__mu), natms_lcl(__atoms->natms_lcl), natms_ph(__atoms->natms_ph), cut_sq(__ff->cut_sq), s_lo(__atoms->comm.s_lo), s_hi(__atoms->comm.s_hi), dynamic(__dynamic), world(__atoms->comm.world), atoms(__atoms), ff(__ff), ielem(gas_type) { random=new Random(seed); s_trials=new type0*[__dim__]; *s_trials=NULL; del_ids=NULL; del_ids_sz=del_ids_cpcty=0; vars=lcl_vars=NULL; } GCMC::~GCMC() { delete [] del_ids; delete [] s_trials; delete random; } void GCMC::add_del_id(int* new_ids,int no) { if(del_ids_sz+no>del_ids_cpcty) { int* del_ids_=new int[del_ids_sz+no]; memcpy(del_ids_,del_ids,del_ids_sz*sizeof(int)); del_ids_cpcty=del_ids_sz+no; delete [] del_ids; del_ids=del_ids_; } memcpy(del_ids+del_ids_sz,new_ids,sizeof(int)*no); del_ids_sz+=no; } int GCMC::get_new_id() { if(del_ids_sz) { del_ids_sz return del_ids[del_ids_sz]; } else { max_id++; return max_id; } } void GCMC::init() { cut=ff->cut[ielem][0]; for(size_t i=1;i<atoms->elements.nelems;i++) cut=MAX(cut,ff->cut[ielem][i]); gas_mass=atoms->elements.masses[gas_type]; kbT=atoms->kB*T; beta=1.0/kbT; lambda=atoms->hP/sqrt(2.0*M_PI*kbT*gas_mass); sigma=sqrt(kbT/gas_mass); z_fac=1.0; for(int i=0;i<__dim__;i++) z_fac/=lambda; z_fac*=exp(beta*mu); vol=1.0; for(int i=0;i<__dim__;i++)vol*=atoms->H[i][i]; id_type max_id_=0; id_type* id=atoms->id->begin(); for(int i=0;i<natms_lcl;i++) max_id_=MAX(id[i],max_id_); MPI_Allreduce(&max_id_,&max_id,1,Vec<id_type>::MPI_T,MPI_MAX,world); for(int i=0;i<del_ids_sz;i++) max_id=MAX(max_id,del_ids[i]); ngas_lcl=0; elem_type* elem=atoms->elem->begin(); for(int i=0;i<natms_lcl;i++) if(elem[i]==gas_type) ngas_lcl++; MPI_Allreduce(&ngas_lcl,&ngas,1,MPI_INT,MPI_SUM,world); } void GCMC::fin() { } void GCMC::box_setup() { int sz=0; max_ntrial_atms=1; for(int i=0;i<__dim__;i++) { type0 tmp=0.0; for(int j=i;j<__dim__;j++) tmp+=atoms->B[j][i]*atoms->B[j][i]; cut_s[i]=sqrt(tmp)*cut; s_lo_ph[i]=s_lo[i]-cut_s[i]; s_hi_ph[i]=s_hi[i]+cut_s[i]; nimages_per_dim[i][0]=static_cast<int>(floor(s_hi_ph[i])); nimages_per_dim[i][1]=-static_cast<int>(floor(s_lo_ph[i])); max_ntrial_atms*=1+nimages_per_dim[i][0]+nimages_per_dim[i][1]; sz+=1+nimages_per_dim[i][0]+nimages_per_dim[i][1]; } *s_trials=new type0[sz]; for(int i=1;i<__dim__;i++) s_trials[i]=s_trials[i-1]+1+nimages_per_dim[i-1][0]+nimages_per_dim[i-1][1]; } void GCMC::box_dismantle() { delete [] *s_trials; *s_trials=NULL; }
#include <ESP8266WiFi.h> #include <PubSubClient.h> #include "mqtt.h" // Connect to MQTT and set up subscriptions based on configuration void MQTT::connect() { // Connect to broker this->mqttClient.setServer(this->host, this->port); mqttClient.connect(this->clientId); Serial.print("Connected to MQTT, with server: "); Serial.print(this->host); Serial.print(", port: "); Serial.print(this->port); Serial.print(", with client ID: "); Serial.println(this->clientId); // Send ping ping(); } // Send ping to MQTT broker void MQTT::ping() { char payload[50]; sprintf(payload, "%s ok", this->clientId); this->mqttClient.publish("/status", payload); Serial.println("Sent ping to broker"); }
using System.Collections.Generic; namespace SmartMeter.Business.Interface.Mapper { public interface IMapTelegram { Persistence.Interface.ITelegram Map(ITelegram businessTelegram); Business.Interface.ITelegram Map(Persistence.Interface.ITelegram persistenceTelegram); IEnumerable<ITelegram> Map(IEnumerable<Persistence.Interface.ITelegram> <API key>); } }
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>NTU D3js HW01</title> <link rel="stylesheet" type="text/css" href="main.css"> <script src="https://d3js.org/d3.v3.min.js"></script> </head> <body> <!-- page 4 --> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br><br> <!-- page 8 --> <div> <hr> <h1></h1> <p></p> <p></p> <p></p> <blockquote> <strong></strong> </blockquote> <p></p> </div> <hr> <!-- page 13 --> <table border="1"> <tr> <th colspan = "4"></th> </tr> <tr> <th></th> <th></th> <th></th> <th></th> </tr> <tr> <td></td> <td rowspan = "6"></td> <td></td> <td>1</td> </tr> <tr> <td></td> <td></td> <td>32</td> </tr> <tr> <td></td> <td></td> <td>1161</td> </tr> <tr> <td></td> <td></td> <td>399</td> </tr> <tr> <td></td> <td></td> <td>26</td> </tr> <tr> <td></td> <td></td> <td>1</td> </tr> </table> <hr> <!-- page 17 --> <a href="http: <img src="http: </a> <hr> <!--02 page 58 <h1>1911~2016</h1> <p id='num1'></p> <input type="button" onclick="launch()" value=""> <script> function launch(){ var number = Math.floor(Math.random()*106)+1911; d3.select('#num1').text(number); } </script> </body> </html>
define("helios/Helios-Debugger", ["amber/boot", "amber_core/Kernel-Objects", "helios/Helios-Core", "helios/Helios-Workspace"], function($boot){ var smalltalk=$boot.vm,nil=$boot.nil,_st=$boot.asReceiver,globals=$boot.globals; smalltalk.addPackage('Helios-Debugger'); smalltalk.packages["Helios-Debugger"].transport = {"type":"amd","amdNamespace":"helios"}; smalltalk.addClass('<API key>', globals.Object, ['context'], 'Helios-Debugger'); smalltalk.addMethod( smalltalk.method({ selector: "context", protocol: 'accessing', fn: function (){ var self=this; var $1; $1=self["@context"]; return $1; }, args: [], source: "context\x0a\x09^ context", messageSends: [], referencedClasses: [] }), globals.<API key>); smalltalk.addMethod( smalltalk.method({ selector: "evaluate:on:", protocol: 'evaluating', fn: function (aString,anEvaluator){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._context())._evaluate_on_(aString,anEvaluator); return $1; }, function($ctx1) {$ctx1.fill(self,"evaluate:on:",{aString:aString,anEvaluator:anEvaluator},globals.<API key>)})}, args: ["aString", "anEvaluator"], source: "evaluate: aString on: anEvaluator\x0a\x09^ self context evaluate: aString on: anEvaluator", messageSends: ["evaluate:on:", "context"], referencedClasses: [] }), globals.<API key>); smalltalk.addMethod( smalltalk.method({ selector: "<API key>:", protocol: 'initialization', fn: function (aContext){ var self=this; self["@context"]=aContext; return self}, args: ["aContext"], source: "<API key>: aContext\x0a\x09context := aContext", messageSends: [], referencedClasses: [] }), globals.<API key>); smalltalk.addMethod( smalltalk.method({ selector: "inspectOn:", protocol: 'inspecting', fn: function (anInspector){ var self=this; var variables,inspectedContext; function $Dictionary(){return globals.Dictionary||(typeof Dictionary=="undefined"?nil:Dictionary)} return smalltalk.withContext(function($ctx1) { var $1,$2,$3,$4,$receiver; variables=_st($Dictionary())._new(); inspectedContext=self._context(); $1=variables; $2=_st(inspectedContext)._locals(); $ctx1.sendIdx["locals"]=1; _st($1)._addAll_($2); $ctx1.sendIdx["addAll:"]=1; _st((function(){ return smalltalk.withContext(function($ctx2) { return _st(_st(inspectedContext)._notNil())._and_((function(){ return smalltalk.withContext(function($ctx3) { return _st(inspectedContext)._isBlockContext(); }, function($ctx3) {$ctx3.fillBlock({},$ctx2,2)})})); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}))._whileTrue_((function(){ return smalltalk.withContext(function($ctx2) { inspectedContext=_st(inspectedContext)._outerContext(); inspectedContext; $3=inspectedContext; if(($receiver = $3) == null || $receiver.isNil){ return $3; } else { return _st(variables)._addAll_(_st(inspectedContext)._locals()); }; }, function($ctx2) {$ctx2.fillBlock({},$ctx1,3)})})); _st(anInspector)._setLabel_("Context"); $4=_st(anInspector)._setVariables_(variables); return self}, function($ctx1) {$ctx1.fill(self,"inspectOn:",{anInspector:anInspector,variables:variables,inspectedContext:inspectedContext},globals.<API key>)})}, args: ["anInspector"], source: "inspectOn: anInspector\x0a\x09| variables inspectedContext |\x0a\x09\x0a\x09variables := Dictionary new.\x0a\x09inspectedContext := self context.\x0a\x09\x0a\x09variables addAll: inspectedContext locals.\x0a\x09\x0a\x09[ inspectedContext notNil and: [ inspectedContext isBlockContext ] ] whileTrue: [\x0a\x09\x09inspectedContext := inspectedContext outerContext.\x0a\x09\x09inspectedContext ifNotNil: [\x0a\x09\x09\x09variables addAll: inspectedContext locals ] ].\x0a\x09\x0a\x09anInspector\x0a\x09\x09setLabel: 'Context';\x0a\x09\x09setVariables: variables", messageSends: ["new", "context", "addAll:", "locals", "whileTrue:", "and:", "notNil", "isBlockContext", "outerContext", "ifNotNil:", "setLabel:", "setVariables:"], referencedClasses: ["Dictionary"] }), globals.<API key>); smalltalk.addMethod( smalltalk.method({ selector: "on:", protocol: 'instance creation', fn: function (aContext){ var self=this; return smalltalk.withContext(function($ctx1) { var $2,$3,$1; $2=self._new(); _st($2).<API key>(aContext); $3=_st($2)._yourself(); $1=$3; return $1; }, function($ctx1) {$ctx1.fill(self,"on:",{aContext:aContext},globals.<API key>.klass)})}, args: ["aContext"], source: "on: aContext\x0a\x09^ self new\x0a\x09\<API key>: aContext;\x0a\x09\x09yourself", messageSends: ["<API key>:", "new", "yourself"], referencedClasses: [] }), globals.<API key>.klass); smalltalk.addClass('HLDebugger', globals.HLFocusableWidget, ['model', 'stackListWidget', 'codeWidget', 'inspectorWidget'], 'Helios-Debugger'); globals.HLDebugger.comment="I am the main widget for the Helios debugger."; smalltalk.addMethod( smalltalk.method({ selector: "codeWidget", protocol: 'widgets', fn: function (){ var self=this; function $<API key>(){return globals.<API key>||(typeof <API key>=="undefined"?nil:<API key>)} function $HLDebuggerCodeModel(){return globals.HLDebuggerCodeModel||(typeof HLDebuggerCodeModel=="undefined"?nil:HLDebuggerCodeModel)} return smalltalk.withContext(function($ctx1) { var $2,$3,$4,$6,$7,$8,$9,$5,$10,$1,$receiver; $2=self["@codeWidget"]; if(($receiver = $2) == null || $receiver.isNil){ $3=_st($<API key>())._new(); $ctx1.sendIdx["new"]=1; $4=$3; $6=_st($HLDebuggerCodeModel())._new(); $7=$6; $8=self._model(); $ctx1.sendIdx["model"]=1; _st($7)._debuggerModel_($8); $9=_st($6)._yourself(); $ctx1.sendIdx["yourself"]=1; $5=$9; _st($4)._model_($5); _st($3)._browserModel_(self._model()); $10=_st($3)._yourself(); self["@codeWidget"]=$10; $1=self["@codeWidget"]; } else { $1=$2; }; return $1; }, function($ctx1) {$ctx1.fill(self,"codeWidget",{},globals.HLDebugger)})}, args: [], source: "codeWidget\x0a\x09^ codeWidget ifNil: [ codeWidget := <API key> new\x0a\x09\x09model: (HLDebuggerCodeModel new\x0a\x09\x09\x09debuggerModel: self model;\x0a\x09\x09\x09yourself);\x0a\x09\x09browserModel: self model;\x0a\x09\x09yourself ]", messageSends: ["ifNil:", "model:", "new", "debuggerModel:", "model", "yourself", "browserModel:"], referencedClasses: ["<API key>", "HLDebuggerCodeModel"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "cssClass", protocol: 'accessing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $2,$1; $2=($ctx1.supercall = true, globals.HLDebugger.superclass.fn.prototype._cssClass.apply(_st(self), [])); $ctx1.supercall = false; $1=_st($2).__comma(" hl_debugger"); return $1; }, function($ctx1) {$ctx1.fill(self,"cssClass",{},globals.HLDebugger)})}, args: [], source: "cssClass\x0a\x09^ super cssClass, ' hl_debugger'", messageSends: [",", "cssClass"], referencedClasses: [] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "focus", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._stackListWidget())._focus(); return self}, function($ctx1) {$ctx1.fill(self,"focus",{},globals.HLDebugger)})}, args: [], source: "focus\x0a\x09self stackListWidget focus", messageSends: ["focus", "stackListWidget"], referencedClasses: [] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "initializeFromError:", protocol: 'initialization', fn: function (anError){ var self=this; function $HLDebuggerModel(){return globals.HLDebuggerModel||(typeof HLDebuggerModel=="undefined"?nil:HLDebuggerModel)} return smalltalk.withContext(function($ctx1) { self["@model"]=_st($HLDebuggerModel())._on_(anError); self._observeModel(); return self}, function($ctx1) {$ctx1.fill(self,"initializeFromError:",{anError:anError},globals.HLDebugger)})}, args: ["anError"], source: "initializeFromError: anError\x0a\x09model := HLDebuggerModel on: anError.\x0a\x09self observeModel", messageSends: ["on:", "observeModel"], referencedClasses: ["HLDebuggerModel"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "inspectorWidget", protocol: 'widgets', fn: function (){ var self=this; function $HLInspectorWidget(){return globals.HLInspectorWidget||(typeof HLInspectorWidget=="undefined"?nil:HLInspectorWidget)} return smalltalk.withContext(function($ctx1) { var $2,$1,$receiver; $2=self["@inspectorWidget"]; if(($receiver = $2) == null || $receiver.isNil){ self["@inspectorWidget"]=_st($HLInspectorWidget())._new(); $1=self["@inspectorWidget"]; } else { $1=$2; }; return $1; }, function($ctx1) {$ctx1.fill(self,"inspectorWidget",{},globals.HLDebugger)})}, args: [], source: "inspectorWidget\x0a\x09^ inspectorWidget ifNil: [ \x0a\x09\x09inspectorWidget := HLInspectorWidget new ]", messageSends: ["ifNil:", "new"], referencedClasses: ["HLInspectorWidget"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "model", protocol: 'accessing', fn: function (){ var self=this; function $HLDebuggerModel(){return globals.HLDebuggerModel||(typeof HLDebuggerModel=="undefined"?nil:HLDebuggerModel)} return smalltalk.withContext(function($ctx1) { var $2,$1,$receiver; $2=self["@model"]; if(($receiver = $2) == null || $receiver.isNil){ self["@model"]=_st($HLDebuggerModel())._new(); $1=self["@model"]; } else { $1=$2; }; return $1; }, function($ctx1) {$ctx1.fill(self,"model",{},globals.HLDebugger)})}, args: [], source: "model\x0a\x09^ model ifNil: [ model := HLDebuggerModel new ]", messageSends: ["ifNil:", "new"], referencedClasses: ["HLDebuggerModel"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "observeModel", protocol: 'actions', fn: function (){ var self=this; function $<API key>(){return globals.<API key>||(typeof <API key>=="undefined"?nil:<API key>)} function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)} function $HLDebuggerProceeded(){return globals.HLDebuggerProceeded||(typeof HLDebuggerProceeded=="undefined"?nil:HLDebuggerProceeded)} return smalltalk.withContext(function($ctx1) { var $1,$2; $1=_st(self._model())._announcer(); _st($1)._on_send_to_($<API key>(),"onContextSelected:",self); $ctx1.sendIdx["on:send:to:"]=1; _st($1)._on_send_to_($HLDebuggerStepped(),"onDebuggerStepped:",self); $ctx1.sendIdx["on:send:to:"]=2; $2=_st($1)._on_send_to_($HLDebuggerProceeded(),"onDebuggerProceeded",self); return self}, function($ctx1) {$ctx1.fill(self,"observeModel",{},globals.HLDebugger)})}, args: [], source: "observeModel\x0a\x09self model announcer \x0a\x09\x09on: <API key>\x0a\x09\x09send: #onContextSelected:\x0a\x09\x09to: self;\x0a\x09\x09\x0a\x09\x09on: HLDebuggerStepped\x0a\x09\x09send: #onDebuggerStepped:\x0a\x09\x09to: self;\x0a\x09\x09\x0a\x09\x09on: HLDebuggerProceeded\x0a\x09\x09send: #onDebuggerProceeded\x0a\x09\x09to: self", messageSends: ["on:send:to:", "announcer", "model"], referencedClasses: ["<API key>", "HLDebuggerStepped", "HLDebuggerProceeded"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "onContextSelected:", protocol: 'reactions', fn: function (anAnnouncement){ var self=this; function $<API key>(){return globals.<API key>||(typeof <API key>=="undefined"?nil:<API key>)} return smalltalk.withContext(function($ctx1) { _st(self._inspectorWidget())._inspect_(_st($<API key>())._on_(_st(anAnnouncement)._context())); return self}, function($ctx1) {$ctx1.fill(self,"onContextSelected:",{anAnnouncement:anAnnouncement},globals.HLDebugger)})}, args: ["anAnnouncement"], source: "onContextSelected: anAnnouncement\x0a\x09self inspectorWidget inspect: (<API key> on: anAnnouncement context)", messageSends: ["inspect:", "inspectorWidget", "on:", "context"], referencedClasses: ["<API key>"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "onDebuggerProceeded", protocol: 'reactions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { self._removeTab(); return self}, function($ctx1) {$ctx1.fill(self,"onDebuggerProceeded",{},globals.HLDebugger)})}, args: [], source: "onDebuggerProceeded\x0a\x09self removeTab", messageSends: ["removeTab"], referencedClasses: [] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "onDebuggerStepped:", protocol: 'reactions', fn: function (anAnnouncement){ var self=this; function $<API key>(){return globals.<API key>||(typeof <API key>=="undefined"?nil:<API key>)} return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._model())._atEnd(); if(smalltalk.assert($1)){ self._removeTab(); }; _st(self._inspectorWidget())._inspect_(_st($<API key>())._on_(_st(anAnnouncement)._context())); _st(self._stackListWidget())._refresh(); return self}, function($ctx1) {$ctx1.fill(self,"onDebuggerStepped:",{anAnnouncement:anAnnouncement},globals.HLDebugger)})}, args: ["anAnnouncement"], source: "onDebuggerStepped: anAnnouncement\x0a\x09self model atEnd ifTrue: [ self removeTab ].\x0a\x09\x0a\x09self inspectorWidget inspect: (<API key> on: anAnnouncement context).\x0a\x09self stackListWidget refresh", messageSends: ["ifTrue:", "atEnd", "model", "removeTab", "inspect:", "inspectorWidget", "on:", "context", "refresh", "stackListWidget"], referencedClasses: ["<API key>"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "registerBindingsOn:", protocol: 'keybindings', fn: function (aBindingGroup){ var self=this; function $HLToolCommand(){return globals.HLToolCommand||(typeof HLToolCommand=="undefined"?nil:HLToolCommand)} return smalltalk.withContext(function($ctx1) { _st($HLToolCommand()).<API key>(aBindingGroup,self._model()); return self}, function($ctx1) {$ctx1.fill(self,"registerBindingsOn:",{aBindingGroup:aBindingGroup},globals.HLDebugger)})}, args: ["aBindingGroup"], source: "registerBindingsOn: aBindingGroup\x0a\x09HLToolCommand \x0a\x09\<API key>: aBindingGroup \x0a\x09\x09for: self model", messageSends: ["<API key>:for:", "model"], referencedClasses: ["HLToolCommand"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "renderContentOn:", protocol: 'rendering', fn: function (html){ var self=this; function $HLContainer(){return globals.HLContainer||(typeof HLContainer=="undefined"?nil:HLContainer)} function $HLVerticalSplitter(){return globals.HLVerticalSplitter||(typeof HLVerticalSplitter=="undefined"?nil:HLVerticalSplitter)} function $<API key>(){return globals.<API key>||(typeof <API key>=="undefined"?nil:<API key>)} return smalltalk.withContext(function($ctx1) { var $2,$1; self._renderHeadOn_(html); $2=_st($HLVerticalSplitter())._with_with_(self._codeWidget(),_st($<API key>())._with_with_(self._stackListWidget(),self._inspectorWidget())); $ctx1.sendIdx["with:with:"]=1; $1=_st($HLContainer())._with_($2); _st(html)._with_($1); $ctx1.sendIdx["with:"]=1; return self}, function($ctx1) {$ctx1.fill(self,"renderContentOn:",{html:html},globals.HLDebugger)})}, args: ["html"], source: "renderContentOn: html\x0a\x09self renderHeadOn: html.\x0a\x09html with: (HLContainer with: (HLVerticalSplitter\x0a\x09\x09with: self codeWidget\x0a\x09\x09with: (<API key>\x0a\x09\x09\x09with: self stackListWidget\x0a\x09\x09\x09with: self inspectorWidget)))", messageSends: ["renderHeadOn:", "with:", "with:with:", "codeWidget", "stackListWidget", "inspectorWidget"], referencedClasses: ["HLContainer", "HLVerticalSplitter", "<API key>"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "renderHeadOn:", protocol: 'rendering', fn: function (html){ var self=this; return smalltalk.withContext(function($ctx1) { var $1,$2; $1=_st(html)._div(); _st($1)._class_("head"); $2=_st($1)._with_((function(){ return smalltalk.withContext(function($ctx2) { return _st(_st(html)._h2())._with_(_st(_st(self._model())._error())._messageText()); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})})); $ctx1.sendIdx["with:"]=1; return self}, function($ctx1) {$ctx1.fill(self,"renderHeadOn:",{html:html},globals.HLDebugger)})}, args: ["html"], source: "renderHeadOn: html\x0a\x09html div \x0a\x09\x09class: 'head'; \x0a\x09\x09with: [ html h2 with: self model error messageText ]", messageSends: ["class:", "div", "with:", "h2", "messageText", "error", "model"], referencedClasses: [] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "stackListWidget", protocol: 'widgets', fn: function (){ var self=this; function $HLStackListWidget(){return globals.HLStackListWidget||(typeof HLStackListWidget=="undefined"?nil:HLStackListWidget)} return smalltalk.withContext(function($ctx1) { var $2,$3,$4,$1,$receiver; $2=self["@stackListWidget"]; if(($receiver = $2) == null || $receiver.isNil){ $3=_st($HLStackListWidget())._on_(self._model()); _st($3)._next_(self._codeWidget()); $4=_st($3)._yourself(); self["@stackListWidget"]=$4; $1=self["@stackListWidget"]; } else { $1=$2; }; return $1; }, function($ctx1) {$ctx1.fill(self,"stackListWidget",{},globals.HLDebugger)})}, args: [], source: "stackListWidget\x0a\x09^ stackListWidget ifNil: [ \x0a\x09\x09stackListWidget := (HLStackListWidget on: self model)\x0a\x09\x09\x09next: self codeWidget;\x0a\x09\x09\x09yourself ]", messageSends: ["ifNil:", "next:", "on:", "model", "codeWidget", "yourself"], referencedClasses: ["HLStackListWidget"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "unregister", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { ($ctx1.supercall = true, globals.HLDebugger.superclass.fn.prototype._unregister.apply(_st(self), [])); $ctx1.supercall = false; $ctx1.sendIdx["unregister"]=1; _st(self._inspectorWidget())._unregister(); return self}, function($ctx1) {$ctx1.fill(self,"unregister",{},globals.HLDebugger)})}, args: [], source: "unregister\x0a\x09super unregister.\x0a\x09self inspectorWidget unregister", messageSends: ["unregister", "inspectorWidget"], referencedClasses: [] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "on:", protocol: 'instance creation', fn: function (anError){ var self=this; return smalltalk.withContext(function($ctx1) { var $2,$3,$1; $2=self._new(); _st($2).<API key>(anError); $3=_st($2)._yourself(); $1=$3; return $1; }, function($ctx1) {$ctx1.fill(self,"on:",{anError:anError},globals.HLDebugger.klass)})}, args: ["anError"], source: "on: anError\x0a\x09^ self new\x0a\x09\<API key>: anError;\x0a\x09\x09yourself", messageSends: ["initializeFromError:", "new", "yourself"], referencedClasses: [] }), globals.HLDebugger.klass); smalltalk.addMethod( smalltalk.method({ selector: "tabClass", protocol: 'accessing', fn: function (){ var self=this; return "debugger"; }, args: [], source: "tabClass\x0a\x09^ 'debugger'", messageSends: [], referencedClasses: [] }), globals.HLDebugger.klass); smalltalk.addMethod( smalltalk.method({ selector: "tabLabel", protocol: 'accessing', fn: function (){ var self=this; return "Debugger"; }, args: [], source: "tabLabel\x0a\x09^ 'Debugger'", messageSends: [], referencedClasses: [] }), globals.HLDebugger.klass); smalltalk.addClass('HLDebuggerCodeModel', globals.HLCodeModel, ['debuggerModel'], 'Helios-Debugger'); smalltalk.addMethod( smalltalk.method({ selector: "debuggerModel", protocol: 'accessing', fn: function (){ var self=this; var $1; $1=self["@debuggerModel"]; return $1; }, args: [], source: "debuggerModel\x0a\x09^ debuggerModel", messageSends: [], referencedClasses: [] }), globals.HLDebuggerCodeModel); smalltalk.addMethod( smalltalk.method({ selector: "debuggerModel:", protocol: 'accessing', fn: function (anObject){ var self=this; self["@debuggerModel"]=anObject; return self}, args: ["anObject"], source: "debuggerModel: anObject\x0a\x09debuggerModel := anObject", messageSends: [], referencedClasses: [] }), globals.HLDebuggerCodeModel); smalltalk.addMethod( smalltalk.method({ selector: "doIt:", protocol: 'actions', fn: function (aString){ var self=this; function $ErrorHandler(){return globals.ErrorHandler||(typeof ErrorHandler=="undefined"?nil:ErrorHandler)} return smalltalk.withContext(function($ctx1) { var $1; $1=_st((function(){ return smalltalk.withContext(function($ctx2) { return _st(self._debuggerModel())._evaluate_(aString); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}))._tryCatch_((function(e){ return smalltalk.withContext(function($ctx2) { _st($ErrorHandler())._handleError_(e); return nil; }, function($ctx2) {$ctx2.fillBlock({e:e},$ctx1,2)})})); return $1; }, function($ctx1) {$ctx1.fill(self,"doIt:",{aString:aString},globals.HLDebuggerCodeModel)})}, args: ["aString"], source: "doIt: aString\x0a\x09^ [ self debuggerModel evaluate: aString ]\x0a\x09\x09tryCatch: [ :e | \x0a\x09\x09\x09ErrorHandler handleError: e.\x0a\x09\x09\x09nil ]", messageSends: ["tryCatch:", "evaluate:", "debuggerModel", "handleError:"], referencedClasses: ["ErrorHandler"] }), globals.HLDebuggerCodeModel); smalltalk.addClass('<API key>', globals.HLBrowserCodeWidget, [], 'Helios-Debugger'); smalltalk.addMethod( smalltalk.method({ selector: "addStopAt:", protocol: 'actions', fn: function (anInteger){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self["@editor"]).<API key>(anInteger,"stops",_st(_st("<div class=\x22stop\x22></stop>"._asJQuery())._toArray())._first()); return self}, function($ctx1) {$ctx1.fill(self,"addStopAt:",{anInteger:anInteger},globals.<API key>)})}, args: ["anInteger"], source: "addStopAt: anInteger\x0a\x09editor\x0a\x09\x09setGutterMarker: anInteger\x0a\x09\x09gutter: 'stops'\x0a\x09\x09value: '<div class=\x22stop\x22></stop>' asJQuery toArray first", messageSends: ["setGutterMarker:gutter:value:", "first", "toArray", "asJQuery"], referencedClasses: [] }), globals.<API key>); smalltalk.addMethod( smalltalk.method({ selector: "clearHighlight", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._editor())._clearGutter_("stops"); return self}, function($ctx1) {$ctx1.fill(self,"clearHighlight",{},globals.<API key>)})}, args: [], source: "clearHighlight\x0a\x09self editor clearGutter: 'stops'", messageSends: ["clearGutter:", "editor"], referencedClasses: [] }), globals.<API key>); smalltalk.addMethod( smalltalk.method({ selector: "contents:", protocol: 'accessing', fn: function (aString){ var self=this; return smalltalk.withContext(function($ctx1) { self._clearHighlight(); ($ctx1.supercall = true, globals.<API key>.superclass.fn.prototype._contents_.apply(_st(self), [aString])); $ctx1.supercall = false; return self}, function($ctx1) {$ctx1.fill(self,"contents:",{aString:aString},globals.<API key>)})}, args: ["aString"], source: "contents: aString\x0a\x09self clearHighlight.\x0a\x09super contents: aString", messageSends: ["clearHighlight", "contents:"], referencedClasses: [] }), globals.<API key>); smalltalk.addMethod( smalltalk.method({ selector: "editorOptions", protocol: 'accessing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $2,$3,$1; $2=($ctx1.supercall = true, globals.<API key>.superclass.fn.prototype._editorOptions.apply(_st(self), [])); $ctx1.supercall = false; _st($2)._at_put_("gutters",["<API key>", "stops"]); $3=_st($2)._yourself(); $1=$3; return $1; }, function($ctx1) {$ctx1.fill(self,"editorOptions",{},globals.<API key>)})}, args: [], source: "editorOptions\x0a\x09^ super editorOptions\x0a\x09\x09at: 'gutters' put: #('<API key>' 'stops');\x0a\x09\x09yourself", messageSends: ["at:put:", "editorOptions", "yourself"], referencedClasses: [] }), globals.<API key>); smalltalk.addMethod( smalltalk.method({ selector: "highlight", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1,$receiver; $1=_st(self._browserModel())._nextNode(); if(($receiver = $1) == null || $receiver.isNil){ $1; } else { var node; node=$receiver; self._highlightNode_(node); }; return self}, function($ctx1) {$ctx1.fill(self,"highlight",{},globals.<API key>)})}, args: [], source: "highlight\x0a\x09self browserModel nextNode ifNotNil: [ :node |\x0a\x09\x09self highlightNode: node ]", messageSends: ["ifNotNil:", "nextNode", "browserModel", "highlightNode:"], referencedClasses: [] }), globals.<API key>); smalltalk.addMethod( smalltalk.method({ selector: "highlightNode:", protocol: 'actions', fn: function (aNode){ var self=this; var token; return smalltalk.withContext(function($ctx1) { var $4,$3,$2,$1,$5,$9,$8,$7,$11,$10,$6,$15,$14,$13,$12,$receiver; if(($receiver = aNode) == null || $receiver.isNil){ aNode; } else { self._clearHighlight(); $4=_st(aNode)._positionStart(); $ctx1.sendIdx["positionStart"]=1; $3=_st($4)._x(); $ctx1.sendIdx["x"]=1; $2=_st($3).__minus((1)); $ctx1.sendIdx["-"]=1; $1=self._addStopAt_($2); $1; $5=self._editor(); $9=_st(aNode)._positionStart(); $ctx1.sendIdx["positionStart"]=2; $8=_st($9)._x(); $ctx1.sendIdx["x"]=2; $7=_st($8).__minus((1)); $ctx1.sendIdx["-"]=2; $11=_st(_st(aNode)._positionStart())._y(); $ctx1.sendIdx["y"]=1; $10=_st($11).__minus((1)); $ctx1.sendIdx["-"]=3; $6=globals.HashedCollection._newFromPairs_(["line",$7,"ch",$10]); $15=_st(aNode)._positionEnd(); $ctx1.sendIdx["positionEnd"]=1; $14=_st($15)._x(); $13=_st($14).__minus((1)); $12=globals.HashedCollection._newFromPairs_(["line",$13,"ch",_st(_st(aNode)._positionEnd())._y()]); _st($5)._setSelection_to_($6,$12); }; return self}, function($ctx1) {$ctx1.fill(self,"highlightNode:",{aNode:aNode,token:token},globals.<API key>)})}, args: ["aNode"], source: "highlightNode: aNode\x0a\x09| token |\x0a\x09\x0a\x09aNode ifNotNil: [\x0a\x09\x09self\x0a\x09\x09\x09clearHighlight;\x0a\x09\x09\x09addStopAt: aNode positionStart x - 1.\x0a\x0a\x09\x09self editor \x0a\x09\x09\x09setSelection: #{ 'line' -> (aNode positionStart x - 1). 'ch' -> (aNode positionStart y - 1) }\x0a\x09\x09\x09to: #{ 'line' -> (aNode positionEnd x - 1). 'ch' -> (aNode positionEnd y) } ]", messageSends: ["ifNotNil:", "clearHighlight", "addStopAt:", "-", "x", "positionStart", "setSelection:to:", "editor", "y", "positionEnd"], referencedClasses: [] }), globals.<API key>); smalltalk.addMethod( smalltalk.method({ selector: "observeBrowserModel", protocol: 'actions', fn: function (){ var self=this; function $<API key>(){return globals.<API key>||(typeof <API key>=="undefined"?nil:<API key>)} function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)} function $HLDebuggerWhere(){return globals.HLDebuggerWhere||(typeof HLDebuggerWhere=="undefined"?nil:HLDebuggerWhere)} return smalltalk.withContext(function($ctx1) { var $2,$1,$4,$3; ($ctx1.supercall = true, globals.<API key>.superclass.fn.prototype.<API key>.apply(_st(self), [])); $ctx1.supercall = false; $2=self._browserModel(); $ctx1.sendIdx["browserModel"]=1; $1=_st($2)._announcer(); $ctx1.sendIdx["announcer"]=1; _st($1)._on_send_to_($<API key>(),"onContextSelected",self); $ctx1.sendIdx["on:send:to:"]=1; $4=self._browserModel(); $ctx1.sendIdx["browserModel"]=2; $3=_st($4)._announcer(); $ctx1.sendIdx["announcer"]=2; _st($3)._on_send_to_($HLDebuggerStepped(),"onContextSelected",self); $ctx1.sendIdx["on:send:to:"]=2; _st(_st(self._browserModel())._announcer())._on_send_to_($HLDebuggerWhere(),"onContextSelected",self); return self}, function($ctx1) {$ctx1.fill(self,"observeBrowserModel",{},globals.<API key>)})}, args: [], source: "observeBrowserModel\x0a\x09super observeBrowserModel.\x0a\x09\x0a\x09self browserModel announcer \x0a\x09\x09on: <API key>\x0a\x09\x09send: #onContextSelected\x0a\x09\x09to: self.\x0a\x09\x0a\x09self browserModel announcer \x0a\x09\x09on: HLDebuggerStepped\x0a\x09\x09send: #onContextSelected\x0a\x09\x09to: self.\x0a\x09\x0a\x09self browserModel announcer \x0a\x09\x09on: HLDebuggerWhere\x0a\x09\x09send: #onContextSelected\x0a\x09\x09to: self", messageSends: ["observeBrowserModel", "on:send:to:", "announcer", "browserModel"], referencedClasses: ["<API key>", "HLDebuggerStepped", "HLDebuggerWhere"] }), globals.<API key>); smalltalk.addMethod( smalltalk.method({ selector: "onContextSelected", protocol: 'reactions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { self._highlight(); return self}, function($ctx1) {$ctx1.fill(self,"onContextSelected",{},globals.<API key>)})}, args: [], source: "onContextSelected\x0a\x09self highlight", messageSends: ["highlight"], referencedClasses: [] }), globals.<API key>); smalltalk.addMethod( smalltalk.method({ selector: "renderOn:", protocol: 'rendering', fn: function (html){ var self=this; return smalltalk.withContext(function($ctx1) { ($ctx1.supercall = true, globals.<API key>.superclass.fn.prototype._renderOn_.apply(_st(self), [html])); $ctx1.supercall = false; self._contents_(_st(_st(self._browserModel())._selectedMethod())._source()); return self}, function($ctx1) {$ctx1.fill(self,"renderOn:",{html:html},globals.<API key>)})}, args: ["html"], source: "renderOn: html\x0a\x09super renderOn: html.\x0a\x09self contents: self browserModel selectedMethod source", messageSends: ["renderOn:", "contents:", "source", "selectedMethod", "browserModel"], referencedClasses: [] }), globals.<API key>); smalltalk.addClass('HLDebuggerModel', globals.HLToolModel, ['rootContext', 'debugger', 'error'], 'Helios-Debugger'); globals.HLDebuggerModel.comment="I am a model for debugging Amber code in Helios.\x0a\x0aMy instances hold a reference to an `ASTDebugger` instance, itself referencing the current `context`. The context should be the root of the context stack."; smalltalk.addMethod( smalltalk.method({ selector: "atEnd", protocol: 'testing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._debugger())._atEnd(); return $1; }, function($ctx1) {$ctx1.fill(self,"atEnd",{},globals.HLDebuggerModel)})}, args: [], source: "atEnd\x0a\x09^ self debugger atEnd", messageSends: ["atEnd", "debugger"], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "contexts", protocol: 'accessing', fn: function (){ var self=this; var contexts,context; function $OrderedCollection(){return globals.OrderedCollection||(typeof OrderedCollection=="undefined"?nil:OrderedCollection)} return smalltalk.withContext(function($ctx1) { var $1; contexts=_st($OrderedCollection())._new(); context=self._rootContext(); _st((function(){ return smalltalk.withContext(function($ctx2) { return _st(context)._notNil(); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}))._whileTrue_((function(){ return smalltalk.withContext(function($ctx2) { _st(contexts)._add_(context); context=_st(context)._outerContext(); return context; }, function($ctx2) {$ctx2.fillBlock({},$ctx1,2)})})); $1=contexts; return $1; }, function($ctx1) {$ctx1.fill(self,"contexts",{contexts:contexts,context:context},globals.HLDebuggerModel)})}, args: [], source: "contexts\x0a\x09| contexts context |\x0a\x09\x0a\x09contexts := OrderedCollection new.\x0a\x09context := self rootContext.\x0a\x09\x0a\x09[ context notNil ] whileTrue: [\x0a\x09\x09contexts add: context.\x0a\x09\x09context := context outerContext ].\x0a\x09\x09\x0a\x09^ contexts", messageSends: ["new", "rootContext", "whileTrue:", "notNil", "add:", "outerContext"], referencedClasses: ["OrderedCollection"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "currentContext", protocol: 'accessing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._debugger())._context(); return $1; }, function($ctx1) {$ctx1.fill(self,"currentContext",{},globals.HLDebuggerModel)})}, args: [], source: "currentContext\x0a\x09^ self debugger context", messageSends: ["context", "debugger"], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "currentContext:", protocol: 'accessing', fn: function (aContext){ var self=this; function $<API key>(){return globals.<API key>||(typeof <API key>=="undefined"?nil:<API key>)} return smalltalk.withContext(function($ctx1) { var $1,$2; self._withChangesDo_((function(){ return smalltalk.withContext(function($ctx2) { self._selectedMethod_(_st(aContext)._method()); _st(self._debugger())._context_(aContext); $ctx2.sendIdx["context:"]=1; $1=_st($<API key>())._new(); _st($1)._context_(aContext); $2=_st($1)._yourself(); return _st(self._announcer())._announce_($2); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})})); return self}, function($ctx1) {$ctx1.fill(self,"currentContext:",{aContext:aContext},globals.HLDebuggerModel)})}, args: ["aContext"], source: "currentContext: aContext\x0a\x09self withChangesDo: [ \x0a\x09\x09self selectedMethod: aContext method.\x0a\x09\x09self debugger context: aContext.\x0a\x09\x09self announcer announce: (<API key> new\x0a\x09\x09\x09context: aContext;\x0a\x09\x09\x09yourself) ]", messageSends: ["withChangesDo:", "selectedMethod:", "method", "context:", "debugger", "announce:", "announcer", "new", "yourself"], referencedClasses: ["<API key>"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "debugger", protocol: 'accessing', fn: function (){ var self=this; function $ASTDebugger(){return globals.ASTDebugger||(typeof ASTDebugger=="undefined"?nil:ASTDebugger)} return smalltalk.withContext(function($ctx1) { var $2,$1,$receiver; $2=self["@debugger"]; if(($receiver = $2) == null || $receiver.isNil){ self["@debugger"]=_st($ASTDebugger())._new(); $1=self["@debugger"]; } else { $1=$2; }; return $1; }, function($ctx1) {$ctx1.fill(self,"debugger",{},globals.HLDebuggerModel)})}, args: [], source: "debugger\x0a\x09^ debugger ifNil: [ debugger := ASTDebugger new ]", messageSends: ["ifNil:", "new"], referencedClasses: ["ASTDebugger"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "error", protocol: 'accessing', fn: function (){ var self=this; var $1; $1=self["@error"]; return $1; }, args: [], source: "error\x0a\x09^ error", messageSends: [], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "evaluate:", protocol: 'evaluating', fn: function (aString){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._environment())._evaluate_for_(aString,self._currentContext()); return $1; }, function($ctx1) {$ctx1.fill(self,"evaluate:",{aString:aString},globals.HLDebuggerModel)})}, args: ["aString"], source: "evaluate: aString\x0a\x09^ self environment \x0a\x09\x09evaluate: aString \x0a\x09\x09for: self currentContext", messageSends: ["evaluate:for:", "environment", "currentContext"], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "flushInnerContexts", protocol: 'private', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=self._currentContext(); $ctx1.sendIdx["currentContext"]=1; _st($1)._innerContext_(nil); self["@rootContext"]=self._currentContext(); self._initializeContexts(); return self}, function($ctx1) {$ctx1.fill(self,"flushInnerContexts",{},globals.HLDebuggerModel)})}, args: [], source: "flushInnerContexts\x0a\x09\x22When stepping, the inner contexts are not relevent anymore,\x0a\x09and can be flushed\x22\x0a\x09\x0a\x09self currentContext innerContext: nil.\x0a\x09rootContext := self currentContext.\x0a\x09self initializeContexts", messageSends: ["innerContext:", "currentContext", "initializeContexts"], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "initializeFromError:", protocol: 'initialization', fn: function (anError){ var self=this; var errorContext; function $AIContext(){return globals.AIContext||(typeof AIContext=="undefined"?nil:AIContext)} return smalltalk.withContext(function($ctx1) { self["@error"]=anError; errorContext=_st($AIContext())._fromMethodContext_(_st(self["@error"])._context()); self["@rootContext"]=_st(self["@error"]).<API key>(errorContext); self._selectedMethod_(_st(self["@rootContext"])._method()); return self}, function($ctx1) {$ctx1.fill(self,"initializeFromError:",{anError:anError,errorContext:errorContext},globals.HLDebuggerModel)})}, args: ["anError"], source: "initializeFromError: anError\x0a\x09| errorContext |\x0a\x09\x0a\x09error := anError.\x0a\x09errorContext := (AIContext fromMethodContext: error context).\x0a\x09rootContext := error signalerContextFrom: errorContext.\x0a\x09self selectedMethod: rootContext method", messageSends: ["fromMethodContext:", "context", "signalerContextFrom:", "selectedMethod:", "method"], referencedClasses: ["AIContext"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "nextNode", protocol: 'accessing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._debugger())._node(); return $1; }, function($ctx1) {$ctx1.fill(self,"nextNode",{},globals.HLDebuggerModel)})}, args: [], source: "nextNode\x0a\x09^ self debugger node", messageSends: ["node", "debugger"], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "onStep", protocol: 'reactions', fn: function (){ var self=this; function $<API key>(){return globals.<API key>||(typeof <API key>=="undefined"?nil:<API key>)} return smalltalk.withContext(function($ctx1) { var $2,$1,$3,$4; self["@rootContext"]=self._currentContext(); $ctx1.sendIdx["currentContext"]=1; $2=self._currentContext(); $ctx1.sendIdx["currentContext"]=2; $1=_st($2)._method(); self._selectedMethod_($1); $3=_st($<API key>())._new(); _st($3)._context_(self._currentContext()); $4=_st($3)._yourself(); _st(self._announcer())._announce_($4); return self}, function($ctx1) {$ctx1.fill(self,"onStep",{},globals.HLDebuggerModel)})}, args: [], source: "onStep\x0a\x09rootContext := self currentContext.\x0a\x09\x0a\x09\x22Force a refresh of the context list and code widget\x22\x0a\x09self selectedMethod: self currentContext method.\x0a\x09self announcer announce: (<API key> new\x0a\x09\x09context: self currentContext;\x0a\x09\x09yourself)", messageSends: ["currentContext", "selectedMethod:", "method", "announce:", "announcer", "context:", "new", "yourself"], referencedClasses: ["<API key>"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "proceed", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerProceeded(){return globals.HLDebuggerProceeded||(typeof HLDebuggerProceeded=="undefined"?nil:HLDebuggerProceeded)} return smalltalk.withContext(function($ctx1) { _st(self._debugger())._proceed(); _st(self._announcer())._announce_(_st($HLDebuggerProceeded())._new()); return self}, function($ctx1) {$ctx1.fill(self,"proceed",{},globals.HLDebuggerModel)})}, args: [], source: "proceed\x0a\x09self debugger proceed.\x0a\x09\x0a\x09self announcer announce: HLDebuggerProceeded new", messageSends: ["proceed", "debugger", "announce:", "announcer", "new"], referencedClasses: ["HLDebuggerProceeded"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "restart", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)} return smalltalk.withContext(function($ctx1) { var $1,$2; _st(self._debugger())._restart(); self._onStep(); $1=_st($HLDebuggerStepped())._new(); _st($1)._context_(self._currentContext()); $2=_st($1)._yourself(); _st(self._announcer())._announce_($2); return self}, function($ctx1) {$ctx1.fill(self,"restart",{},globals.HLDebuggerModel)})}, args: [], source: "restart\x0a\x09self debugger restart.\x0a\x09self onStep.\x0a\x09\x0a\x09self announcer announce: (HLDebuggerStepped new\x0a\x09\x09context: self currentContext;\x0a\x09\x09yourself)", messageSends: ["restart", "debugger", "onStep", "announce:", "announcer", "context:", "new", "currentContext", "yourself"], referencedClasses: ["HLDebuggerStepped"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "rootContext", protocol: 'accessing', fn: function (){ var self=this; var $1; $1=self["@rootContext"]; return $1; }, args: [], source: "rootContext\x0a\x09^ rootContext", messageSends: [], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "stepOver", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)} return smalltalk.withContext(function($ctx1) { var $1,$2; _st(self._debugger())._stepOver(); self._onStep(); $1=_st($HLDebuggerStepped())._new(); _st($1)._context_(self._currentContext()); $2=_st($1)._yourself(); _st(self._announcer())._announce_($2); return self}, function($ctx1) {$ctx1.fill(self,"stepOver",{},globals.HLDebuggerModel)})}, args: [], source: "stepOver\x0a\x09self debugger stepOver.\x0a\x09self onStep.\x0a\x09\x0a\x09self announcer announce: (HLDebuggerStepped new\x0a\x09\x09context: self currentContext;\x0a\x09\x09yourself)", messageSends: ["stepOver", "debugger", "onStep", "announce:", "announcer", "context:", "new", "currentContext", "yourself"], referencedClasses: ["HLDebuggerStepped"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "where", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerWhere(){return globals.HLDebuggerWhere||(typeof HLDebuggerWhere=="undefined"?nil:HLDebuggerWhere)} return smalltalk.withContext(function($ctx1) { _st(self._announcer())._announce_(_st($HLDebuggerWhere())._new()); return self}, function($ctx1) {$ctx1.fill(self,"where",{},globals.HLDebuggerModel)})}, args: [], source: "where\x0a\x09self announcer announce: HLDebuggerWhere new", messageSends: ["announce:", "announcer", "new"], referencedClasses: ["HLDebuggerWhere"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "on:", protocol: 'instance creation', fn: function (anError){ var self=this; return smalltalk.withContext(function($ctx1) { var $2,$3,$1; $2=self._new(); _st($2).<API key>(anError); $3=_st($2)._yourself(); $1=$3; return $1; }, function($ctx1) {$ctx1.fill(self,"on:",{anError:anError},globals.HLDebuggerModel.klass)})}, args: ["anError"], source: "on: anError\x0a\x09^ self new\x0a\x09\<API key>: anError;\x0a\x09\x09yourself", messageSends: ["initializeFromError:", "new", "yourself"], referencedClasses: [] }), globals.HLDebuggerModel.klass); smalltalk.addClass('HLErrorHandler', globals.Object, [], 'Helios-Debugger'); smalltalk.addMethod( smalltalk.method({ selector: "confirmDebugError:", protocol: 'error handling', fn: function (anError){ var self=this; function $<API key>(){return globals.<API key>||(typeof <API key>=="undefined"?nil:<API key>)} return smalltalk.withContext(function($ctx1) { var $1,$2; $1=_st($<API key>())._new(); _st($1).<API key>(_st(anError)._messageText()); _st($1)._actionBlock_((function(){ return smalltalk.withContext(function($ctx2) { return self._debugError_(anError); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})})); _st($1)._cancelButtonLabel_("Abandon"); _st($1).<API key>("Debug"); $2=_st($1)._show(); return self}, function($ctx1) {$ctx1.fill(self,"confirmDebugError:",{anError:anError},globals.HLErrorHandler)})}, args: ["anError"], source: "confirmDebugError: anError\x0a\<API key> new\x0a\x09\<API key>: anError messageText;\x0a\x09\x09actionBlock: [ self debugError: anError ];\x0a\x09\<API key>: 'Abandon';\x0a\x09\<API key>: 'Debug';\x0a\x09\x09show", messageSends: ["confirmationString:", "new", "messageText", "actionBlock:", "debugError:", "cancelButtonLabel:", "confirmButtonLabel:", "show"], referencedClasses: ["<API key>"] }), globals.HLErrorHandler); smalltalk.addMethod( smalltalk.method({ selector: "debugError:", protocol: 'error handling', fn: function (anError){ var self=this; function $HLDebugger(){return globals.HLDebugger||(typeof HLDebugger=="undefined"?nil:HLDebugger)} function $Error(){return globals.Error||(typeof Error=="undefined"?nil:Error)} function $ConsoleErrorHandler(){return globals.ConsoleErrorHandler||(typeof ConsoleErrorHandler=="undefined"?nil:ConsoleErrorHandler)} return smalltalk.withContext(function($ctx1) { _st((function(){ return smalltalk.withContext(function($ctx2) { return _st(_st($HLDebugger())._on_(anError))._openAsTab(); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}))._on_do_($Error(),(function(error){ return smalltalk.withContext(function($ctx2) { return _st(_st($ConsoleErrorHandler())._new())._handleError_(error); }, function($ctx2) {$ctx2.fillBlock({error:error},$ctx1,2)})})); return self}, function($ctx1) {$ctx1.fill(self,"debugError:",{anError:anError},globals.HLErrorHandler)})}, args: ["anError"], source: "debugError: anError\x0a\x0a\x09[ \x0a\x09\x09(HLDebugger on: anError) openAsTab \x0a\x09] \x0a\x09\x09on: Error \x0a\x09\x09do: [ :error | ConsoleErrorHandler new handleError: error ]", messageSends: ["on:do:", "openAsTab", "on:", "handleError:", "new"], referencedClasses: ["HLDebugger", "Error", "ConsoleErrorHandler"] }), globals.HLErrorHandler); smalltalk.addMethod( smalltalk.method({ selector: "handleError:", protocol: 'error handling', fn: function (anError){ var self=this; return smalltalk.withContext(function($ctx1) { self._confirmDebugError_(anError); return self}, function($ctx1) {$ctx1.fill(self,"handleError:",{anError:anError},globals.HLErrorHandler)})}, args: ["anError"], source: "handleError: anError\x0a\x09self confirmDebugError: anError", messageSends: ["confirmDebugError:"], referencedClasses: [] }), globals.HLErrorHandler); smalltalk.addMethod( smalltalk.method({ selector: "onErrorHandled", protocol: 'error handling', fn: function (){ var self=this; function $HLProgressWidget(){return globals.HLProgressWidget||(typeof HLProgressWidget=="undefined"?nil:HLProgressWidget)} return smalltalk.withContext(function($ctx1) { var $1,$2; $1=_st($HLProgressWidget())._default(); _st($1)._flush(); $2=_st($1)._remove(); return self}, function($ctx1) {$ctx1.fill(self,"onErrorHandled",{},globals.HLErrorHandler)})}, args: [], source: "onErrorHandled\x0a\x09\x22when an error is handled, we need to make sure that\x0a\x09any progress bar widget gets removed. Because HLProgressBarWidget is asynchronous,\x0a\x09it has to be done here.\x22\x0a\x09\x0a\x09HLProgressWidget default \x0a\x09\x09flush; \x0a\x09\x09remove", messageSends: ["flush", "default", "remove"], referencedClasses: ["HLProgressWidget"] }), globals.HLErrorHandler); smalltalk.addClass('HLStackListWidget', globals.HLToolListWidget, [], 'Helios-Debugger'); smalltalk.addMethod( smalltalk.method({ selector: "items", protocol: 'accessing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._model())._contexts(); return $1; }, function($ctx1) {$ctx1.fill(self,"items",{},globals.HLStackListWidget)})}, args: [], source: "items\x0a\x09^ self model contexts", messageSends: ["contexts", "model"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "label", protocol: 'accessing', fn: function (){ var self=this; return "Call stack"; }, args: [], source: "label\x0a\x09^ 'Call stack'", messageSends: [], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "observeModel", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)} return smalltalk.withContext(function($ctx1) { ($ctx1.supercall = true, globals.HLStackListWidget.superclass.fn.prototype._observeModel.apply(_st(self), [])); $ctx1.supercall = false; _st(_st(self._model())._announcer())._on_send_to_($HLDebuggerStepped(),"onDebuggerStepped:",self); return self}, function($ctx1) {$ctx1.fill(self,"observeModel",{},globals.HLStackListWidget)})}, args: [], source: "observeModel\x0a\x09super observeModel.\x0a\x09\x0a\x09self model announcer \x0a\x09\x09on: HLDebuggerStepped\x0a\x09\x09send: #onDebuggerStepped:\x0a\x09\x09to: self", messageSends: ["observeModel", "on:send:to:", "announcer", "model"], referencedClasses: ["HLDebuggerStepped"] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "onDebuggerStepped:", protocol: 'reactions', fn: function (anAnnouncement){ var self=this; return smalltalk.withContext(function($ctx1) { self["@items"]=nil; self._refresh(); return self}, function($ctx1) {$ctx1.fill(self,"onDebuggerStepped:",{anAnnouncement:anAnnouncement},globals.HLStackListWidget)})}, args: ["anAnnouncement"], source: "onDebuggerStepped: anAnnouncement\x0a\x09items := nil.\x0a\x09self refresh", messageSends: ["refresh"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "proceed", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._model())._proceed(); return self}, function($ctx1) {$ctx1.fill(self,"proceed",{},globals.HLStackListWidget)})}, args: [], source: "proceed\x0a\x09self model proceed", messageSends: ["proceed", "model"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "renderButtonsOn:", protocol: 'rendering', fn: function (html){ var self=this; return smalltalk.withContext(function($ctx1) { var $1,$3,$4,$5,$6,$7,$8,$9,$10,$2; $1=_st(html)._div(); _st($1)._class_("debugger_bar"); $ctx1.sendIdx["class:"]=1; $2=_st($1)._with_((function(){ return smalltalk.withContext(function($ctx2) { $3=_st(html)._button(); $ctx2.sendIdx["button"]=1; _st($3)._class_("btn restart"); $ctx2.sendIdx["class:"]=2; _st($3)._with_("Restart"); $ctx2.sendIdx["with:"]=2; $4=_st($3)._onClick_((function(){ return smalltalk.withContext(function($ctx3) { return self._restart(); }, function($ctx3) {$ctx3.fillBlock({},$ctx2,2)})})); $ctx2.sendIdx["onClick:"]=1; $4; $5=_st(html)._button(); $ctx2.sendIdx["button"]=2; _st($5)._class_("btn where"); $ctx2.sendIdx["class:"]=3; _st($5)._with_("Where"); $ctx2.sendIdx["with:"]=3; $6=_st($5)._onClick_((function(){ return smalltalk.withContext(function($ctx3) { return self._where(); }, function($ctx3) {$ctx3.fillBlock({},$ctx2,3)})})); $ctx2.sendIdx["onClick:"]=2; $6; $7=_st(html)._button(); $ctx2.sendIdx["button"]=3; _st($7)._class_("btn stepOver"); $ctx2.sendIdx["class:"]=4; _st($7)._with_("Step over"); $ctx2.sendIdx["with:"]=4; $8=_st($7)._onClick_((function(){ return smalltalk.withContext(function($ctx3) { return self._stepOver(); }, function($ctx3) {$ctx3.fillBlock({},$ctx2,4)})})); $ctx2.sendIdx["onClick:"]=3; $8; $9=_st(html)._button(); _st($9)._class_("btn proceed"); _st($9)._with_("Proceed"); $10=_st($9)._onClick_((function(){ return smalltalk.withContext(function($ctx3) { return self._proceed(); }, function($ctx3) {$ctx3.fillBlock({},$ctx2,5)})})); return $10; }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})})); $ctx1.sendIdx["with:"]=1; return self}, function($ctx1) {$ctx1.fill(self,"renderButtonsOn:",{html:html},globals.HLStackListWidget)})}, args: ["html"], source: "renderButtonsOn: html\x0a\x09html div \x0a\x09\x09class: 'debugger_bar'; \x0a\x09\x09with: [\x0a\x09\x09\x09html button \x0a\x09\x09\x09\x09class: 'btn restart';\x0a\x09\x09\x09\x09with: 'Restart';\x0a\x09\x09\x09\x09onClick: [ self restart ].\x0a\x09\x09\x09html button \x0a\x09\x09\x09\x09class: 'btn where';\x0a\x09\x09\x09\x09with: 'Where';\x0a\x09\x09\x09\x09onClick: [ self where ].\x0a\x09\x09\x09html button \x0a\x09\x09\x09\x09class: 'btn stepOver';\x0a\x09\x09\x09\x09with: 'Step over';\x0a\x09\x09\x09\x09onClick: [ self stepOver ].\x0a\x09\x09\x09html button \x0a\x09\x09\x09\x09class: 'btn proceed';\x0a\x09\x09\x09\x09with: 'Proceed';\x0a\x09\x09\x09\x09onClick: [ self proceed ] ]", messageSends: ["class:", "div", "with:", "button", "onClick:", "restart", "where", "stepOver", "proceed"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "restart", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._model())._restart(); return self}, function($ctx1) {$ctx1.fill(self,"restart",{},globals.HLStackListWidget)})}, args: [], source: "restart\x0a\x09self model restart", messageSends: ["restart", "model"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "selectItem:", protocol: 'actions', fn: function (aContext){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._model())._currentContext_(aContext); ($ctx1.supercall = true, globals.HLStackListWidget.superclass.fn.prototype._selectItem_.apply(_st(self), [aContext])); $ctx1.supercall = false; return self}, function($ctx1) {$ctx1.fill(self,"selectItem:",{aContext:aContext},globals.HLStackListWidget)})}, args: ["aContext"], source: "selectItem: aContext\x0a \x09self model currentContext: aContext.\x0a\x09super selectItem: aContext", messageSends: ["currentContext:", "model", "selectItem:"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "selectedItem", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._model())._currentContext(); return $1; }, function($ctx1) {$ctx1.fill(self,"selectedItem",{},globals.HLStackListWidget)})}, args: [], source: "selectedItem\x0a \x09^ self model currentContext", messageSends: ["currentContext", "model"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "stepOver", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._model())._stepOver(); return self}, function($ctx1) {$ctx1.fill(self,"stepOver",{},globals.HLStackListWidget)})}, args: [], source: "stepOver\x0a\x09self model stepOver", messageSends: ["stepOver", "model"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "where", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._model())._where(); return self}, function($ctx1) {$ctx1.fill(self,"where",{},globals.HLStackListWidget)})}, args: [], source: "where\x0a\x09self model where", messageSends: ["where", "model"], referencedClasses: [] }), globals.HLStackListWidget); });
MIME-Version: 1.0 Server: CERN/3.0 Date: Monday, 16-Dec-96 23:33:46 GMT Content-Type: text/html Content-Length: 3390 Last-Modified: Tuesday, 20-Feb-96 22:21:50 GMT <html> <head> <title> CodeWarrior for CS100 </title> </head> <body> <h2> Setting Up CodeWarrior for CS100 </h2> CodeWarrior can be run on your own personal Macintosh. Copies of CodeWarrior 8 can be purchased from the Campus Store. The CodeWarrior installed in the CIT labs is just like the one you would install on your Mac, except for a few things we have added -- the CSLib library and the CS100 Basic project stationery. <p> <strong>Note:</strong> These additions were built using CodeWarrior version 8, so it is possible that they will not work with earlier versions of CodeWarrior (although we have heard from people that they do). <p> Once you have retrieved the CS100 Additions folder, install the additions as follows: <ul> <li> Open the CS100 Additions folder. Inside it there is a SimpleText file containing instructions similar to these. There are two folders called INTO MacOS Support and INTO (Project Stationery). The folder structure in the CS100 Additions folder is meant to mirror the folder structure inside the Metrowerks CodeWarrior folder of your copy of CodeWarrior, to make it easy to follow these instructions. <p> <li> Open your CodeWarrior8 or CW 8 Gold folder. Open the Metrowerks CodeWarrior folder inside it. <p> <li> Open the INTO MacOS Support folder in the CS100 additions. Move the CS100 Support folder into the MacOS Support folder in your Metrowerks CodeWarrior folder. <p> <li> Open the INTO (Project Stationery) folder. Move the CS100 Basic 68K.mu file into the (Project Stationery) folder in your Metrowerks CodeWarrior folder. <p> <li> Open the INTO Proj. Stat. Support folder in the INTO (Project Stationery) folder. Move the <replace me CS100>.c file into the Project Stationery Support folder in the (Project Stationery) folder of your CodeWarrior. <p> </ul> When you open a new project with CodeWarrior, you should now be able to select the CS100 Basic 68K stationery. This will include the CSLib library, which should also now be available to you. <hr> Click here to get the CS100 Additions folder. <p> <a href = "ftp://ftp.cs.cornell.edu/pub/courses/cs100-s96/CS100Additions.sea.hqx"> CS100 Additions Folder </a> <hr> <h3>Other Machines</h3> If you have a copy of CodeWarrior for a computer other than the Mac, you may still be able to set up the CS100 environment. However, the course staff will not be able support this. <ol> <li> Build the CSLib library. Get the source code for by anonymous FTP from Addison-Wesley. Follow the instructions on page 670 in the Roberts textbook (Appendix B, Library Sources). Compile the source code on your machine using CodeWarrior. (To create the CSLib library for CS100 we only compiled the <code>genlib</code>, <code>simpio</code>, <code>string</code>, <code>random</code>, and <code>exception</code> parts of the library; we left out the graphics stuff. If everything seems to work for your machine, feel free to compile all of it.) Put the compiled library and the library header files into the support directory for your CodeWarrior. <p> <li> Make the CS100 Basic project stationery. Our project stationery is based on the ANSI project stationery, with the CSLib library added. Put your project stationery in the project stationery directory of your CodeWarrior. </ol> </body> <hr> <address> CS100 Spring 1996 <br> pierce@cs.cornell.edu </address> </html>
<div ng-class="{ invalid: !ngDisabled && !valid }"> <div class="form-group"> <label ng-show="ngLabel" class="control-label">{{ngLabel}}<small ng-show="ngTip">({{ngTip}})</small></label> <div class="row <API key>"> <div class="col-sm-6 <API key>" ng-class="{ 'has-error': !ngDisabled && !valid && coordinates.longitude === '', 'has-feedback': !ngDisabled && !valid && coordinates.longitude === '' }"> <input type="text" class="form-control" ng-disabled="ngDisabled" ng-class="{ 'coordinates-invalid': !ngDisabled && !valid && coordinates.longitude === '' }" ng-model="coordinates.longitude" ng-change="changed()" placeholder="longitude" ng-keypress="<API key>($event)" /> <span ng-show="!ngDisabled && !valid && coordinates.longitude === ''" tooltip="value is required" class="glyphicon <API key> <API key>"></span> </div> <div class="col-sm-6 <API key>" ng-class="{ 'has-error': !ngDisabled && !valid && coordinates.latitude === '', 'has-feedback': !ngDisabled && !valid.latitude === '' }"> <input type="text" class="form-control" ng-disabled="ngDisabled" ng-class="{ 'coordinates-invalid': !ngDisabled && !valid && coordinates.latitude === '' }" ng-model="coordinates.latitude" ng-change="changed()" placeholder="latitude" ng-keypress="<API key>($event)" /> <span ng-show="!ngDisabled && !valid && coordinates.latitude === ''" tooltip="value is required" class="glyphicon <API key> <API key>"></span> </div> </div> <div class="map-container" ng-class="{ 'map-disabled': ngDisabled }"> <div id="map{{id}}" class="form-map" ng-style="{ 'height': height }"></div> </div> </div> </div>
def calc(): h, l = input().split(' ') mapa = [] for i_row in range(int(h)): mapa.append(input().split(' ')) maior_num = 0 for row in mapa: for col in row: n = int(col) if (n > maior_num): maior_num = n qtd = [0 for i in range(maior_num + 1)] for row in mapa: for col in row: n = int(col) qtd[n] = qtd[n] + 1 menor = 1 for i in range(1, len(qtd)): if (qtd[i] <= qtd[menor]): menor = i print(menor) calc()
package com.stulsoft.ysps.pduration import scala.concurrent.duration._ object PDuration { def main(args: Array[String]): Unit = { println("==>main") var fiveSec = 5.seconds println(s"fiveSec=$fiveSec") fiveSec = 15.seconds println(s"fiveSec=$fiveSec") println("<==main") } }
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QApplication> #include <QMainWindow> #include <QTextEdit> #include <QMenu> #include <QMenuBar> #include <QAction> #include <QDialog> #include <QDesktopWidget> #include <QMdiArea> #include <QMdiSubWindow> #include <QDockWidget> #include <QTreeWidget> #include <QProcess> #include <QTimer> #include <vector> #include <cassert> #include "CodeArea.h" #include "Console.h" #include "FnSelectDialog.h" #include "Outline.h" class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(); QSize sizeHint() const; void flattenedOutline(FlattenedOutline *outline) const; signals: public slots: void fnSelect(); void toggleSimple(); void openFileDialog(); void saveFile(); void saveFileAsDialog(); void setActiveCodeArea(QMdiSubWindow *area); void runProgram(); void runPythonParser(); void <API key>(); void <API key>(int exitCode, QProcess::ExitStatus exitStatus); void jumpToFunction(QTreeWidgetItem* item, int column); private: QMdiArea *mainArea; // process QProcess *programProcess; QProcess *pythonParserProcess; // console Console *console; QDockWidget *consoleDock; // editor CodeArea *activeCodeArea; std::vector<CodeArea*> codeAreas; FnSelectDialog *fnSelectDialog; // code outline QTreeWidget *codeOutline; QDockWidget *codeOutlineDock; std::vector<OutlineClass> outlineClasses; QTreeWidgetItem *functionsHeader; // timer QTimer *parseTimer; // console actions QAction *runProgramAction; // menus QMenu *fileMenu; QMenu *helpMenu; // menu actions QAction *openFileAction; QAction *saveFileAction; QAction *saveFileAsAction; // code actions QAction *fnSelectAction; // ui actions QAction *toggleSimpleAction; bool usingSimple; // project actions QAction *<API key>; QAction *<API key>; // git actions QAction *openGitDialogAction; // program actions QAction *exitProgramAction; // meta QString lastUsedDirectory; }; #endif
/** * Error for services to through when they encounter a problem with the request. * Distinguishes between a bad service request and a general error */ function ServiceError(message) { this.name = "ServiceError"; this.message = (message || ""); } ServiceError.prototype = Object.create(Error.prototype, { constructor: {value: ServiceError} }); /** * Error for when an item is not found */ function NotFoundError(message) { this.name = "NotFoundError"; this.message = (message || "Not found"); } NotFoundError.prototype = Object.create(ServiceError.prototype, { constructor: { value: NotFoundError} }); exports.ServiceError = ServiceError; exports.NotFoundError = NotFoundError;
import shaven from 'shaven' const svgNS = 'http: export default function (svg, config) { const yDensity = 0.1 const yRange = config.max.value - config.min.value const graphHeight = config.height * 0.8 const graphWidth = config.width * 0.95 const coSysHeight = config.height * 0.6 const coSysWidth = config.width * 0.85 const barchart = shaven( ['g', { transform: 'translate(' + [graphWidth * 0.1, graphHeight].join() + ')', }], svgNS, )[0] const coordinateSystem = shaven(['g'], svgNS)[0] const bars = shaven(['g'], svgNS)[0] function <API key> () { function ordinates () { let cssClass let index for (index = 0; index < config.size; index++) { cssClass = index === 0 ? '<API key>' : '<API key>' shaven( [coordinateSystem, ['line', { class: cssClass, x1: (coSysWidth / config.size) * index, y1: '5', x2: (coSysWidth / config.size) * index, y2: -coSysHeight, }], ['text', config.keys[index], { class: '<API key>', transform: 'rotate(40 ' + ((coSysWidth / config.size) * index) + ', 10)', // <API key> id-length x: (coSysWidth / config.size) * index, y: 10, // eslint-disable-line id-length }], ], svgNS, ) } } function abscissas () { let styleClass let index for (index = 0; index <= (yRange * yDensity); index++) { styleClass = index === 0 ? '<API key>' : '<API key>' shaven( [coordinateSystem, ['line', { class: styleClass, x1: -5, y1: -(coSysHeight / yRange) * (index / yDensity), x2: coSysWidth, y2: -(coSysHeight / yRange) * (index / yDensity), }], ['text', String(index / yDensity + config.min.value), { class: '<API key>', x: -coSysWidth * 0.05, // eslint-disable-line id-length // <API key> id-length y: -(coSysHeight / yRange) * (index / yDensity), }], ], svgNS, ) } } abscissas() ordinates() } function buildBars () { function drawBar (element, index) { const height = config.animations ? 0 : (config.values[index] - config.min.value) * (coSysHeight / yRange) const bar = shaven( ['rect', { class: 'vectual_bar_bar', // <API key> id-length x: index * (coSysWidth / config.size), // <API key> id-length y: -(config.values[index] - config.min.value) * (coSysHeight / yRange), height: height, width: 0.7 * (coSysWidth / config.size), }, ['title', config.keys[index] + ': ' + config.values[index]], ], svgNS, )[0] function localSetAnimations () { shaven( [bar, ['animate', { attributeName: 'height', to: (config.values[index] - config.min.value) * (coSysHeight / yRange), begin: '0s', dur: '1s', fill: 'freeze', }], ['animate', { attributeName: 'y', from: 0, to: -(config.values[index] - config.min.value) * (coSysHeight / yRange), begin: '0s', dur: '1s', fill: 'freeze', }], ['animate', { attributeName: 'fill', to: 'rgb(100,210,255)', begin: 'mouseover', dur: '100ms', fill: 'freeze', additive: 'replace', }], ['animate', { attributeName: 'fill', to: 'rgb(0,150,250)', begin: 'mouseout', dur: '200ms', fill: 'freeze', additive: 'replace', }], ], svgNS, ) } function localInject () { shaven([bars, [bar]]) } if (config.animations) localSetAnimations() localInject() } config.data.forEach(drawBar) } function setAnimations () { shaven( [bars, ['animate', { attributeName: 'opacity', from: 0, to: 0.8, begin: '0s', dur: '1s', fill: 'freeze', additive: 'replace', }], ], svgNS, ) } function inject () { shaven( [svg, [barchart, [coordinateSystem], [bars], ], ], ) } <API key>() buildBars() if (config.animations) setAnimations() inject() return svg }
require File.dirname(__FILE__) + '/spec' class Object class << self # Lookup missing generators using const_missing. This allows any # generator to reference another without having to know its location: # RubyGems, ~/.rubigen/generators, and APP_ROOT/generators. def <API key>(class_id) if md = /(.+)Generator$/.match(class_id.to_s) name = md.captures.first.demodulize.underscore RubiGen::Base.active.lookup(name).klass else <API key>(class_id) end end unless respond_to?(:<API key>) alias_method :<API key>, :const_missing alias_method :const_missing, :<API key> end end end # User home directory lookup adapted from RubyGems. def Dir.user_home if ENV['HOME'] ENV['HOME'] elsif ENV['USERPROFILE'] ENV['USERPROFILE'] elsif ENV['HOMEDRIVE'] and ENV['HOMEPATH'] "#{ENV['HOMEDRIVE']}:#{ENV['HOMEPATH']}" else File.expand_path '~' end end module RubiGen # Generator lookup is managed by a list of sources which return specs # describing where to find and how to create generators. This module # provides class methods for manipulating the source list and looking up # generator specs, and an #instance wrapper for quickly instantiating # generators by name. # A spec is not a generator: it's a description of where to find # the generator and how to create it. A source is anything that # yields generators from #each. PathSource and GemGeneratorSource are provided. module Lookup def self.included(base) base.extend(ClassMethods) # base.<API key>! # TODO is this required since it has no scope/source context end # Convenience method to instantiate another generator. def instance(generator_name, args, runtime_options = {}) self.class.active.instance(generator_name, args, runtime_options) end module ClassMethods # The list of sources where we look, in order, for generators. def sources if <API key>(:sources).blank? if superclass == RubiGen::Base superclass_sources = superclass.sources diff = superclass_sources.inject([]) do |mem, source| found = false application_sources.each { |app_source| found ||= true if app_source == source} mem << source unless found mem end <API key>(:sources, diff) end active.<API key>! if <API key>(:sources).blank? end <API key>(:sources) end # Add a source to the end of the list. def append_sources(*args) sources.concat(args.flatten) invalidate_cache! end # Add a source to the beginning of the list. def prepend_sources(*args) sources = self.sources reset_sources <API key>(:sources, args.flatten + sources) invalidate_cache! end # Reset the source list. def reset_sources <API key>(:sources, []) invalidate_cache! end # Use application generators (app, ?). def <API key>!(*filters) reset_sources <API key>(:sources, application_sources(filters)) end def application_sources(filters = []) filters.unshift 'app' app_sources = [] app_sources << PathSource.new(:builtin, File.join(File.dirname(__FILE__), %w[.. .. app_generators])) app_sources << filtered_sources(filters) app_sources.flatten end # Use component generators (test_unit, etc). # 1. Current application. If APP_ROOT is defined we know we're # generating in the context of this application, so search # APP_ROOT/generators. # 2. User home directory. Search ~/.rubigen/generators. # 3. RubyGems. Search for gems containing /{scope}_generators folder. # 4. Builtins. None currently. # Search can be filtered by passing one or more prefixes. # e.g. <API key>!(:rubygems) means it will also search in the following # folders: # 5. User home directory. Search ~/.rubigen/rubygems_generators. # 6. RubyGems. Search for gems containing /rubygems_generators folder. def <API key>!(*filters) reset_sources new_sources = [] if defined? ::APP_ROOT new_sources << PathSource.new(:root, "#{::APP_ROOT}/generators") new_sources << PathSource.new(:vendor, "#{::APP_ROOT}/vendor/generators") new_sources << PathSource.new(:plugins, "#{::APP_ROOT}/vendor/pluginsgenerators") end new_sources << filtered_sources(filters) <API key>(:sources, new_sources.flatten) end def filtered_sources(filters) new_sources = [] new_sources << PathFilteredSource.new(:user, "#{Dir.user_home}/.rubigen/", *filters) if Object.const_defined?(:Gem) new_sources << GemPathSource.new(*filters) end new_sources end # Lookup knows how to find generators' Specs from a list of Sources. # Searches the sources, in order, for the first matching name. def lookup(generator_name) @found ||= {} generator_name = generator_name.to_s.downcase @found[generator_name] ||= cache.find { |spec| spec.name == generator_name } unless @found[generator_name] chars = generator_name.scan(/./).map{|c|" rx = /^#{chars}$/ gns = cache.select {|spec| spec.name =~ rx } @found[generator_name] ||= gns.first if gns.length == 1 raise GeneratorError, "Pattern '#{generator_name}' matches more than one generator: #{gns.map{|sp|sp.name}.join(', ')}" if gns.length > 1 end @found[generator_name] or raise GeneratorError, "Couldn't find '#{generator_name}' generator" end # Convenience method to lookup and instantiate a generator. def instance(generator_name, args = [], runtime_options = {}) active.lookup(generator_name).klass.new(args, full_options(runtime_options)) end private # Lookup and cache every generator from the source list. def cache @cache ||= sources.inject([]) { |cache, source| cache + source.to_a } end # Clear the cache whenever the source list changes. def invalidate_cache! @cache = nil end end end # Sources enumerate (yield from #each) generator specs which describe # where to find and how to create generators. Enumerable is mixed in so, # for example, source.collect will retrieve every generator. # Sources may be assigned a label to distinguish them. class Source include Enumerable attr_reader :label def initialize(label) @label = label end # The each method must be implemented in subclasses. # The base implementation raises an error. def each raise NotImplementedError end # Return a convenient sorted list of all generator names. def names(filter = nil) inject([]) do |mem, spec| case filter when :visible mem << spec.name if spec.visible? end mem end.sort end end # PathSource looks for generators in a filesystem directory. class PathSource < Source attr_reader :path def initialize(label, path) super label @path = File.expand_path path end # Yield each eligible subdirectory. def each Dir["#{path}/[a-z]*"].each do |dir| if File.directory?(dir) yield Spec.new(File.basename(dir), dir, label) end end end def ==(source) self.class == source.class && path == source.path end end class PathFilteredSource < PathSource attr_reader :filters def initialize(label, path, *filters) super label, File.join(path, "#{filter_str(filters)}generators") end def filter_str(filters) @filters = filters.first.is_a?(Array) ? filters.first : filters return "" if @filters.blank? filter_str = @filters.map {|filter| "#{filter}_"}.join(",") filter_str += "," "{#{filter_str}}" end def ==(source) self.class == source.class && path == source.path && filters == source.filters && label == source.label end end class AbstractGemSource < Source def initialize super :RubyGems end end # GemPathSource looks for generators within any RubyGem's /{filter_}generators<generator_name>_generator.rb file. class GemPathSource < AbstractGemSource attr_accessor :filters def initialize(*filters) super() @filters = filters end # Yield each generator within rails_generator subdirectories. def each <API key>.each do |generator| yield Spec.new(File.basename(generator).sub(/_generator.rb$/, ''), File.dirname(generator), label) end end def ==(source) self.class == source.class && filters == source.filters end private def <API key> @<API key> ||= Gem::cache.inject({}) do |latest, name_gem| name, gem = name_gem hem = latest[gem.name] latest[gem.name] = gem if hem.nil? or gem.version > hem.version latest end.values.inject([]) do |mem, gem| Dir[gem.full_gem_path + "/#{filter_str}generators*_generator.rb"].each do |generator| mem << generator end mem end.reverse end def filter_str @filters = filters.first.is_a?(Array) ? filters.first : filters return "" if filters.blank? filter_str = filters.map {|filter| "#{filter}_"}.join(",") filter_str += "," "{#{filter_str}}" end end end
<sup><sup>*Release notes were automatically generated by [Shipkit](http://shipkit.org/)*</sup></sup> # 0.9.17 - 2020-05-31 - [17 commits](https: - [Enhancement] Deploy locally to OpenHAB [( # 0.9.14 - 2019-03-18 - [2 commits](https: - No pull requests referenced in commit messages. # 0.9.13 - 2019-03-18 - [2 commits](https: - [Bug] # 0.9.12 - 2019-03-18 - no code changes (no commits) - published to [![Bintray](https: # 0.9.11 - 2019-03-18 - [5 commits](https: - [Enhancement] Add LGTM badges [( - [Enhancement] Update protocol to ver. 10 [( - [Enhancement] Move long running tests to integration tests package [( - - - # 0.9.10 - 2019-03-08 - [5 commits](https: - [Enhancement] Add Shipkit [( # 0.9.9 - 2019-03-04 - [3 commits](https: - [Enhancement] Add Shipkit [( # 0.9.8 - 2019-03-04 - [1 commit](https: - [Enhancement] Add Shipkit [( # 0.9.7 - 2019-03-04 - [1 commit](https: - [Enhancement] Add Shipkit [( # 0.9.6 - 2019-03-04 - [2 commits](https: - [Enhancement] Add Shipkit [( # 0.9.5 - 2019-02-20 - [1 commit](https: - [Enhancement] Add Shipkit [( # 0.9.4 - 2019-02-20 - no code changes (no commits) - published to [![Bintray](https: # 0.9.3 - 2019-02-20 - [1 commit](https: - [Enhancement] Add Shipkit [( # 0.9.2 - 2019-02-19 - 865 commits by [Martin Grzeslowski](https: - [Enhancement] Add Shipkit [( - Add shipkit # 0.9.1 - 2019-02-19 - 864 commits by [Martin](https: - [Enhancement] Add Shipkit [( - Add shipkit
import Ember from "ember"; export default Ember.Route.extend({ model: function() { return this.store.query('answer', {correct: true}); } });
<?php namespace Sokil\Mongo\Validator; /** * Alphanumeric values validator * * @author Dmytro Sokil <dmytro.sokil@gmail.com> */ class <API key> extends \Sokil\Mongo\Validator { public function validateField(\Sokil\Mongo\Document $document, $fieldName, array $params) { if (!$document->get($fieldName)) { return; } if (preg_match('/^\w+$/', $document->get($fieldName))) { return; } if (!isset($params['message'])) { $params['message'] = 'Field "' . $fieldName . '" not alpha-numeric in model ' . get_called_class(); } $document->addError($fieldName, $this->getName(), $params['message']); } }
<?php /** * swPagesAdmin actions. * * @package soleoweb * @subpackage swPagesAdmin * @author Your name here * @version SVN: $Id: actions.class.php 8507 2008-04-17 17:32:20Z fabien $ */ class <API key> extends sfActions { public function executeIndex($request) { $this->sw_blog_tagList = new swBlogTagsDatagrid( $request->getParameter('filters', array()), array( 'page' => $request->getParameter('page'), 'per_page' => 10, ) ); } public function executeCreate() { $this->form = new swBlogTagForm(); $this->setTemplate('edit'); } public function executeEdit($request) { $this->form = $this->getswBlogTagForm($request->getParameter('id')); } public function executeUpdate($request) { $this->forward404Unless($request->isMethod('post')); $this->form = $this->getswBlogTagForm($request->getParameter('id')); $this->form->bind($request->getParameter('sw_blog_tag')); if ($this->form->isValid()) { $sw_blog_tag = $this->form->save(); $this->getUser()->setFlash('notice-ok', __('<API key>', null, 'swToolbox')); $this->redirect('swBlogTagsAdmin/edit?id='.$sw_blog_tag['id']); } $this->getUser()->setFlash('notice-error', __('<API key>', null, 'swToolbox')); $this->setTemplate('edit'); } public function executeDelete($request) { $this->forward404Unless($sw_blog_tag = $this->getswBlogTagById($request->getParameter('id'))); $sw_blog_tag->delete(); $this->getUser()->setFlash('notice-ok', __('<API key>', null, 'swToolbox')); $this->redirect('swBlogTagsAdmin/index'); } private function getswBlogTagTable() { return Doctrine::getTable('swBlogTag'); } private function getswBlogTagById($id) { return $this->getswBlogTagTable()->find($id); } private function getswBlogTagForm($id) { $sw_blog_tag = $this->getswBlogTagById($id); if ($sw_blog_tag instanceof swBlogTag) { return new swBlogTagForm($sw_blog_tag); } else { return new swBlogTagForm(); } } }
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif FOUNDATION_EXPORT double <API key>; FOUNDATION_EXPORT const unsigned char <API key>[];
//This file is automatically rebuilt by the Cesium build process. /*global define*/ define(function() { 'use strict'; \n\ const vec4 K_RGB2HSB = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n\ \n\ vec3 czm_RGBToHSB(vec3 rgb)\n\ {\n\ vec4 p = mix(vec4(rgb.bg, K_RGB2HSB.wz), vec4(rgb.gb, K_RGB2HSB.xy), step(rgb.b, rgb.g));\n\ vec4 q = mix(vec4(p.xyw, rgb.r), vec4(rgb.r, p.yzx), step(p.x, rgb.r));\n\ \n\ float d = q.x - min(q.w, q.y);\n\ return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + czm_epsilon7)), d / (q.x + czm_epsilon7), q.x);\n\ }\n\ "; });
# Intro This is the documentation of [Weave.jl](http://github.com/mpastell/weave.jl). Weave is a scientific report generator/literate programming tool for Julia. It resembles [Pweave](http://mpastell.com/pweave) and, Knitr and Sweave. **Current features** * Noweb, markdown or script syntax for input documents. * Execute code as terminal or "script" chunks. * Capture Gadfly, PyPlot and Winston figures. * Supports LaTex, Pandoc, Github markdown, MultiMarkdown, Asciidoc and reStructuredText output * Publish markdown directly to html and pdf using Pandoc. * Simple caching of results ![Weave code and output](http://mpastell.com/images/weave_demo.png) ## Contents @contents
/** * Demo App for TopcoatTouch */ $(document).ready(function() { <% if (kitchenSink) { if (mvc) { %> // Create the topcoatTouch object var tt = new TopcoatTouch({menu: [{id: 'help', name: 'Help'}, {id: 'info', name: 'Info'}, {id: 'about', name: 'About'}]}); tt.on(tt.EVENTS.MENU_ITEM_CLICKED, function(page, id) { if (id == 'help') { tt.goTo('help', 'slidedown', true); } else if (id == 'about') { tt.goTo('about', 'pop', true); } }); tt.createController('home'); tt.createController('about').addEvent('click', 'button', function() { tt.goBack(); }); tt.createController('info').addEvent('click', 'button', function() { tt.goBack(); }); tt.createController('help').addEvent('click', 'button', function() { tt.goBack(); }); tt.createController('buttonExample', { postrender: function($page) { // Show a message when anyone clicks on button of the test form... $page.find('.testForm').submit(function() { tt.showDialog('<h3>Button Clicked</h3>'); return false; }); } }); tt.createController('carouselExample', { postadd: function() { // When the page is loaded, run the following... // Setup iScroll.. this.carouselScroll = new IScroll('#carouselWrapper', { scrollX: true, scrollY: false, momentum: false, snap: true, snapSpeed: 400, keyBindings: true, indicators: { el: document.getElementById('carouselIndicator'), resize: false } }); }, pageend: function() { if (this.carouselScroll != null) { this.carouselScroll.destroy(); this.carouselScroll = null; } } }); tt.createController('checkRadioExample'); tt.createController('formExample'); tt.createController('galleryExample', { postrender: function($page) { $page.find('#changeButton').click(function() { createPlaceHolder($page, $('#gallery-picker').data('value')); }); createPlaceHolder($page, 'kittens'); } }); tt.createController('<API key>', { postadd: function() { // Show the loading message... $(document).on('click', '#showLoading', function() { tt.showLoading('10 seconds'); var count = 10; var interval = setInterval(function() { if (--count <= 0) { clearInterval(interval); tt.hideLoading(); } else { $('#<API key>').text(count + ' seconds'); } },1000); }); // Show the dialog... $(document).on('click', '#showDialog', function() { tt.showDialog('This is a dialog', 'Example Dialog', {OK: function() { console.log('OK Pressed') } , Cancel: function() { console.log('Cancel Pressed')}}); }); } }); // First page we go to home... This could be done in code by setting the class to 'page page-center', but here is how to do it in code... tt.goTo('home'); function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } // Create the placeholders in the gallery... function createPlaceHolder($page, type) { var placeHolders = { kittens : 'placekitten.com', bears: 'placebear.com', lorem: 'lorempixel.com', bacon: 'baconmockup.com', murray: 'www.fillmurray.com'}; var gallery = ''; for (var i = 0; i < getRandomInt(50,100); i++) { gallery += '<li class="photoClass" style="background:url(http://' + placeHolders[type] + '/' + getRandomInt(200,300) + '/' + getRandomInt(200,300) + ') 50% 50% no-repeat"></li>'; } $page.find('.photo-gallery').html(gallery); tt.refreshScroll(); // Refresh the scroller tt.scrollTo(0,0); // Move back to the top of the page... } <% // End If MVC KitchenSink } else { // Start SingleDocument KitchenSink %> // Create the topcoatTouch object var tt = new TopcoatTouch({menu: [{id: 'help', name: 'Help'}, {id: 'info', name: 'Info'}, {id: 'about', name: 'About'}]}); // First page we go to home... This could be done in code by setting the class to 'page page-center', but here is how to do it in code... tt.goTo('home'); var carouselScroll = null; tt.on(tt.EVENTS.MENU_ITEM_CLICKED, function(page, id) { if (id == 'help') { tt.goTo('help', 'slidedown', true); } else if (id == 'info') { tt.goTo('info', 'flip', true); } else if (id == 'about') { tt.goTo('about', 'pop', true); } }); tt.on('click', 'button', 'help about info', function() { tt.goBack(); }); // Show the loading message... $('#showLoading').click(function() { tt.showLoading('10 seconds'); var count = 10; var interval = setInterval(function() { if (--count <= 0) { clearInterval(interval); tt.hideLoading(); } else { $('#<API key>').text(count + ' seconds'); } },1000); }); // Show the dialog... $('#showDialog').click(function() { tt.showDialog('This is a dialog', 'Example Dialog', {OK: function() { console.log('OK Pressed') } , Cancel: function() { console.log('Cancel Pressed')}}); }); tt.on(tt.EVENTS.PAGE_START, 'carouselExample', function() { // When the page is loaded, run the following... // Setup iScroll.. carouselScroll = new IScroll('#carouselWrapper', { scrollX: true, scrollY: false, momentum: false, snap: true, snapSpeed: 400, keyBindings: true, indicators: { el: document.getElementById('carouselIndicator'), resize: false } }); }).on(tt.EVENTS.PAGE_END, 'carouselExample', function() { // When the page is unloaded, run the following... if (carouselScroll != null) { carouselScroll.destroy(); carouselScroll = null; } }); // Show a message when anyone clicks on button of the test form... $('.testForm').submit(function() { tt.showDialog('<h3>Button Clicked</h3>'); return false; }); function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } // Create the placeholders in the gallery... function createPlaceHolder(type) { var placeHolders = { kittens : 'placekitten.com', bears: 'placebear.com', lorem: 'lorempixel.com', bacon: 'baconmockup.com', murray: 'www.fillmurray.com'}; var gallery = ''; for (var i = 0; i < getRandomInt(50,100); i++) { gallery += '<li class="photoClass" style="background:url(http://' + placeHolders[type] + '/' + getRandomInt(200,300) + '/' + getRandomInt(200,300) + ') 50% 50% no-repeat"></li>'; } $('.photo-gallery').html(gallery); tt.refreshScroll(); // Refresh the scroller tt.scrollTo(0,0); // Move back to the top of the page... } $('#gallery-picker').change(function(e, id) { createPlaceHolder(id); }); createPlaceHolder('kittens'); <% } } else { %> // Create the topcoatTouch object var tt = new TopcoatTouch(); <% if (mvc) { %> tt.createController('home'); <% } else { %> // First page we go to home... This could be done in code by setting the class to 'page page-center', but here is how to do it in code... <% } %> tt.goTo('home'); <% } %> });
use std::borrow::{Borrow, Cow}; use std::ffi::{CStr, CString}; use std::fmt; use std::mem; use std::ops; use std::os::raw::c_char; use std::ptr; const STRING_SIZE: usize = 512; This is a C String abstractions that presents a CStr like interface for interop purposes but tries to be little nicer by avoiding heap allocations if the string is within the generous bounds (512 bytes) of the statically sized buffer. Strings over this limit will be heap allocated, but the interface outside of this abstraction remains the same. pub enum CFixedString { Local { s: [c_char; STRING_SIZE], len: usize, }, Heap { s: CString, len: usize, }, } impl CFixedString { Creates an empty CFixedString, this is intended to be used with write! or the `fmt::Write` trait pub fn new() -> Self { unsafe { CFixedString::Local { s: mem::uninitialized(), len: 0, } } } pub fn from_str<S: AsRef<str>>(s: S) -> Self { Self::from(s.as_ref()) } pub fn as_ptr(&self) -> *const c_char { match *self { CFixedString::Local { ref s, .. } => s.as_ptr(), CFixedString::Heap { ref s, .. } => s.as_ptr(), } } Returns true if the string has been heap allocated pub fn is_allocated(&self) -> bool { match *self { CFixedString::Local { .. } => false, _ => true, } } Converts a `CFixedString` into a `Cow<str>`. This function will calculate the length of this string (which normally requires a linear amount of work to be done) and then return the resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences with `U+FFFD REPLACEMENT CHARACTER`. If there are no invalid UTF-8 sequences, this will merely return a borrowed slice. pub fn to_string(&self) -> Cow<str> { String::from_utf8_lossy(&self.to_bytes()) } pub unsafe fn as_str(&self) -> &str { use std::slice; use std::str; match *self { CFixedString::Local { ref s, len } => { str::from_utf8_unchecked(slice::from_raw_parts(s.as_ptr() as *const u8, len)) } CFixedString::Heap { ref s, len } => { str::from_utf8_unchecked(slice::from_raw_parts(s.as_ptr() as *const u8, len)) } } } } impl<'a> From<&'a str> for CFixedString { fn from(s: &'a str) -> Self { use std::fmt::Write; let mut string = CFixedString::new(); string.write_str(s).unwrap(); string } } impl fmt::Write for CFixedString { fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { // use std::fmt::Write; unsafe { let cur_len = self.as_str().len(); match cur_len + s.len() { len if len <= STRING_SIZE - 1 => { match *self { CFixedString::Local { s: ref mut ls, len: ref mut lslen } => { let ptr = ls.as_mut_ptr() as *mut u8; ptr::copy(s.as_ptr(), ptr.offset(cur_len as isize), s.len()); *ptr.offset(len as isize) = 0; *lslen = len; } _ => unreachable!(), } } len => { let mut heapstring = String::with_capacity(len + 1); heapstring.write_str(self.as_str()).unwrap(); heapstring.write_str(s).unwrap(); *self = CFixedString::Heap { s: CString::new(heapstring).unwrap(), len: len, }; } } } // Yah....we should do error handling Ok(()) } } impl From<CFixedString> for String { fn from(s: CFixedString) -> Self { String::from_utf8_lossy(&s.to_bytes()).into_owned() } } impl ops::Deref for CFixedString { type Target = CStr; fn deref(&self) -> &CStr { use std::slice; match *self { CFixedString::Local { ref s, len } => unsafe { mem::transmute(slice::from_raw_parts(s.as_ptr(), len + 1)) }, CFixedString::Heap { ref s, .. } => s, } } } impl Borrow<CStr> for CFixedString { fn borrow(&self) -> &CStr { self } } impl AsRef<CStr> for CFixedString { fn as_ref(&self) -> &CStr { self } } impl Borrow<str> for CFixedString { fn borrow(&self) -> &str { unsafe { self.as_str() } } } impl AsRef<str> for CFixedString { fn as_ref(&self) -> &str { unsafe { self.as_str() } } } macro_rules! format_c { // This does not work on stable, to change the * to a + and // have this arm be used when there are no arguments :( // ($fmt:expr) => { // use std::fmt::Write; // let mut fixed = CFixedString::new(); // write!(&mut fixed, $fmt).unwrap(); // fixed ($fmt:expr, $($args:tt)*) => ({ use std::fmt::Write; let mut fixed = CFixedString::new(); write!(&mut fixed, $fmt, $($args)*).unwrap(); fixed }) } #[cfg(test)] mod tests { use super::*; use std::fmt::Write; fn gen_string(len: usize) -> String { let mut out = String::with_capacity(len); for _ in 0..len / 16 { out.write_str("zyxvutabcdef9876").unwrap(); } for i in 0..len % 16 { out.write_char((i as u8 + 'A' as u8) as char).unwrap(); } assert_eq!(out.len(), len); out } #[test] fn test_empty_handler() { let short_string = ""; let t = CFixedString::from_str(short_string); assert!(!t.is_allocated()); assert_eq!(&t.to_string(), short_string); } #[test] fn test_short_1() { let short_string = "test_local"; let t = CFixedString::from_str(short_string); assert!(!t.is_allocated()); assert_eq!(&t.to_string(), short_string); } #[test] fn test_short_2() { let short_string = "test_local stoheusthsotheost"; let t = CFixedString::from_str(short_string); assert!(!t.is_allocated()); assert_eq!(&t.to_string(), short_string); } #[test] fn test_511() { // this string (width 511) buffer should just fit let test_511_string = gen_string(511); let t = CFixedString::from_str(&test_511_string); assert!(!t.is_allocated()); assert_eq!(&t.to_string(), &test_511_string); } #[test] fn test_512() { // this string (width 512) buffer should not fit let test_512_string = gen_string(512); let t = CFixedString::from_str(&test_512_string); assert!(t.is_allocated()); assert_eq!(&t.to_string(), &test_512_string); } #[test] fn test_513() { // this string (width 513) buffer should not fit let test_513_string = gen_string(513); let t = CFixedString::from_str(&test_513_string); assert!(t.is_allocated()); assert_eq!(&t.to_string(), &test_513_string); } #[test] fn test_to_owned() { let short = "this is an amazing string"; let t = CFixedString::from_str(short); assert!(!t.is_allocated()); assert_eq!(&String::from(t), short); let long = gen_string(1025); let t = CFixedString::from_str(&long); assert!(t.is_allocated()); assert_eq!(&String::from(t), &long); } #[test] fn test_short_format() { let mut fixed = CFixedString::new(); write!(&mut fixed, "one_{}", 1).unwrap(); write!(&mut fixed, "_two_{}", "two").unwrap(); write!(&mut fixed, "_three_{}-{}-{:.3}", 23, "some string data", 56.789) .unwrap(); assert!(!fixed.is_allocated()); assert_eq!(&fixed.to_string(), "<API key> string data-56.789"); } #[test] fn test_long_format() { let mut fixed = CFixedString::new(); let mut string = String::new(); for i in 1..30 { let genned = gen_string(i * i); write!(&mut fixed, "{}_{}", i, genned).unwrap(); write!(&mut string, "{}_{}", i, genned).unwrap(); } assert!(fixed.is_allocated()); assert_eq!(&fixed.to_string(), &string); } // TODO: Reenable this test once the empty match arm is allowed // by the compiler // #[test] // fn <API key>() { // let empty = format_c!(""); // let no_args = format_c!("there are no format args"); // assert!(!empty.is_allocated()); // assert_eq!(&empty.to_string(), ""); // assert!(!no_args.is_allocated()); // assert_eq!(&no_args.to_string(), "there are no format args"); #[test] fn <API key>() { let first = 23; let second = " let third = u32::max_value(); let fourth = gen_string(512 - 45); let fixed = format_c!("{}_{}_0x{:x}_{}", first, second, third, fourth); let heaped = format!("{}_{}_0x{:x}_{}", first, second, third, fourth); assert!(!fixed.is_allocated()); assert_eq!(&fixed.to_string(), &heaped); } #[test] fn test_long_fmt_macro() { let first = ""; let second = gen_string(510); let third = 3; let fourth = gen_string(513 * 8); let fixed = format_c!("{}_{}{}{}", first, second, third, fourth); let heaped = format!("{}_{}{}{}", first, second, third, fourth); assert!(fixed.is_allocated()); assert_eq!(&fixed.to_string(), &heaped); } }