repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
rogeriopvl/pullhub
lib/cli.js
1598
const pullhub = require('../') const getUserRepos = require('./repos') const meta = require('../package.json') module.exports = function (args) { if (args.help) { showUsage() process.exit(0) } else if (args.version) { showVersion() process.exit(0) } else if (args.user) { const labels = args.labels getUserRepos(args.user) .then((repos) => { const parsedRepos = repos .filter((repo) => repo.owner.login === args.user) .map((repo) => repo.full_name) return pullhub(parsedRepos, labels) }) .then(outputFormatter) .catch(errorFormatter) } else if (args._.length < 1) { showUsage() process.exit(-1) } else { const repos = args._ const labels = args.labels pullhub(repos, labels) .then(outputFormatter) .catch(errorFormatter) } } function showUsage () { console.log(meta.name + ' <repos> [--labels] [--version] [--help]\n') console.log( '\t<repos> space separated repos in the user/repo format' ) console.log('\t--user <username> get all repos for given username') console.log('\t--labels comma separated labels to filter PRs by') console.log('\t--version show version info') console.log('\t--help show this usage info') } function showVersion () { console.log(meta.name + ' version ' + meta.version) } function outputFormatter (prs) { prs.map(pr => { console.log('#' + pr.number + ' ' + pr.title + ' | ' + pr.html_url) }) } function errorFormatter (err) { console.log('Error: ', err.message) }
mit
JasonPuglisi/snow-irc-bot
modules/yo.js
1614
module.exports = { sendYo: function(client, network, channel, command, trigger, nickname, target, args, prefix) { if (config.apis.yo !== undefined) { var yoName = config.apis.yo.name; var yoKey = config.apis.yo.key; } if (yoName !== undefined && yoKey !== undefined) { var targetUser = args[0]; if (targetUser.charAt(0) === '@') { var alias = targetUser.substring(1).toLowerCase(); if (save.profiles[client] !== undefined && save.profiles[client][alias] !== undefined) if (save.profiles[client][alias].yo !== undefined) targetUser = save.profiles[client][alias].yo; } if (targetUser.charAt(0) === '@') rpc.emit('call', client, 'privmsg', [target, prefix + 'The nickname \'' + targetUser.substring(1) + '\' is invalid']); else { var link = args[1]; var validLink = true; if (link !== undefined) { var regexp = /(http|https):\/\/.*\..*/; var validLink = regexp.test(link); } if (!validLink) link = undefined; var yoUrl = 'http://api.justyo.co/yo/'; request.post(yoUrl, { form: { api_token: yoKey, username: targetUser, link: link } }, function (error, response, body) { if (!error && response.statusCode === 200) rpc.emit('call', client, 'privmsg', [target, prefix + 'Sent a Yo to ' + targetUser.toUpperCase() + ' (Make sure they\'ve sent a Yo to ' + yoName.toUpperCase() + ' before)']); else rpc.emit('call', client, 'privmsg', [target, prefix + 'The Yo to ' + targetUser.toUpperCase() + ' is invalid (Wait a minute and try again)']); }); } } } };
mit
meowy/komrade
src/main/java/pounces/komrade/api/TelegramApi.java
6851
package pounces.komrade.api; import com.squareup.okhttp.RequestBody; import kotlin.Unit; import pounces.komrade.api.data.*; import retrofit.http.*; import rx.Observable; import java.util.List; public interface TelegramApi { @FormUrlEncoded @POST("getUpdates") Observable<Response<List<Update>>> getUpdates( @Field("offset") Integer offset, @Field("limit") Integer limit, @Field("timeout") Integer timeout ); @POST("setWebhook") Observable<Response<Boolean>> setWebhook( @Query("url") String url ); @Multipart @POST("setWebhook") Observable<Response<Boolean>> setWebhook( @Query("url") String url, @Part("certificate") String certificate ); @GET("getMe") Observable<Response<User>> apiGetMe(); @FormUrlEncoded @POST("sendMessage") Observable<Response<Message>> sendMessage( @Field("chat_id") String chatId, @Field("text") String text, @Field("parse_mode") String parseMode, @Field("disable_web_page_preview") Boolean disableWebPagePreview, @Field("reply_to_message_id") Integer replyToMessageId, @Field("reply_markup") ReplyMarkup replyMarkup ); @FormUrlEncoded @POST("forwardMessage") Observable<Response<Message>> forwardMessage( @Field("chat_id") String chatId, @Field("from_chat_id") String fromChatId, @Field("message_id") Integer messageId ); @FormUrlEncoded @POST("sendPhoto") Observable<Response<Message>> sendPhoto( @Field("chat_id") String chatId, @Field("photo") String photo, @Field("caption") String caption, @Field("reply_to_message_id") Integer replyToMessageId, @Field("reply_markup") ReplyMarkup replyMarkup ); @Multipart @POST("sendPhoto") Observable<Response<Message>> sendPhoto( @Field("chat_id") String chatId, @Part("photo") RequestBody photo, @Field("caption") String caption, @Field("reply_to_message_id") Integer replyToMessageId, @Field("reply_markup") ReplyMarkup replyMarkup ); @FormUrlEncoded @POST("sendAudio") Observable<Response<Message>> sendAudio( @Field("chat_id") String chatId, @Field("audio") String audio, @Field("duration") Integer duration, @Field("performer") String performer, @Field("title") String title, @Field("reply_to_message_id") Integer replyToMessageId, @Field("reply_markup") ReplyMarkup replyMarkup ); @Multipart @POST("sendAudio") Observable<Response<Message>> sendAudio( @Field("chat_id") String chatId, @Part("audio") RequestBody audio, @Field("duration") Integer duration, @Field("performer") String performer, @Field("title") String title, @Field("reply_to_message_id") Integer replyToMessageId, @Field("reply_markup") ReplyMarkup replyMarkup ); @FormUrlEncoded @POST("sendDocument") Observable<Response<Message>> sendDocument( @Field("chat_id") String chatId, @Field("document") String document, @Field("reply_to_message_id") Integer replyToMessageId, @Field("reply_markup") ReplyMarkup replyMarkup ); @Multipart @POST("sendDocument") Observable<Response<Message>> sendDocument( @Field("chat_id") String chatId, @Part("document") RequestBody document, @Field("reply_to_message_id") Integer replyToMessageId, @Field("reply_markup") ReplyMarkup replyMarkup ); @FormUrlEncoded @POST("sendSticker") Observable<Response<Message>> sendSticker( @Field("chat_id") String chatId, @Field("sticker") String sticker, @Field("reply_to_message_id") Integer replyToMessageId, @Field("reply_markup") ReplyMarkup replyMarkup ); @Multipart @POST("sendSticker") Observable<Response<Message>> sendSticker( @Field("chat_id") String chatId, @Part("sticker") RequestBody sticker, @Field("reply_to_message_id") Integer replyToMessageId, @Field("reply_markup") ReplyMarkup replyMarkup ); @FormUrlEncoded @POST("sendVideo") Observable<Response<Message>> sendVideo( @Field("chat_id") String chatId, @Field("video") String video, @Field("duration") Integer duration, @Field("caption") String caption, @Field("reply_to_message_id") Integer replyToMessageId, @Field("reply_markup") ReplyMarkup replyMarkup ); @Multipart @POST("sendVideo") Observable<Response<Message>> sendVideo( @Field("chat_id") String chatId, @Part("video") RequestBody video, @Field("duration") Integer duration, @Field("caption") String caption, @Field("reply_to_message_id") Integer replyToMessageId, @Field("reply_markup") ReplyMarkup replyMarkup ); @FormUrlEncoded @POST("sendVoice") Observable<Response<Message>> sendVoice( @Field("chat_id") String chatId, @Field("voice") String voice, @Field("duration") Integer duration, @Field("reply_to_message_id") Integer replyToMessageId, @Field("reply_markup") ReplyMarkup replyMarkup ); @Multipart @POST("sendVoice") Observable<Response<Message>> sendVoice( @Field("chat_id") String chatId, @Part("voice") RequestBody voice, @Field("duration") Integer duration, @Field("reply_to_message_id") Integer replyToMessageId, @Field("reply_markup") ReplyMarkup replyMarkup ); @FormUrlEncoded @POST("sendLocation") Observable<Response<Message>> sendLocation( @Field("chat_id") String chatId, @Field("latitude") Float latitude, @Field("longitude") Float longitude, @Field("reply_to_message_id") Integer replyToMessageId, @Field("reply_markup") ReplyMarkup replyMarkup ); @FormUrlEncoded @POST("sendChatAction") Observable<Response<Unit>> sendChatAction( @Field("chat_id") String chatId, @Field("action") String action ); @GET("getUserProfilePhotos") Observable<Response<UserProfilePhotos>> getUserProfilePhotos( @Query("user_id") Integer userId, @Query("offset") Integer offset, @Query("limit") Integer limit ); @GET("getFile") Observable<Response<File>> getFile( @Query("file_id") String fileId ); }
mit
lighter-cd/ezui_react_one
src/lib/components/form/Checkbox.js
1321
import React from 'react'; import injectSheet from 'react-jss'; import classNames from 'classnames'; const styles = theme => ({ checkBox: { appearance: 'none', position: 'relative', width: theme.checkBoxSizeOuter, height: theme.checkBoxSizeOuter, border: `${theme.checkBoxBorder} solid ${theme.checkBoxUncheckBorderColor}`, outline: 0, borderRadius: theme.checkBoxBorderRadiusOuter, boxSizing: 'border-box', backgroundColor: theme.checkBoxUncheckBgColor, '&:checked': { borderColor: theme.checkBoxCheckBorderColor, backgroundColor: theme.checkBoxCheckBgColor, '&:after': { content: '\\2714', // content: "\'X\'", fontSize: theme.checkBoxSize, position: 'absolute', top: 0, left: 0, width: theme.checkBoxSize, height: theme.checkBoxSize, lineHeight: theme.checkBoxSize, textAlign: 'center', color: theme.checkBoxColor, }, }, }, }); const CheckBox = (props) => { const { classes, className, sheet, theme, ...others } = props; const cls = classNames(classes.checkBox, { [className]: className, }); return ( <div> <input className={cls} type="checkBox" {...others} /> </div> ); }; export default injectSheet(styles)(CheckBox);
mit
noscosystems/osotto
application/models/db/ProductImages.php
7649
<?php // Add the namespace here: namespace application\models\db; // Along with the correct "use"'s/ use \Yii; use \CException; use \application\components\ActiveRecord; /** * This is the model class for table "product_images". * * The followings are the available columns in table 'product_images': * @property integer $id * @property integer $productId * @property string $url * * The followings are the available model relations: * @property Product $product */ class ProductImages extends ActiveRecord { public $errors = []; /** * @return string the associated database table name */ public function tableName() { return 'product_images'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('productId, url', 'required'), array('productId', 'numerical', 'integerOnly'=>true), array('url', 'length', 'max'=>100), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. array('id, productId, url', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'product' => array(self::BELONGS_TO, '\\application\\models\\db\\Product', 'productId'), ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'id' => 'ID', 'productId' => 'Product', 'url' => 'Url', ); } /** * Retrieves a list of models based on the current search/filter conditions. * * Typical usecase: * - Initialize the model fields with values from filter form. * - Execute this method to get CActiveDataProvider instance which will filter * models according to data in model fields. * - Pass data provider to CGridView, CListView or any similar widget. * * @return CActiveDataProvider the data provider that can return the models * based on the search/filter conditions. */ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id); $criteria->compare('productId',$this->productId); $criteria->compare('url',$this->url,true); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); } /** * Returns the static model of the specified AR class. * Please note that you should have this exact method in all your CActiveRecord descendants! * @param string $className active record class name. * @return ProductImages the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } public function image_upload(){ //2 097 152 = 2MegaBytes; $allowed_img_types = Array('image/jpeg','image/png'); //allowed image types, stored in an array //$mime_type = image_type_to_mime_type(exif_imagetype($_FILES['image1']['tmp_name'])); $size = []; if ($_FILES['image1']['size']>0 && $_FILES['image1']['type']!='' && $_FILES['image1']['tmp_name']!=''){ $size = getimagesize($_FILES['image1']['tmp_name']); if (!in_array($size['mime'],$allowed_img_types)){ // Checking wether the image is of the allowed image types array_push($this->errors, 'Image not of allowed type. Allowed image types are jpeg, bmp and png!'); } else if ($size[0]>2664 || $size[1]>1998 || $_FILES['image1']['size']>5242880){ $folder = Yii::getPathOfAlias('application.views.Uploads.images').'/'; $ext = strstr($_FILES['image1']['name'], '.'); $src=''; switch ($size['mime']){ case 'image/jpeg':{ $src = imagecreatefromjpeg($_FILES['image1']['tmp_name']); // Source image $sw = imagesx($src); // Source image Width $sh = imagesy($src); // Source image Height $dw = 2664; // Destination image Width $dh = 1998; // Destination image Height $wr = $sw / $dw; // Width Ratio (source:destination) $hr = $sh / $dh; // Height Ratio (source:destination) $cx = 0; // Crop X (source offset left) $cy = 0; // Crop Y (source offset top) if ($hr < $wr){ // Height is the limiting dimension;adjust Width $ow = $sw; // Old Source Width (temp) $sw = $dw * $hr; // New virtual Source Width $cx = ($ow - $sw) / 2; // Crops source width; focus remains centered } if ($wr < $hr){ // Width is the limiting dimension; adjust Height $oh = $sh; // Old Source Height (temp) $sh = $dh * $wr; // New virtual Source Height $cy = ($oh - $sh) / 2; // Crops source height; focus remains centered } // If the width ratio equals the height ratio, the dimensions stay the same. $dst = imagecreatetruecolor($dw, $dh); // Destination image imagecopyresampled($dst, $src, 0, 0, $cx, $cy, $dw, $dh, $sw, $sh); // Previews the resized image (not saved) $name = substr(md5(time()), 0, 7).$ext; $this->url = $folder.$name; imagejpeg($dst, $folder.$name , 95); return true; break; } case 'image/png':{ $src = imagecreatefrompng($_FILES['image1']['tmp_name']); // Source image $sw = imagesx($src); // Source image Width $sh = imagesy($src); // Source image Height $dw = 2664; // Destination image Width $dh = 1998; // Destination image Height $wr = $sw / $dw; // Width Ratio (source:destination) $hr = $sh / $dh; // Height Ratio (source:destination) $cx = 0; // Crop X (source offset left) $cy = 0; // Crop Y (source offset top) if ($hr < $wr){ // Height is the limiting dimension;adjust Width $ow = $sw; // Old Source Width (temp) $sw = $dw * $hr; // New virtual Source Width $cx = ($ow - $sw) / 2; // Crops source width; focus remains centered } if ($wr < $hr){ // Width is the limiting dimension; adjust Height $oh = $sh; // Old Source Height (temp) $sh = $dh * $wr; // New virtual Source Height $cy = ($oh - $sh) / 2; // Crops source height; focus remains centered } // If the width ratio equals the height ratio, the dimensions stay the same. $dst = imagecreatetruecolor($dw, $dh); // Destination image imagecopyresampled($dst, $src, 0, 0, $cx, $cy, $dw, $dh, $sw, $sh); // Previews the resized image (not saved) $name = substr(md5(time()), 0, 7).$ext; $this->url = $folder.$name; imagepng($dst, $folder.$name , 9); return true; break; } default: return false; } } else{ $ext = strstr($_FILES['image1']['name'], '.'); $_FILES['image1']['name'] = substr(md5(time()), 0, 7).$ext; //sets a name based on crrent time //then md5's it :D and get's a part of the string as the name $folder = Yii::getPathOfAlias('application.views.Uploads.images').'/'; $this->url = $folder.$_FILES['image1']['name']; if ( !move_uploaded_file($_FILES['image1']['tmp_name'], $this->url) ) array_push($this->errors, 'Unable to upload image, please try again!'); return true; } }else{ Yii::app()->user->setFlash('empty', 'Can not upload an empty image!'); } } public function unlinkPath(){ return (unlink($this->url))?true:false; } }
mit
barkerest/barkest_core
test/models/barkest_core/database_config_test.rb
735
module BarkestCore class DatabaseConfigTest < ActiveSupport::TestCase def setup @item = BarkestCore::DatabaseConfig.new('my_db', adapter: :sqlite3, database: 'mydb.sqlite', pool: 5, timeout: 5000) end test 'should be valid' do assert @item.valid? end test 'should require name' do assert_required @item, :name end test 'should require adapter' do assert_required @item, :adapter end test 'should require database' do assert_required @item, :database end test 'should require pool' do assert_required @item, :pool end test 'should require timeout' do assert_required @item, :timeout end end end
mit
paulgrayson/pivotal-reporting-kit
spec/lib/prkit/config_spec.rb
483
require 'spec_helper' require './lib/prkit' describe PRKit::Config do describe '#ensure_configured!' do it 'does not raise an error if api token configured' do expect do PRKit::Config.ensure_configured! end.to raise_exception end it 'raises an error if api token not configured' do expect do PRKit::Config.configure(api_token: "123434") PRKit::Config.ensure_configured! end.to_not raise_exception end end end
mit
nico01f/z-pec
ZimbraSelenium/src/java/com/zimbra/qa/selenium/projects/admin/tests/resources/GetResource.java
4017
package com.zimbra.qa.selenium.projects.admin.tests.resources; import java.util.List; import org.testng.annotations.Test; import com.zimbra.qa.selenium.framework.ui.Button; import com.zimbra.qa.selenium.framework.util.HarnessException; import com.zimbra.qa.selenium.framework.util.ZAssert; import com.zimbra.qa.selenium.framework.util.ZimbraAdminAccount; import com.zimbra.qa.selenium.projects.admin.core.AdminCommonTest; import com.zimbra.qa.selenium.projects.admin.items.AccountItem; import com.zimbra.qa.selenium.projects.admin.items.ResourceItem; public class GetResource extends AdminCommonTest { public GetResource() { logger.info("New "+ GetResource.class.getCanonicalName()); // All tests start at the "Resources" page super.startingPage = app.zPageManageResources; } /** * Testcase : Verify created resource is displayed in UI. * Steps : * 1. Create a resource of type Location using SOAP. * 2. Verify resource is present in the list. * @throws HarnessException */ @Test( description = "Verify created resource is present in the resource list view", groups = { "smoke" }) public void GetResource_01() throws HarnessException { // Create a new resource in the Admin Console using SOAP ResourceItem resource = new ResourceItem(); ZimbraAdminAccount.AdminConsoleAdmin().soapSend( "<CreateCalendarResourceRequest xmlns='urn:zimbraAdmin'>" + "<name>" + resource.getEmailAddress() + "</name>" + "<a n=\"displayName\">" + resource.getName() + "</a>" + "<a n=\"zimbraCalResType\">" + "Location" + "</a>" + "<password>test123</password>" + "</CreateCalendarResourceRequest>"); // Enter the search string to find the account app.zPageSearchResults.zAddSearchQuery(resource.getEmailAddress()); // Click search app.zPageSearchResults.zToolbarPressButton(Button.B_SEARCH); // Get the list of displayed accounts List<AccountItem> accounts = app.zPageSearchResults.zListGetAccounts(); ZAssert.assertNotNull(accounts, "Verify the resource list is returned"); AccountItem found = null; for (AccountItem a : accounts) { logger.info("Looking for account "+ resource.getEmailAddress() + " found: "+ a.getGEmailAddress()); if ( resource.getEmailAddress().equals(a.getGEmailAddress()) ) { found = a; break; } } ZAssert.assertNotNull(found, "Verify the account is found"); } /** * Testcase : Verify created resource is displayed in UI. * Steps : * 1. Create a resource of type Equipment using SOAP. * 2. Verify resource is present in the list. * @throws HarnessException */ @Test( description = "Verify created resource is present in the resource list view", groups = { "smoke" }) public void GetResource_02() throws HarnessException { // Create a new resource in the Admin Console using SOAP ResourceItem resource = new ResourceItem(); ZimbraAdminAccount.AdminConsoleAdmin().soapSend( "<CreateCalendarResourceRequest xmlns='urn:zimbraAdmin'>" + "<name>" + resource.getEmailAddress() + "</name>" + "<a n=\"displayName\">" + resource.getName() + "</a>" + "<a n=\"zimbraCalResType\">" + "Equipment" + "</a>" + "<password>test123</password>" + "</CreateCalendarResourceRequest>"); // Enter the search string to find the account app.zPageSearchResults.zAddSearchQuery(resource.getEmailAddress()); // Click search app.zPageSearchResults.zToolbarPressButton(Button.B_SEARCH); // Get the list of displayed accounts List<AccountItem> accounts = app.zPageSearchResults.zListGetAccounts(); ZAssert.assertNotNull(accounts, "Verify the resource list is returned"); AccountItem found = null; for (AccountItem a : accounts) { logger.info("Looking for account "+ resource.getEmailAddress() + " found: "+ a.getGEmailAddress()); if ( resource.getEmailAddress().equals(a.getGEmailAddress()) ) { found = a; break; } } ZAssert.assertNotNull(found, "Verify the account is found"); } }
mit
abjerner/Skybrud.Social.Slack
src/Skybrud.Social.Slack/Models/Users/SlackPresence.cs
2578
using Newtonsoft.Json.Linq; using Skybrud.Essentials.Json.Extensions; using Skybrud.Essentials.Time; using Skybrud.Social.Slack.Models.Common; namespace Skybrud.Social.Slack.Models.Users { /// <summary> /// Class representing the presence of a user. /// </summary> public class SlackPresence : SlackResult { #region Properties /// <summary> /// Gets the presence of the user. /// </summary> public SlackPresenceState Presence { get; } /// <summary> /// Gets whether the user is online. /// </summary> public SlackBoolean IsOnline { get; } /// <summary> /// Gets whether the user is auto away. /// </summary> public SlackBoolean IsAutoAway { get; } /// <summary> /// Gets whether the user is manual away. /// </summary> public SlackBoolean IsManualAway { get; } /// <summary> /// Gets the connection count. /// </summary> public int ConnectionCount { get; } /// <summary> /// Gets a timestamp with the last activity of the user. /// </summary> public EssentialsTime LastActivity { get; } #endregion #region Constructors /// <summary> /// Initializes a new instance based on the specified <paramref name="json"/> object. /// </summary> /// <param name="json">An instance of <see cref="JObject"/> representing the object.</param> protected SlackPresence(JObject json) : base(json) { Presence = json.GetEnum("presence", SlackPresenceState.Unspecified); IsOnline = json.GetString("online", ParseBoolean); IsAutoAway = json.GetString("auto_away", ParseBoolean); IsManualAway = json.GetString("manual_away", ParseBoolean); ConnectionCount = json.GetInt32("connection_count"); LastActivity = json.GetInt32("last_activity", x => x > 0 ? EssentialsTime.FromUnixTimestamp(x) : null); } #endregion #region Static methods /// <summary> /// Parses the specified <paramref name="json"/> object into an instance of <see cref="SlackPresence"/>. /// </summary> /// <param name="json">The instance of <see cref="JObject"/> to parse.</param> /// <returns>An instance of <see cref="SlackPresence"/>.</returns> public static SlackPresence Parse(JObject json) { return json == null ? null : new SlackPresence(json); } #endregion } }
mit
zaiyu-dev/club
test/controllers/site.test.js
1236
/*! * nodeclub - site controller test * Copyright(c) 2012 fengmk2 <fengmk2@gmail.com> * MIT Licensed */ /** * Module dependencies. */ var should = require('should'); var config = require('../../config'); var app = require('../../app'); var request = require('supertest')(app); describe('test/controllers/site.test.js', function () { it('should / 200', function (done) { request.get('/').end(function (err, res) { res.status.should.equal(200); res.text.should.containEql('积分榜'); res.text.should.containEql('友情社区'); done(err); }); }); it('should /?page=-1 200', function (done) { request.get('/?page=-1').end(function (err, res) { res.status.should.equal(200); res.text.should.containEql('积分榜'); res.text.should.containEql('友情社区'); done(err); }); }); it('should /sitemap.xml 200', function (done) { request.get('/sitemap.xml') .expect(200, function (err, res) { res.text.should.containEql('<url>'); done(err); }); }); // it('should /app/download', function (done) { // request.get('/app/download') // .expect(302, function (err, res) { // done(err); // }); // }); });
mit
wizzardo/http
src/main/java/com/wizzardo/http/EpollOutputStream.java
1795
package com.wizzardo.http; import com.wizzardo.epoll.ByteBufferProvider; import java.io.IOException; import java.io.OutputStream; /** * @author: wizzardo * Date: 9/3/14 */ public class EpollOutputStream extends OutputStream { private HttpConnection connection; private int offset; private byte[] buffer; protected volatile boolean waiting; public EpollOutputStream(HttpConnection connection) { this.connection = connection; buffer = new byte[16 * 1024]; offset = 0; } @Override public void write(byte[] b, int off, int len) throws IOException { flush(); waiting = true; connection.write(b, off, len, getByteBufferProvider()); waitFor(); } protected ByteBufferProvider getByteBufferProvider() { return (ByteBufferProvider) Thread.currentThread(); } @Override public void close() throws IOException { flush(); connection.close(); } @Override public void flush() throws IOException { if (offset > 0) { int length = offset; offset = 0; write(buffer, 0, length); } } @Override public void write(int b) throws IOException { if (offset >= buffer.length) flush(); buffer[offset++] = (byte) b; } protected void waitFor() { if (waiting) { synchronized (this) { while (waiting) { try { this.wait(); } catch (InterruptedException ignored) { } } } } } protected void wakeUp() { synchronized (this) { waiting = false; this.notifyAll(); } } }
mit
AaronLieberman/ArduinoTinkering
RobotControl/RobotControl/MainWindow.xaml.cs
636
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace RobotControl { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } }
mit
brunolauze/openpegasus-providers-old
src/Providers/UNIXProviders/DNSProtocolEndpoint/UNIX_DNSProtocolEndpoint_FREEBSD.hpp
12762
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// UNIX_DNSProtocolEndpoint::UNIX_DNSProtocolEndpoint(void) { } UNIX_DNSProtocolEndpoint::~UNIX_DNSProtocolEndpoint(void) { } Boolean UNIX_DNSProtocolEndpoint::getInstanceID(CIMProperty &p) const { p = CIMProperty(PROPERTY_INSTANCE_ID, getInstanceID()); return true; } String UNIX_DNSProtocolEndpoint::getInstanceID() const { return String (""); } Boolean UNIX_DNSProtocolEndpoint::getCaption(CIMProperty &p) const { p = CIMProperty(PROPERTY_CAPTION, getCaption()); return true; } String UNIX_DNSProtocolEndpoint::getCaption() const { return String (""); } Boolean UNIX_DNSProtocolEndpoint::getDescription(CIMProperty &p) const { p = CIMProperty(PROPERTY_DESCRIPTION, getDescription()); return true; } String UNIX_DNSProtocolEndpoint::getDescription() const { return String (""); } Boolean UNIX_DNSProtocolEndpoint::getElementName(CIMProperty &p) const { p = CIMProperty(PROPERTY_ELEMENT_NAME, getElementName()); return true; } String UNIX_DNSProtocolEndpoint::getElementName() const { return String("DNSProtocolEndpoint"); } Boolean UNIX_DNSProtocolEndpoint::getGeneration(CIMProperty &p) const { p = CIMProperty(PROPERTY_GENERATION, getGeneration()); return true; } Uint64 UNIX_DNSProtocolEndpoint::getGeneration() const { return Uint64(0); } Boolean UNIX_DNSProtocolEndpoint::getInstallDate(CIMProperty &p) const { p = CIMProperty(PROPERTY_INSTALL_DATE, getInstallDate()); return true; } CIMDateTime UNIX_DNSProtocolEndpoint::getInstallDate() const { struct tm* clock; // create a time structure time_t val = time(NULL); clock = gmtime(&(val)); // Get the last modified time and put it into the time structure return CIMDateTime( clock->tm_year + 1900, clock->tm_mon + 1, clock->tm_mday, clock->tm_hour, clock->tm_min, clock->tm_sec, 0,0, clock->tm_gmtoff); } Boolean UNIX_DNSProtocolEndpoint::getName(CIMProperty &p) const { p = CIMProperty(PROPERTY_NAME, getName()); return true; } String UNIX_DNSProtocolEndpoint::getName() const { return String (""); } Boolean UNIX_DNSProtocolEndpoint::getOperationalStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_OPERATIONAL_STATUS, getOperationalStatus()); return true; } Array<Uint16> UNIX_DNSProtocolEndpoint::getOperationalStatus() const { Array<Uint16> as; return as; } Boolean UNIX_DNSProtocolEndpoint::getStatusDescriptions(CIMProperty &p) const { p = CIMProperty(PROPERTY_STATUS_DESCRIPTIONS, getStatusDescriptions()); return true; } Array<String> UNIX_DNSProtocolEndpoint::getStatusDescriptions() const { Array<String> as; return as; } Boolean UNIX_DNSProtocolEndpoint::getStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_STATUS, getStatus()); return true; } String UNIX_DNSProtocolEndpoint::getStatus() const { return String(DEFAULT_STATUS); } Boolean UNIX_DNSProtocolEndpoint::getHealthState(CIMProperty &p) const { p = CIMProperty(PROPERTY_HEALTH_STATE, getHealthState()); return true; } Uint16 UNIX_DNSProtocolEndpoint::getHealthState() const { return Uint16(DEFAULT_HEALTH_STATE); } Boolean UNIX_DNSProtocolEndpoint::getCommunicationStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_COMMUNICATION_STATUS, getCommunicationStatus()); return true; } Uint16 UNIX_DNSProtocolEndpoint::getCommunicationStatus() const { return Uint16(0); } Boolean UNIX_DNSProtocolEndpoint::getDetailedStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_DETAILED_STATUS, getDetailedStatus()); return true; } Uint16 UNIX_DNSProtocolEndpoint::getDetailedStatus() const { return Uint16(0); } Boolean UNIX_DNSProtocolEndpoint::getOperatingStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_OPERATING_STATUS, getOperatingStatus()); return true; } Uint16 UNIX_DNSProtocolEndpoint::getOperatingStatus() const { return Uint16(DEFAULT_OPERATING_STATUS); } Boolean UNIX_DNSProtocolEndpoint::getPrimaryStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_PRIMARY_STATUS, getPrimaryStatus()); return true; } Uint16 UNIX_DNSProtocolEndpoint::getPrimaryStatus() const { return Uint16(DEFAULT_PRIMARY_STATUS); } Boolean UNIX_DNSProtocolEndpoint::getEnabledState(CIMProperty &p) const { p = CIMProperty(PROPERTY_ENABLED_STATE, getEnabledState()); return true; } Uint16 UNIX_DNSProtocolEndpoint::getEnabledState() const { return Uint16(DEFAULT_ENABLED_STATE); } Boolean UNIX_DNSProtocolEndpoint::getOtherEnabledState(CIMProperty &p) const { p = CIMProperty(PROPERTY_OTHER_ENABLED_STATE, getOtherEnabledState()); return true; } String UNIX_DNSProtocolEndpoint::getOtherEnabledState() const { return String (""); } Boolean UNIX_DNSProtocolEndpoint::getRequestedState(CIMProperty &p) const { p = CIMProperty(PROPERTY_REQUESTED_STATE, getRequestedState()); return true; } Uint16 UNIX_DNSProtocolEndpoint::getRequestedState() const { return Uint16(0); } Boolean UNIX_DNSProtocolEndpoint::getEnabledDefault(CIMProperty &p) const { p = CIMProperty(PROPERTY_ENABLED_DEFAULT, getEnabledDefault()); return true; } Uint16 UNIX_DNSProtocolEndpoint::getEnabledDefault() const { return Uint16(0); } Boolean UNIX_DNSProtocolEndpoint::getTimeOfLastStateChange(CIMProperty &p) const { p = CIMProperty(PROPERTY_TIME_OF_LAST_STATE_CHANGE, getTimeOfLastStateChange()); return true; } CIMDateTime UNIX_DNSProtocolEndpoint::getTimeOfLastStateChange() const { struct tm* clock; // create a time structure time_t val = time(NULL); clock = gmtime(&(val)); // Get the last modified time and put it into the time structure return CIMDateTime( clock->tm_year + 1900, clock->tm_mon + 1, clock->tm_mday, clock->tm_hour, clock->tm_min, clock->tm_sec, 0,0, clock->tm_gmtoff); } Boolean UNIX_DNSProtocolEndpoint::getAvailableRequestedStates(CIMProperty &p) const { p = CIMProperty(PROPERTY_AVAILABLE_REQUESTED_STATES, getAvailableRequestedStates()); return true; } Array<Uint16> UNIX_DNSProtocolEndpoint::getAvailableRequestedStates() const { Array<Uint16> as; return as; } Boolean UNIX_DNSProtocolEndpoint::getTransitioningToState(CIMProperty &p) const { p = CIMProperty(PROPERTY_TRANSITIONING_TO_STATE, getTransitioningToState()); return true; } Uint16 UNIX_DNSProtocolEndpoint::getTransitioningToState() const { return Uint16(0); } Boolean UNIX_DNSProtocolEndpoint::getSystemCreationClassName(CIMProperty &p) const { p = CIMProperty(PROPERTY_SYSTEM_CREATION_CLASS_NAME, getSystemCreationClassName()); return true; } String UNIX_DNSProtocolEndpoint::getSystemCreationClassName() const { return String("UNIX_ComputerSystem"); } Boolean UNIX_DNSProtocolEndpoint::getSystemName(CIMProperty &p) const { p = CIMProperty(PROPERTY_SYSTEM_NAME, getSystemName()); return true; } String UNIX_DNSProtocolEndpoint::getSystemName() const { return CIMHelper::HostName; } Boolean UNIX_DNSProtocolEndpoint::getCreationClassName(CIMProperty &p) const { p = CIMProperty(PROPERTY_CREATION_CLASS_NAME, getCreationClassName()); return true; } String UNIX_DNSProtocolEndpoint::getCreationClassName() const { return String("UNIX_DNSProtocolEndpoint"); } Boolean UNIX_DNSProtocolEndpoint::getNameFormat(CIMProperty &p) const { p = CIMProperty(PROPERTY_NAME_FORMAT, getNameFormat()); return true; } String UNIX_DNSProtocolEndpoint::getNameFormat() const { return String (""); } Boolean UNIX_DNSProtocolEndpoint::getProtocolType(CIMProperty &p) const { p = CIMProperty(PROPERTY_PROTOCOL_TYPE, getProtocolType()); return true; } Uint16 UNIX_DNSProtocolEndpoint::getProtocolType() const { return Uint16(0); } Boolean UNIX_DNSProtocolEndpoint::getProtocolIFType(CIMProperty &p) const { p = CIMProperty(PROPERTY_PROTOCOL_I_F_TYPE, getProtocolIFType()); return true; } Uint16 UNIX_DNSProtocolEndpoint::getProtocolIFType() const { return Uint16(0); } Boolean UNIX_DNSProtocolEndpoint::getOtherTypeDescription(CIMProperty &p) const { p = CIMProperty(PROPERTY_OTHER_TYPE_DESCRIPTION, getOtherTypeDescription()); return true; } String UNIX_DNSProtocolEndpoint::getOtherTypeDescription() const { return String (""); } Boolean UNIX_DNSProtocolEndpoint::getHostname(CIMProperty &p) const { p = CIMProperty(PROPERTY_HOSTNAME, getHostname()); return true; } String UNIX_DNSProtocolEndpoint::getHostname() const { return String (""); } Boolean UNIX_DNSProtocolEndpoint::getDHCPOptionsToUse(CIMProperty &p) const { p = CIMProperty(PROPERTY_D_H_C_P_OPTIONS_TO_USE, getDHCPOptionsToUse()); return true; } Array<Uint16> UNIX_DNSProtocolEndpoint::getDHCPOptionsToUse() const { Array<Uint16> as; return as; } Boolean UNIX_DNSProtocolEndpoint::getAppendParentSuffixes(CIMProperty &p) const { p = CIMProperty(PROPERTY_APPEND_PARENT_SUFFIXES, getAppendParentSuffixes()); return true; } Boolean UNIX_DNSProtocolEndpoint::getAppendParentSuffixes() const { return Boolean(false); } Boolean UNIX_DNSProtocolEndpoint::getAppendPrimarySuffixes(CIMProperty &p) const { p = CIMProperty(PROPERTY_APPEND_PRIMARY_SUFFIXES, getAppendPrimarySuffixes()); return true; } Boolean UNIX_DNSProtocolEndpoint::getAppendPrimarySuffixes() const { return Boolean(false); } Boolean UNIX_DNSProtocolEndpoint::getDNSSuffixesToAppend(CIMProperty &p) const { p = CIMProperty(PROPERTY_D_N_S_SUFFIXES_TO_APPEND, getDNSSuffixesToAppend()); return true; } Array<String> UNIX_DNSProtocolEndpoint::getDNSSuffixesToAppend() const { Array<String> as; return as; } Boolean UNIX_DNSProtocolEndpoint::getDomainName(CIMProperty &p) const { p = CIMProperty(PROPERTY_DOMAIN_NAME, getDomainName()); return true; } String UNIX_DNSProtocolEndpoint::getDomainName() const { return String (""); } Boolean UNIX_DNSProtocolEndpoint::getRegisterThisConnectionsAddress(CIMProperty &p) const { p = CIMProperty(PROPERTY_REGISTER_THIS_CONNECTIONS_ADDRESS, getRegisterThisConnectionsAddress()); return true; } Boolean UNIX_DNSProtocolEndpoint::getRegisterThisConnectionsAddress() const { return Boolean(false); } Boolean UNIX_DNSProtocolEndpoint::getUseSuffixWhenRegistering(CIMProperty &p) const { p = CIMProperty(PROPERTY_USE_SUFFIX_WHEN_REGISTERING, getUseSuffixWhenRegistering()); return true; } Boolean UNIX_DNSProtocolEndpoint::getUseSuffixWhenRegistering() const { return Boolean(false); } Boolean UNIX_DNSProtocolEndpoint::initialize() { return false; } Boolean UNIX_DNSProtocolEndpoint::load(int &pIndex) { return false; } Boolean UNIX_DNSProtocolEndpoint::finalize() { return false; } Boolean UNIX_DNSProtocolEndpoint::find(Array<CIMKeyBinding> &kbArray) { CIMKeyBinding kb; String systemCreationClassNameKey; String systemNameKey; String creationClassNameKey; String nameKey; for(Uint32 i = 0; i < kbArray.size(); i++) { kb = kbArray[i]; CIMName keyName = kb.getName(); if (keyName.equal(PROPERTY_SYSTEM_CREATION_CLASS_NAME)) systemCreationClassNameKey = kb.getValue(); else if (keyName.equal(PROPERTY_SYSTEM_NAME)) systemNameKey = kb.getValue(); else if (keyName.equal(PROPERTY_CREATION_CLASS_NAME)) creationClassNameKey = kb.getValue(); else if (keyName.equal(PROPERTY_NAME)) nameKey = kb.getValue(); } /* EXecute find with extracted keys */ return false; }
mit
sequin/sequin.claimsauthentication
src/Sequin.ClaimsAuthentication.Sample/Startup.cs
2241
namespace Sequin.ClaimsAuthentication.Sample { using System; using System.Collections.Generic; using System.Security.Claims; using Configuration; using global::Owin; using Microsoft.Owin; using Owin; using Owin.Middleware; using Pipeline; using Sequin.Owin; using Sequin.Owin.Extensions; using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>; public class Startup { public void Configuration(IAppBuilder app) { // Force sign-in with role app.Use(new Func<AppFunc, AppFunc>(next => (async env => { var context = new OwinContext(env); var claims = new List<Claim> { new Claim("role", "SomeRole") }; context.Request.User = new ClaimsPrincipal(new ClaimsIdentity(claims, "SomeAuthType")); await next.Invoke(env); }))); app.UseSequin(SequinOptions.Configure() .WithOwinDefaults() .WithPipeline(x => new OptOutCommandAuthorization(new OwinIdentityProvider()) { Next = x.IssueCommand }) .Build(), new [] { new ResponseMiddleware(typeof (UnauthorizedCommandResponseMiddleware)) }); } } }
mit
MortenHoustonLudvigsen/KarmaTestAdapter
TestProjects/KarmaRequireJasmine/ui/src/common/config.js
1167
var requireCommonConfig = { //requirejs.config({ baseUrl: 'ui/src', waitSeconds: 15, //Default: 7 urlArgs: 'r1', map: { '*': { //'css': '../bower_modules/require-css/css', 'jquery.ui.sortable': 'jquery-ui/sortable' //Specifically added due to knockout-sortable function needing that folder path } }, paths: { //Folder Paths: //jQuery 'jquery': '../bower_modules/jquery/dist/jquery', 'jquery-ui': '../bower_modules/jquery-ui/ui', //knockout 'knockout': '../bower_modules/knockout/dist/knockout', 'koAmdHelpers': '../bower_modules/knockout-amd-helpers/build/knockout-amd-helpers.min', 'q': '../bower_modules/q/q', 'text': '../bower_modules/requirejs-text/text', 'css': '../bower_modules/require-css/css', 'css-builder': '../bower_modules/require-css/css-builder', 'normalize': '../bower_modules/require-css/normalize', }, shim: { 'jquery': { exports: '$' }, 'jquery-ui': { deps: ['jquery'] }, 'q': { exports: 'Q' } } };
mit
ablaser/airtemplate
tests/CacheLoaderTest.php
4058
<?php use PHPUnit\Framework\TestCase; use org\bovigo\vfs\vfsStream; use org\bovigo\vfs\vfsStreamDirectory; use Gamez\Psr\Log\TestLoggerTrait; use Symfony\Component\Cache\Adapter\FilesystemAdapter; use AirTemplate\Loader\CacheLoader; if (!defined('n')) define('n', "\n"); if (!defined('br')) define('br', "<br>"); class CacheLoaderTest extends PHPUnit_Framework_TestCase { use TestLoggerTrait; protected $logger; private $templates = array( 'test' => '<b>{{var1}} {{var2|esc}}</b>', ); private $custom_delim = array( 'test' => '<b>[@var1] [@var2|esc]</b>' ); protected function setUp() { $this->root = vfsStream::setup('test'); $this->cache = vfsStream::url('test/cache'); $this->file_1 = vfsStream::url('test/test_1.tmpl'); file_put_contents($this->file_1, $this->templates['test']); $this->file_2 = vfsStream::url('test/test_2.tmpl'); file_put_contents($this->file_2, $this->custom_delim['test']); $this->logger = $this->getTestLogger(); } public function testCacheLoader() { // Act $cache = new FilesystemAdapter('', 60, $this->cache); $loader = new CacheLoader($cache, 60, $this->root->url()); // cache templates $parsed = $loader->load(['test' => 'test_1.tmpl']); // read cached templates $parsed2 = $loader->load(['test' => 'test_1.tmpl']); // Assert $this->assertInstanceOf(AirTemplate\Loader\CacheLoader::class, $loader); $this->assertTrue(is_array($parsed)); $this->assertTrue(is_array($parsed2)); $this->assertEquals($parsed, $parsed2); $this->assertEquals(1, count($parsed)); $this->assertEquals(5, count($parsed['test']['template'])); $this->assertEquals(2, count($parsed['test']['fields'])); $this->assertEquals('var2', $parsed['test']['fields'][3]); $this->assertEquals(0, count($parsed['test']['options']['var1'])); $this->assertEquals(1, count($parsed['test']['options']['var2'])); $this->assertEquals('esc', $parsed['test']['options']['var2'][0]); } public function testCacheLoaderCustomDelim() { $parseOptions = array( 'splitPattern' => '/(\[@)|\]/', 'fieldPrefix' => '[@' ); // Act $cache = new FilesystemAdapter('', 60, $this->cache); $cache->clear(); $loader = new CacheLoader($cache, 60, $this->root->url(), $parseOptions); // chache templates $parsed = $loader->load(['test' => 'test_2.tmpl']); // read cached templates $parsed2 = $loader->load(['test' => 'test_2.tmpl']); // Assert $this->assertTrue(is_array($parsed)); $this->assertTrue(is_array($parsed2)); $this->assertEquals($parsed, $parsed2); $this->assertEquals(1, count($parsed)); $this->assertEquals(5, count($parsed['test']['template'])); $this->assertEquals(2, count($parsed['test']['fields'])); $this->assertEquals('var2', $parsed['test']['fields'][3]); $this->assertEquals(0, count($parsed['test']['options']['var1'])); $this->assertEquals(1, count($parsed['test']['options']['var2'])); $this->assertEquals('esc', $parsed['test']['options']['var2'][0]); } public function testLogger() { // Act $cache = new FilesystemAdapter('', 60, $this->cache); $cache->clear(); $loader = new CacheLoader($cache, 60); $loader->setDir($this->root->url()); $loader->setLogger($this->logger); // chache templates $parsed = $loader->load(['test' => 'test_2.tmpl']); // read cached templates $parsed2 = $loader->load(['test' => 'test_2.tmpl']); // Assert $this->assertTrue(is_array($parsed)); $this->assertEquals(1, count($parsed)); $this->assertTrue($this->logger->hasRecord('Cache hit: ')); $this->assertTrue($this->logger->hasRecord('Cache save: ')); } }
mit
eturino/eapi
lib/eapi/definition_runners/runner.rb
2601
module Eapi module DefinitionRunners class Runner def self.validate_element_with(klass:, field:, validate_element_with:) klass.send :validates_each, field do |record, attr, value| if value.respond_to?(:each) value.each do |v| validate_element_with.call(record, attr, v) end end end end def self.validate_type(klass:, field:, type:) klass.send :validates_each, field do |record, attr, value| allow_raw = klass.property_allow_raw?(field) unless Eapi::TypeChecker.new(type, allow_raw).is_valid_type?(value) record.errors.add(attr, "must be a #{type}") end end end def self.validate_with(klass:, field:, validate_with:) klass.send :validates_each, field do |record, attr, value| validate_with.call(record, attr, value) end end def self.validate_element_type(klass:, field:, element_type:) klass.send :validates_each, field do |record, attr, value| allow_raw = klass.property_allow_raw?(field) if value.respond_to?(:each) value.each do |v| unless Eapi::TypeChecker.new(element_type, allow_raw).is_valid_type?(v) record.errors.add(attr, "element must be a #{element_type}") end end end end end def self.required(klass:, field:) klass.send :validates_presence_of, field end def self.unique(klass:, field:) klass.send :validates_each, field do |record, attr, value| if value.respond_to?(:group_by) grouped = value.group_by { |i| i } repeated_groups = grouped.select { |k, v| v.size > 1 } unless repeated_groups.empty? repeated = Hash[repeated_groups.map { |k, v| [k, v.size] }] record.errors.add(attr, "elements must be unique (repeated elements: #{repeated})") end end end end def self.allow_raw(klass:, field:, allow_raw:) if allow_raw klass.send :property_allow_raw, field else klass.send :property_disallow_raw, field end end def self.init(klass:, field:, type:) klass.send :define_init, field, type end def self.multiple_accessor(klass:, field:) klass.send :define_multiple_accessor, field end def self.multiple_clearer(klass:, field:) klass.send :define_multiple_clearer, field end end end end
mit
ikernits/jetty-sample
src/main/java/org/ikernits/sample/TestBean.java
654
package org.ikernits.sample; import org.apache.log4j.Logger; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Required; /** * Created by ikernits on 04/10/15. */ public class TestBean implements InitializingBean { protected String testProp; @Required public void setTestProp(String testProp) { this.testProp = testProp; } @Override public void afterPropertiesSet() throws Exception { System.out.println(this.getClass() + " initialized: " + testProp); } public String getTest() { return Thread.currentThread().getName(); } }
mit
xenophy/NextJS
lib/nx/database/MySQL/insert.js
992
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /*! * Next JS * Copyright (c)2011 Xenophy.CO.,LTD All rights Reserved. * http://www.xenophy.com */ // {{{ NX.database.MySQL.insert module.exports = function(table, o, fn) { var me = this, i, sql = ''; sql += 'INSERT INTO ' + table; sql += '('; i = 0; NX.iterate(o, function(key) { if(i > 0) { sql += ', '; } sql += key; i++; }); sql += ') VALUES ('; i = 0; NX.iterate(o, function(key, value) { if(i > 0) { sql += ', '; } if(NX.isString(value)) { value = '"' + value + '"'; } sql += value; i++; }); sql += ')'; // {{{ インサート me.driver.query(sql, function(err) { fn(err); }); // }}} }; // }}} /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * End: */
mit
alphabetcoinfund/alphabetcoinfund
src/qt/signverifymessagedialog.cpp
8734
#include "signverifymessagedialog.h" #include "ui_signverifymessagedialog.h" #include "addressbookpage.h" #include "base58.h" #include "guiutil.h" #include "init.h" #include "main.h" #include "optionsmodel.h" #include "walletmodel.h" #include "wallet.h" #include <string> #include <vector> #include <QClipboard> SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SignVerifyMessageDialog), model(0) { ui->setupUi(this); #if (QT_VERSION >= 0x040700) /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addressIn_SM->setPlaceholderText(tr("Enter a valid AlphabetCoinFund address")); ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature")); ui->addressIn_VM->setPlaceholderText(tr("Enter a valid AlphabetCoinFund address")); ui->signatureIn_VM->setPlaceholderText(tr("Enter AlphabetCoinFund signature")); #endif GUIUtil::setupAddressWidget(ui->addressIn_SM, this); GUIUtil::setupAddressWidget(ui->addressIn_VM, this); ui->addressIn_SM->installEventFilter(this); ui->messageIn_SM->installEventFilter(this); ui->signatureOut_SM->installEventFilter(this); ui->addressIn_VM->installEventFilter(this); ui->messageIn_VM->installEventFilter(this); ui->signatureIn_VM->installEventFilter(this); ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont()); ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont()); } SignVerifyMessageDialog::~SignVerifyMessageDialog() { delete ui; } void SignVerifyMessageDialog::setModel(WalletModel *model) { this->model = model; } void SignVerifyMessageDialog::setAddress_SM(QString address) { ui->addressIn_SM->setText(address); ui->messageIn_SM->setFocus(); } void SignVerifyMessageDialog::setAddress_VM(QString address) { ui->addressIn_VM->setText(address); ui->messageIn_VM->setFocus(); } void SignVerifyMessageDialog::showTab_SM(bool fShow) { ui->tabWidget->setCurrentIndex(0); if (fShow) this->show(); } void SignVerifyMessageDialog::showTab_VM(bool fShow) { ui->tabWidget->setCurrentIndex(1); if (fShow) this->show(); } void SignVerifyMessageDialog::on_addressBookButton_SM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_SM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_pasteButton_SM_clicked() { setAddress_SM(QApplication::clipboard()->text()); } void SignVerifyMessageDialog::on_signMessageButton_SM_clicked() { /* Clear old signature to ensure users don't get confused on error with an old signature displayed */ ui->signatureOut_SM->clear(); CBitcoinAddress addr(ui->addressIn_SM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if (!ctx.isValid()) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled.")); return; } CKey key; if (!pwalletMain->GetKey(keyID, key)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Private key for the entered address is not available.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_SM->document()->toPlainText().toStdString(); std::vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>")); return; } ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>")); ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size()))); } void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked() { QApplication::clipboard()->setText(ui->signatureOut_SM->text()); } void SignVerifyMessageDialog::on_clearButton_SM_clicked() { ui->addressIn_SM->clear(); ui->messageIn_SM->clear(); ui->signatureOut_SM->clear(); ui->statusLabel_SM->clear(); ui->addressIn_SM->setFocus(); } void SignVerifyMessageDialog::on_addressBookButton_VM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_VM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked() { CBitcoinAddress addr(ui->addressIn_VM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } bool fInvalid = false; std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid); if (fInvalid) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_VM->document()->toPlainText().toStdString(); CKey key; if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig)) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again.")); return; } if (!(CBitcoinAddress(key.GetPubKey().GetID()) == addr)) { ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>")); return; } ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>")); } void SignVerifyMessageDialog::on_clearButton_VM_clicked() { ui->addressIn_VM->clear(); ui->signatureIn_VM->clear(); ui->messageIn_VM->clear(); ui->statusLabel_VM->clear(); ui->addressIn_VM->setFocus(); } bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn) { if (ui->tabWidget->currentIndex() == 0) { /* Clear status message on focus change */ ui->statusLabel_SM->clear(); /* Select generated signature */ if (object == ui->signatureOut_SM) { ui->signatureOut_SM->selectAll(); return true; } } else if (ui->tabWidget->currentIndex() == 1) { /* Clear status message on focus change */ ui->statusLabel_VM->clear(); } } return QDialog::eventFilter(object, event); }
mit
maolion/Cox.js
src/modules/Net/Cookies.js
2687
/** * ${project} < ${FILE} > * * @DATE ${DATE} * @VERSION ${version} * @AUTHOR ${author} * * ---------------------------------------------------------------------------- * * ---------------------------------------------------------------------------- * 实现参考相关资料 * http://www.cnblogs.com/Darren_code/archive/2011/11/24/Cookie.html */ Define( "Cookies", function( require, Cookies ){ var DAY = 86400000, RE_SEPARATE = "; ", cache = {}, originCookies = "" ; function parse( cookie ){ cache = {}; XList.forEach( cookie.split( RE_SEPARATE ), function( cookie ){ cookie = cookie.split( "=" ); cache[ cookie[0] ] = unescape( cookie[1] ); } ); originCookies = document.cookie; return cache; } Cookies.get = function( key ){ if( document.cookie !== originCookies ){ parse( document.cookie ); } return cache[ key ]; }; function updateCookie( key, value, expires, path, domain ){ if( expires instanceof Date ){ expires = expires.toGMTString(); }else if( +expires && is( Number, +expires ) ){ var date = new Date; date.setTime( date.getTime() + (expires*DAY) ); expires = date.toGMTString(); }else{ expires = 0; } document.cookie = key + "=" + escape( value.toString() ) + "; path=" + path + "; domain=" + domain + "; expires=" + expires ; parse( document.cookie ); } Cookies.set = XFunction( String, Object, Optional( Number ), Optional( String ), Optional( String ), updateCookie ); Cookies.set.define( String, Object, Date, Optional( String ), Optional( String ), function( key, value, expires, path, domain ){ updateCookie( key, value, expires, path, domain ); } ); Cookies.set.define( String, Object, Cox.PlainObject, function( key, value, options ){ updateCookie( key, value, options.expires, options.path, options.domain || "" ); } ); Cookies.remove = XFunction( String, Optional( String ), Optional( String ), function( key, path, domain ){ updateCookie( key, "", new Date - 1, path, domain ); } ); } );
mit
ToJans/dypsok
Dypsok.Specs/CatalogSpecs.cs
3318
using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Shouldly; namespace Dypsok.Specs { [TestClass] public class CatalogSpecs { [TestInitialize] public void SetupProducts() { var catalogState = new CatalogState(); this.Queries = catalogState; this.Changes = catalogState; this.a_fake_ProductIdGenerator = new FakeProductIdGenerator(); this.Catalog = new Catalog(catalogState, catalogState, a_fake_ProductIdGenerator); } [TestMethod] public void should_contain_a_product_when_it_is_registered() { Catalog.RegisterProduct(a_product_id, some_fare_zones); Queries.IdExists(a_product_id).ShouldBe(true); } [TestMethod, ExpectedException(typeof(DuplicateProductIdException))] public void should_fail_when_registering_an_existing_id() { Changes.ProductRegistered(a_product_id); Catalog.RegisterProduct(a_product_id, some_fare_zones); } [TestMethod, ExpectedException(typeof(TooManyFareZonesException))] public void should_fail_when_registering_too_many_fare_zones() { Catalog.RegisterProduct(a_product_id, too_many_fare_zones); } [TestMethod] public void should_succeed_when_registering_a_product_with_an_empty_product_id() { Catalog.RegisterProduct(ProductId.Empty, some_fare_zones); Queries.IdExists(a_fake_ProductIdGenerator.IdToReturn); } [TestMethod, ExpectedException(typeof(NoMoreProductIdsAvailableException))] public void should_fail_when_registering_with_an_empty_product_id_and_new_product_ids_are_unavailable() { a_fake_ProductIdGenerator.NoMoreIdsAvailable = true; Catalog.RegisterProduct(ProductId.Empty, some_fare_zones); } [TestMethod] public void should_succeed_when_registering_a_subscription() { Catalog.RegisterSubscription(a_product_id, some_fare_zones, a_payment_schedule); Queries.IdExists(a_product_id).ShouldBe(true); } Catalog Catalog; IQueryACatalog Queries; IChangeACatalog Changes; ProductId a_product_id = new ProductId("products/1"); IEnumerable<FareZone> some_fare_zones = "AMS,NY,BRU".Split(',').Select(x => new FareZone(x)); IEnumerable<FareZone> too_many_fare_zones = "AMS,NY,BRU,RIO".Split(',').Select(x => new FareZone(x)); FakeProductIdGenerator a_fake_ProductIdGenerator; PaymentSchedule a_payment_schedule = new PaymentSchedule(); public class FakeProductIdGenerator : IGenerateProductIds { public ProductId IdToReturn = new ProductId("products/2"); public bool NoMoreIdsAvailable; public ProductId Next() { if (NoMoreIdsAvailable) throw new NoMoreProductIdsAvailableException(); else return IdToReturn; } } } }
mit
planetpowershell/planetpowershell
src/Firehose.Web/Authors/ChrisGardner.cs
1104
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class ChrisGardner : IAmAMicrosoftMVP { public string FirstName => "Chris"; public string LastName => "Gardner"; public string ShortBioOrTagLine => "General tech nerd spending too much time in PowerShell."; public string StateOrRegion => "Yorkshire, UK"; public string EmailAddress => "halbaradkenafin@outlook.com"; public string TwitterHandle => "halbaradkenafin"; public string GravatarHash => "0fb1b268e36194d977d56e778d5794a2"; public string GitHubHandle => "chrislgardner"; public GeoPosition Position => new GeoPosition(53.8008,-1.5491); public Uri WebSite => new Uri("https://chrislgardner.github.io"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://chrislgardner.github.io/feed.xml"); } } public string FeedLanguageCode => "en"; } }
mit
rgeraads/phpDocumentor2
src/phpDocumentor/Transformer/Transformer.php
9470
<?php declare(strict_types=1); /** * This file is part of phpDocumentor. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @link http://phpdoc.org */ namespace phpDocumentor\Transformer; use InvalidArgumentException; use League\Flysystem\Filesystem; use League\Flysystem\FilesystemInterface; use phpDocumentor\Compiler\CompilerPassInterface; use phpDocumentor\Descriptor\ProjectDescriptor; use phpDocumentor\Dsn; use phpDocumentor\Event\Dispatcher; use phpDocumentor\Parser\FlySystemFactory; use phpDocumentor\Transformer\Event\PostTransformationEvent; use phpDocumentor\Transformer\Event\PostTransformEvent; use phpDocumentor\Transformer\Event\PreTransformationEvent; use phpDocumentor\Transformer\Event\PreTransformEvent; use phpDocumentor\Transformer\Event\WriterInitializationEvent; use phpDocumentor\Transformer\Writer\Initializable; use phpDocumentor\Transformer\Writer\WriterAbstract; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; use RuntimeException; use function in_array; use function sprintf; /** * Core class responsible for transforming the cache file to a set of artifacts. */ class Transformer implements CompilerPassInterface { public const EVENT_PRE_TRANSFORMATION = 'transformer.transformation.pre'; public const EVENT_POST_TRANSFORMATION = 'transformer.transformation.post'; public const EVENT_PRE_INITIALIZATION = 'transformer.writer.initialization.pre'; public const EVENT_POST_INITIALIZATION = 'transformer.writer.initialization.post'; public const EVENT_PRE_TRANSFORM = 'transformer.transform.pre'; public const EVENT_POST_TRANSFORM = 'transformer.transform.post'; /** @var int represents the priority in the Compiler queue. */ public const COMPILER_PRIORITY = 5000; /** @var string|null $target Target location where to output the artifacts */ protected $target = null; /** @var FilesystemInterface|null $destination The destination filesystem to write to */ private $destination = null; /** @var Template\Collection $templates */ protected $templates; /** @var Writer\Collection $writers */ protected $writers; /** @var Transformation[] $transformations */ protected $transformations = []; /** @var LoggerInterface */ private $logger; /** @var FlySystemFactory */ private $flySystemFactory; /** * Wires the template collection and writer collection to this transformer. */ public function __construct( Template\Collection $templateCollection, Writer\Collection $writerCollection, LoggerInterface $logger, FlySystemFactory $flySystemFactory ) { $this->templates = $templateCollection; $this->writers = $writerCollection; $this->logger = $logger; $this->flySystemFactory = $flySystemFactory; } public function getDescription() : string { return 'Transform analyzed project into artifacts'; } /** * Sets the target location where to output the artifacts. * * @param string $target The target location where to output the artifacts. */ public function setTarget(string $target) : void { $this->target = $target; $this->destination = $this->flySystemFactory->create(Dsn::createFromString($target)); } /** * Returns the location where to store the artifacts. */ public function getTarget() : ?string { return $this->target; } public function destination() : FilesystemInterface { return $this->destination; } public function getTemplatesDirectory() : Filesystem { $dsnString = $this->getTemplates()->getTemplatesPath(); try { $filesystem = $this->flySystemFactory->create(Dsn::createFromString($dsnString)); } catch (InvalidArgumentException $e) { throw new RuntimeException( 'Unable to access the folder with the global templates, received DSN is: ' . $dsnString ); } return $filesystem; } /** * Returns the list of templates which are going to be adopted. */ public function getTemplates() : Template\Collection { return $this->templates; } /** * Transforms the given project into a series of artifacts as provided by the templates. */ public function execute(ProjectDescriptor $project) : void { /** @var PreTransformEvent $preTransformEvent */ $preTransformEvent = PreTransformEvent::createInstance($this); $preTransformEvent->setProject($project); Dispatcher::getInstance()->dispatch( $preTransformEvent, self::EVENT_PRE_TRANSFORM ); $transformations = $this->getTemplates()->getTransformations(); $this->initializeWriters($project, $transformations); $this->transformProject($project, $transformations); /** @var PostTransformEvent $postTransformEvent */ $postTransformEvent = PostTransformEvent::createInstance($this); $postTransformEvent->setProject($project); Dispatcher::getInstance()->dispatch($postTransformEvent, self::EVENT_POST_TRANSFORM); $this->logger->log(LogLevel::NOTICE, 'Finished transformation process'); } /** * Initializes all writers that are used during this transformation. * * @param Transformation[] $transformations */ private function initializeWriters(ProjectDescriptor $project, array $transformations) : void { $isInitialized = []; foreach ($transformations as $transformation) { $writerName = $transformation->getWriter(); if (in_array($writerName, $isInitialized, true)) { continue; } $isInitialized[] = $writerName; $writer = $this->writers[$writerName]; $this->initializeWriter($writer, $project); } } /** * Initializes the given writer using the provided project meta-data. * * This method wil call for the initialization of each writer that supports an initialization routine (as defined by * the `Initializable` interface). * * In addition to this, the following events emitted for each writer that is present in the collected list of * transformations, even those that do not implement the `Initializable` interface. * * Emitted events: * * - transformer.writer.initialization.pre, before the initialization of a single writer. * - transformer.writer.initialization.post, after the initialization of a single writer. * * @uses Dispatcher to emit the events surrounding an initialization. */ private function initializeWriter(WriterAbstract $writer, ProjectDescriptor $project) : void { /** @var WriterInitializationEvent $instance */ $instance = WriterInitializationEvent::createInstance($this); $event = $instance->setWriter($writer); Dispatcher::getInstance()->dispatch($event, self::EVENT_PRE_INITIALIZATION); if ($writer instanceof Initializable) { $writer->initialize($project); } Dispatcher::getInstance()->dispatch($event, self::EVENT_POST_INITIALIZATION); } /** * Applies all given transformations to the provided project. * * @param Transformation[] $transformations */ private function transformProject(ProjectDescriptor $project, array $transformations) : void { foreach ($transformations as $transformation) { $transformation->setTransformer($this); $this->applyTransformationToProject($transformation, $project); } } /** * Applies the given transformation to the provided project. * * This method will attempt to find an appropriate writer for the given transformation and invoke that with the * transformation and project so that an artifact can be generated that matches the intended transformation. * * In addition this method will emit the following events: * * - transformer.transformation.pre, before the project has been transformed with this transformation. * - transformer.transformation.post, after the project has been transformed with this transformation * * @uses Dispatcher to emit the events surrounding a transformation. */ private function applyTransformationToProject(Transformation $transformation, ProjectDescriptor $project) : void { $this->logger->log( LogLevel::NOTICE, sprintf( ' Writer %s %s on %s', $transformation->getWriter(), ($transformation->getQuery() ? ' using query "' . $transformation->getQuery() . '"' : ''), $transformation->getArtifact() ) ); $preTransformationEvent = PreTransformationEvent::create($this, $transformation); Dispatcher::getInstance()->dispatch($preTransformationEvent, self::EVENT_PRE_TRANSFORMATION); $writer = $this->writers[$transformation->getWriter()]; $writer->transform($project, $transformation); $postTransformationEvent = PostTransformationEvent::createInstance($this); Dispatcher::getInstance()->dispatch($postTransformationEvent, self::EVENT_POST_TRANSFORMATION); } }
mit
Timeswitch/rma-ss15
server/app/Database.js
610
/** * Created by michael on 26/07/15. */ var config = require('./config.js').database; var Knex = require('knex'); var Bookshelf = require('bookshelf'); var connection = Knex({ client: config.driver, connection: { host: config.server + ':' + config.port, user: config.user, password: config.password, database: config.database, filename: config.filename }, migrations: { tableName: 'knex_migrations', directory: 'app/Migrations' } }); var database = Bookshelf(connection); database.plugin('registry'); module.exports = database;
mit
barryhammen/hapi-swagger
bin/mock-routes.js
4705
var Joi = require('joi'); var handler = function(request, reply) { reply('ok'); }; module.exports = [{ method: 'GET', path: '/test', config: { handler: handler, validate: { query: { param1: Joi.string().required() } }, tags: ['admin', 'api'], description: 'Test GET', notes: 'test note' } }, { method: 'GET', path: '/another/test', config: { handler: handler, validate: { query: { param1: Joi.string().required() } }, tags: ['admin', 'api'] } }, { method: 'GET', path: '/zanother/test', config: { handler: handler, validate: { query: { param1: Joi.string().required() } }, tags: ['admin', 'api'] } }, { method: 'POST', path: '/test', config: { handler: handler, validate: { query: { param2: Joi.string().valid('first', 'last') } }, tags: ['admin', 'api'] } }, { method: 'DELETE', path: '/test', config: { handler: handler, validate: { query: { param2: Joi.string().valid('first', 'last') } }, tags: ['admin', 'api'] } }, { method: 'PUT', path: '/test', config: { handler: handler, validate: { query: { param2: Joi.string().valid('first', 'last') } }, tags: ['admin', 'api'] } }, { method: 'GET', path: '/notincluded', config: { handler: handler, plugins: { lout: false } } }, { method: 'GET', path: '/nested', config: { handler: handler, validate: { query: { param1: Joi.object({ nestedparam1: Joi.string().required() }) } } } }, { method: 'GET', path: '/rootobject', config: { handler: handler, validate: { query: Joi.object({ param1: Joi.string().required() }) } } }, { method: 'GET', path: '/path/{pparam}/test', config: { handler: handler, validate: { params: { pparam: Joi.string().required() } } } }, { method: 'GET', path: '/emptyobject', config: { handler: handler, validate: { query: { param1: Joi.object() } } } }, { method: 'GET', path: '/alternatives', config: { handler: handler, validate: { query: { param1: Joi.alternatives(Joi.number().required(), Joi.string().valid('first', 'last')) } } } }, { method: 'GET', path: '/novalidation', config: { handler: handler } }, { method: 'GET', path: '/withresponse', config: { handler: handler, response: { schema: { param1: Joi.string() } } } }, { method: 'GET', path: '/withhtmlnote', config: { handler: handler, validate: { query: { param1: Joi.string().notes('<span class="htmltypenote">HTML type note</span>') } }, notes: '<span class="htmlroutenote">HTML route note</span>' } }, { method: 'POST', path: '/denybody', config: { handler: handler, validate: { payload: false } } }, { method: 'POST', path: '/rootemptyobject', config: { handler: handler, validate: { payload: Joi.object() } } },{ method: 'GET', path: '/boom()', config: { tags: ['api'], notes: 'test', handler: handler, validate: { query: { param1: Joi.string() } }, } },{ method: 'GET', path: '/$code', config: { tags: ['api'], notes: 'test', handler: handler, validate: { query: { param1: Joi.string() } }, } },{ method: 'GET', path: '/test/{page}/route/{pagesize}', config: { description: 'Hapi-swagger bug test', tags: ['api', 'private'], validate: { params: { page: Joi.number().required(), pagesize: Joi.number().required() } }, auth: false, handler: function(request, reply) { var page = request.params.page; var pagesize = request.params.pagesize; //this will be the value of page reply(pagesize); } } },{ method: 'GET', path: '/models/{username}', config: { handler: function (request, reply) { reply("list of models") }, description: 'Get todo', notes: 'Returns a todo item by the id passed in the path', tags: ['api'], plugins: { 'hapi-swagger': { nickname: 'modelsapi' } }, validate: { params: { username: Joi.number() .required() .description('the id for the todo item') } } } }];
mit
BenVercammen/scorekeeper
IndividualService/test_domain.py
3596
# -*- coding: utf-8 -*- from unittest.case import TestCase from uuid import uuid4 from IndividualService.domain import Individual class TestIndividualDomain(TestCase): """ """ def testIndividualConstructor(self): """ Test the Individual constructor """ individual = Individual(uuid4(), 'Test', {'test': None, 'bool': True}) self.assertEqual('Test', individual.name) self.assertEqual(None, individual.properties['test']) self.assertEqual(True, individual.properties['bool']) self.assertEqual(1, len(individual.release())) def testIndividualConstructorWithoutId(self): """ Individual should not be created without ID. """ try: Individual(None, 'Test') self.fail('Individual should not be created without ID') except Exception as e: self.assertIn('require', str(e)) self.assertIn('UUID', str(e)) def testPropertyAdded(self): individual = Individual(uuid4(), 'Name', {}) self.assertEqual(1, len(individual.release()), 'IndividualCreated event expected') self.assertEqual(0, len(individual.properties)) individual.addProperty('Prop1', 'Value1') individual.addProperty('Prop2', 'Value2') self.assertEqual(2, len(individual.release()), '2 IndividualPropertyAdded events expected') self.assertEqual(2, len(individual.properties)) self.assertEqual('Value1', individual.properties['Prop1']) self.assertEqual('Value2', individual.properties['Prop2']) def testPropertyChanged(self): individual = Individual(uuid4(), 'Name', {'prop1': 'val1'}) self.assertEqual(1, len(individual.release()), 'IndividualCreated event expected') self.assertEqual(1, len(individual.properties)) individual.changeProperty('prop1', 'val2') self.assertEqual(1, len(individual.release()), '1 IndividualPropertyChanged event expected') self.assertEqual(1, len(individual.properties)) self.assertEqual('val2', individual.properties['prop1']) def testChangeUnknownProperty(self): individual = Individual(uuid4(), 'Name', {'prop1': 'val1'}) self.assertEqual(1, len(individual.release()), 'IndividualCreated event expected') self.assertEqual(1, len(individual.properties)) try: individual.changeProperty('prop2', 'val2') self.fail("Changing an unknown property should raise an exception!") except Exception as e: self.assertIn('prop2', str(e)) self.assertIn('cannot be set', str(e)) def testPropertyRemoved(self): individual = Individual(uuid4(), 'Name', {'prop1': 'val1'}) self.assertEqual(1, len(individual.release()), 'IndividualCreated event expected') self.assertEqual(1, len(individual.properties)) individual.removeProperty('prop1') self.assertEqual(1, len(individual.release()), '1 IndividualPropertyRemoved event expected') self.assertEqual(0, len(individual.properties)) def testRemoveUnknownProperty(self): individual = Individual(uuid4(), 'Name', {'prop1': 'val1'}) self.assertEqual(1, len(individual.release()), 'IndividualCreated event expected') self.assertEqual(1, len(individual.properties)) try: individual.removeProperty('prop2') self.fail("Removing an unknown property should raise an exception!") except Exception as e: self.assertIn('prop2', str(e)) self.assertIn('cannot be removed', str(e))
mit
lextel/evolution
fuel/app/classes/helper/coins.php
1396
<?php namespace Helper; class Coins { /** * 显示金钱 * * @param $points 点数 * @param $onlyGold 只显示元宝 * */ public static function showCoins($points, $onlyGold = true) { \Config::load('common'); $point = \Config::get('point'); $gold = floor($points/$point); $coins = ''; if(!empty($gold)) { $coins .= $gold . \Config::get('unit2'); } else { $coins .= '0' . \Config::get('unit2'); } if(!$onlyGold) { $silver = $points%$point; $coins .= $silver . \Config::get('unit4'); } return $coins; } /** * 显示金钱 * * @param $points 点数 * @param $onlyGold 只显示元宝 * */ public static function showIconCoins($points, $onlyGold = true) { \Config::load('common'); $point = \Config::get('point'); $gold = floor($points/$point); $coins = ''; if(!empty($gold)) { $coins .= \Config::get('unit') . $gold . \Config::get('unit2'); } else { $coins .= \Config::get('unit') . '0' . \Config::get('unit2'); } if(!$onlyGold) { $silver = $points%$point; $coins .= \Config::get('unit3') . $silver . \Config::get('unit4'); } return $coins; } }
mit
KingYSoft/foretch
angular-admin/src/admin/admin.component.ts
1232
import { Component, ViewContainerRef, Injector, OnInit, AfterViewInit } from '@angular/core'; import { AppConsts } from 'shared/AppConsts'; import { AppComponentBase } from 'shared/app-component-base'; import { SignalRHelper } from 'shared/helpers/SignalRHelper'; @Component({ templateUrl: './admin.component.html' }) export class AdminComponent extends AppComponentBase implements OnInit, AfterViewInit { private viewContainerRef: ViewContainerRef; constructor( injector: Injector ) { super(injector); } ngOnInit(): void { if (this.appSession.application.features['SignalR']) { SignalRHelper.initSignalR(); } abp.event.on('abp.notifications.received', userNotification => { abp.notifications.showUiNotifyForUserNotification(userNotification); // Desktop notification Push.create('AbpZeroTemplate', { body: userNotification.notification.data.message, icon: abp.appPath + 'assets/app-logo-small.png', timeout: 6000, onClick: function () { window.focus(); this.close(); } }); }); } ngAfterViewInit(): void { ($ as any).AdminBSB.activateAll(); ($ as any).AdminBSB.activateDemo(); } }
mit
goliatone/jii
src/model.js
32877
(function(namespace, exportName, moduleName, extendsModule){ var Module = namespace[moduleName]; ///////////////////////////////////////////////////////// //// HELPER METHODS. ///////////////////////////////////////////////////////// //Shim for Object.create var _createObject = Object.create || function(o) { var Func; Func = function() {}; Func.prototype = o; return new Func(); }; var _hasOwn = function(scope,prop){ return Object.prototype.hasOwnProperty.call(scope,prop); }; var _isEmpty = function(obj){ if(!obj) return true; if(typeof obj === "string"){ if(obj === '') return true; else return false; } if( obj.hasOwnProperty('length') && obj.length === 0) return true; var key; for(key in obj) { if (obj.hasOwnProperty(key)) return false; } return true; }; var _hasAttributes = function(scope){ var attrs = Array.prototype.slice(arguments,1); for(var prop in scope){ if(! _hasOwn(scope, prop)) return false; } return true; }; var _isFunc = function(obj){ return (typeof obj === 'function'); }; var _isArray = function(value) { return Object.prototype.toString.call(value) === '[object Array]'; }; var _getKeys = function(o){ if (typeof o !== 'object') return null; var ret=[],p; for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p); return ret; }; var _result = function(obj, property){ if(obj == null) return null; var value = obj[property]; return _isFunc(value) ? value.call(obj) : value; }; var _capitalize =function(str){ return str.charAt(0).toUpperCase() + str.slice(1); }; var _map = function(fun /*, thisp*/){ var len = this.length; if (typeof fun !== "function") throw new TypeError(); var res = new Array(len); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) res[i] = fun.call(thisp, this[i], i, this); } return res; }; var _merge = function(a, b){ for(var p in b){ if(b.hasOwnProperty(p)) a[p] = b[p]; } return a; }; var _intersect = function(a,b){ a.filter(function(n){ return (b.indexOf(n) !== -1);}); }; var _firstToLowerCase = function(str){ return str.charAt(0).toLowerCase() + str.slice(1); }; ///////////////////////////////////////////////////// //// MODEL ///////////////////////////////////////////////////// /** * Model is a glorified Object with pubsub and an interface * to deal with attributes, validation * * TODO: Deal with attributes and relations. What if an * attribute is an objecty? right now, we loose it. * TODO: Hold fields in its own object, instead of assigning * them to the model instance. So they can be accessed * with modelInstance.fields() */ var Model = Module( exportName, 'BaseModule' ).extend({ records:{}, grecords:{}, attributes:[], extended:function(Self){ Self.dispacher = new Self(); Self.reset(); }, configure: function(config){ //here, we should parse config to get //meta, and THEN, do a merge if(_hasOwn(config, 'attributes')) this.extend(config.attributes, this.attributes); //$.extend(true,this.attributes,config.attributes); // this.attributes = config.attributes; // this.unbind(); //TODO: list configurable props and merge //only those from config.(?) this.fk = 'id'; }, clonesArray:function(array){ var value; var i = 0, l = array.length; var result = []; for(; i < l; i++){ value = array[i]; result.push(value.clone()); } return result; }, makeGid:function(){ return 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8); return v.toString(16); }).toUpperCase(); }, isGid:function(gid){ if(_isEmpty(gid)) return false; // if(typeof gid === obj) gid = gid.replace(/[A-Z\d]/g,function(){return 0;}); return (gid === '00000000-0000-0000-0000-000000000000'); }, reset:function(options){ this.records = {}; this.grecords = {}; this.attributes = []; }, /** * Add a model or a list of models to the collection. * * @access public * @param record * @param options * @return */ //TODO: HOW DO WE WANT TO HANDLE CLONES AND STORING BY REF?! add:function(record,options){ options = options || {silent:true}; var records = _isArray(record) ? record.slice() : [record]; var i = 0, l = records.length, local; for(;i < l; i++){ records[i] = this._prepareModel(records[i],options); } i = 0; l = records.length; for(;i < l; i++){ record = records[i]; local = this.has(record) && this.get(record); if(local){ //Do we merge both records?! if(options.merge && local) local.load(record); //we already have it, remove it records.splice(i,1); //update index, ensure we loop all! --i; --l; //and move on continue; } //subscribe to updates record.subscribe('all', this._handleModel, this, options); //Nofity we are adding the record. // this.dispacher.publish('added', record); //save a ref. to the record. this.grecords[record.gid] = record; //save a ref to the record. TODO:Should we clone!? //TODO: use this.fk if(record.has('id')) this.records[record.id] = record;//.clone(); //TODO: make id a method id() => return this[this.fk]; } //should we register for all updates on model?! //that way we can track changes, i.e add it to the dirty //list, if id changes, update return record; }, _prepareModel: function(attrs, options) { if (attrs instanceof Model) { //if (!attrs.collection) attrs.collection = this; return attrs; } options = options || {}; //options.fk = this.fk; //options.collection = this; var model = new this.prototype.__class__(attrs, options); //if (!model._validate(model.attributes, options)) return false; return model; }, get:function(id){ id = this.ensureId(id); if(!this.has(id)) return null; var r; if((r = this.records[id])) return r; //at this point we know that it has to be a ghost one return this.grecords[id]; }, ensureId:function(id, onlyId){ if(typeof id === 'object'){ if(_hasOwn(id,'id')) id = id.id; else if(_hasOwn(id,'gid') && !onlyId) id = id.gid; else return null; } return id; }, has:function(id){ if(!id) return false; id = this.ensureId(id); //how do we want to handle errors!? return _hasOwn(this.records,id) || _hasOwn(this.grecords,id); }, count:function(gRecords){ var t = 0, p,rec; rec = gRecords ? this.grecords : this.records; for(p in rec){ if(rec.hasOwnProperty(p)) t++; } return t; }, remove:function(id){ //TODO: Do we want to remove by gid?! most likely if(!this.has(id)) return null; var r = this.get(id); //remove all listeners r.unsubscribe('all',this.proxy(this._handleModel)); //Nofity we are removing the record. // this.dispacher.publish('removed', r); //do remove delete this.records[r.id]; delete this.grecords[r.gid]; return r; }, _handleModel:function(topic,options){ switch(topic){ case 'create': //this.add(this); break; case 'remove': break; case 'destroy': this.remove(options.target.id); break; } }, //////////////////////////////////////////////////////////// //// ArrayCollection Stuff. //////////////////////////////////////////////////////////// each:function(callback, context){ var r = this.all(); var results = []; var key, value, i = 0; for(key in r){ if(r.hasOwnProperty(key)){ value = r[key]; context = context || value; results.push(callback.call(context, value, i++, r)); } } return results; }, all:function(){ return this.clonesArray(this.recordsValues()); }, first:function(){ var record = this.recordsValues()[0]; //void 0, evaluates to undefined; return record ? record.clone() : 0; }, last:function(){ var values = this.recordsValues(); var record = values[values.length - 1]; return record ? record.clone() : void 0; }, /*count:function(){ return this.recordsValues().length; },*/ //////////// toJSON:function(){ return this.recordsValues(); }, fromJSON:function(objects){ if(!objects) return null; console.log('FROM FUCKING JSON'); if(typeof objects === 'string'){ console.log(objects); try{ objects = JSON.parse(objects); } catch(e) { console.log('Error! ',objects); } } if(_isArray(objects)){ var result = []; var i = 0, l = objects.length; var value; for(; i < l; i++){ value = objects[i]; result.push(new this(value, {skipSync:true})); } return result; } else { return [new this(objects, {skipSync:true})]; } }, fromForm:function(selector){ var model = new this(); return model.fromForm(selector); }, recordsValues:function(){ var key, value; var result = []; var r = this.records; for(key in r){ if(r.hasOwnProperty(key)){ value = r[key]; result.push(value); } } return result; } }).include({ //TODO: Do we want this on the reset method, what about inheritance. errors:{}, validators:{}, scenario:null, init:function(attrs, options){ this.modelName = _capitalize(this.__name__); this.modelId = _firstToLowerCase(this.__name__); this.clearErrors(); if(attrs) this.load(attrs,options); console.log('CREATE MODEL, ',this.gid); this.gid = this.ctor.makeGid(); // if(attrs && attrs.hasOwnProperty('gid')) // this.gid = attrs.gid; //We save a copy in static model. this.ctor.add(this); }, /*log:function(){ if(this.debug === false || !window.console) return; window.console.log.apply(window.console, arguments); },*/ //////////////////////////////////////////////////////// //// VALIDATION: Todo, move to it's own module. //////////////////////////////////////////////////////// validate:function(attributes, options){ options = options || {}; if(options.clearErrors) this.clearErrors(); var validators, validator, prop; validators = this.getValidators(); //if(this.beforeValidate()) return false; for(prop in validators){ if(validators.hasOwnProperty(prop)){ validator = validators[prop]; //TODO: do we want to register objects or methods? //validator.call(this, attributes); validator.validate(this, attributes); } } //this.afterValidate(); return !this.hasErrors(); }, getValidators:function(attribute){ //ensure we have validators. this.getValidatorList(); var validators = []; var validator; var scenario = this.getScenario(); for(validator in validators){ if(validators.hasOwnProperty(validator)){ validator = validators[validator]; if(validator.applyTo(scenario)){ if(!attribute || validator.validatesAttribute(attribute)) validators.push(validator); } } } return validators; }, getValidatorList:function(){ return (this.validators || (this.validators = this.createValidators())); }, createValidators:function(){ var validators = {}; for( var rule in this.rules){ if(this.rules.hasOwnProperty(rule)){ rule = this.rules[rule]; if(_hasAttributes(rule, 'name', 'attribute')){ //TODO:Figure out how do we store them, and how we access. validators[rule.attribute] = rule; } } } return validators; }, addError:function(attribute, error){ var errors = this.errors[attribute] || (this.errors[attribute] = []); errors.push(error); }, addErrors:function(errors){ var error, attribute; for( attribute in errors){ if(errors.hasOwnProperty(attribute)){ error = errors[attribute]; if(_isArray(error)) this.addErrors(error); else this.addError(attribute, error); } } }, clearErrors:function(attr){ if(attr && attr in this.errors) delete this.errors[attr]; else this.errors = {}; }, hasError:function(attribute){ return this.errors.hasOwnProperty(attribute); }, hasErrors:function(attribute){ if(attribute) return this.hasError(attribute); else return _isEmpty(this.errors); }, getErrors:function(attribute){ var errors; if(attribute) errors = (this.errors[attribute] || []).concat(); else errors = _merge({},this.errors); return errors; }, getError:function(attribute){ return this.hasError(attribute) ? this.errors[attribute][0] : void(0); }, //////////////////////////////////////////////////////// /** * It will load all values provied in attr object * into the record. * */ load:function(attr){ var key, value, prop; // var attributes = this.getAttributeNames(); //we need to filter the stuff we load (?) //TODO: Should we validate?! for(key in attr){ if(attr.hasOwnProperty(key)){ // console.log('We go for key: ', key); value = attr[key]; if(typeof value === 'object') this.load(value); else if(_isFunc(this[key])) this[key](value); else this[key] = value; } } return this; }, /** * Repopulates the record with the latest data. * It's an asynchronous mehtod. * * */ restore:function(){ //Not really, we still want to get original src. // if(this.isNewRecord()) return this; //TODO: load clean.attributes instead. //We need to use gid, since id might not be set. var original = this.constructor.findByGid(this.gid); this.load(original.getAttributes()); //If we return this, wouldn't it be the same? return original; }, get:function(attribute){ return this[attribute]; }, set:function(attribute, value, options){ var old = this[attribute]; this[attribute] = value; //TODO: We should store changes and mark fields //as dirty. (?) //TODO: We should handle validation here as well. if(!options || !options.silent ) this.publish('update.'+attribute,{old:old, value:value},options); return this; }, has:function(attribute){ return this.hasOwnProperty(attribute); }, setScenario:function(scenario){ if(!scenario || scenario === this.scenario) return; this.scenario = scenario; return this; }, getScenario:function(){ return this.scenario; }, duplicate:function(asNewRecord){ var result = new this.constructor(this.getAttributes()); if(asNewRecord === false) result.gid = this.gid; else delete result.id; return result; }, clone:function(){ return _createObject(this); }, hasAttribute:function(attribute){ return this.getAttributeNames().indexOf(attribute) !== -1; }, getAttributeNames:function(){ return this.constructor.attributes.concat(); //var attrs = this.constructor.attributes; //return _getKeys(attrs); }, getAttributes:function(names){ var name, attrs = this.getAttributeNames(); if(names && _isArray(names)) attrs = _intersect(attrs,names); var i = 0, l = attrs.length, res = {}; for(; i < l; i++ ){ name = attrs[i]; if( name in this) res[name] = _result(this, name); } if(this.id) res.id = this.id; return res; }, //TODO: Check that name is in accepted attrs. updateAttribute:function(name, value, options){ var old = this[name]; this[name] = value; //TODO: update:name to follow conventions. this.publish('update.'+name,{old:old, value:value},options); return this.save(options); }, updateAttributes:function(values, options){ //TODO: Should we only do this if we have subscribers? //if(this.willPublish('updateAttributes')) var old = this.getAttributes(); this.load(values); //TODO: update:all?attributes this.publish('update.attributes',{old:old, values:values},options); return this.save(options); }, isNewRecord:function(){ return ! this.isRecord(); }, isEqual:function(record){ if(!record) return false; if(record.constructor !== this.constructor) return false; if(record.gid !== this.gid) return false; if(record.id !== this.id) return false; return true; }, isValid:function(){ return this.validate(); }, isInvalid:function(){ return ! this.validate(); }, isRecord:function(){ //TODO: this.collection.has(this.id); return this.id && this.id in this.constructor.records; }, toString:function(){ return '['+this.__name__+' => '+" ]"; //return "<" + this.constructor.className + " (" + (JSON.stringify(this)) + ")>"; }, toJSONString:function(){ return JSON.stringify(this.getAttributes()); }, toJSON:function(){ return this.getAttributes(); }, fromJSON:function(records){ return this.load(records); } }); // Model.include(namespace.PubSub.mixins['pubsub']); //TODO: Parse attributes, we want to have stuff //like attribute type, and validation info. Model.prototype.metadata = function(meta){ }; /** * * */ Model.prototype.fromForm = function(selector, keyModifier){ var inputs = $(selector).serializeArray(); var i = 0, l = inputs.length; var name, key, result = {}; keyModifier = keyModifier || new RegExp("(^"+this.modelName+"\\[)(\\w+)(\\]$)"); for(; i < l; i++){ key = inputs[i]; name = key.name.replace(keyModifier, "$2"); result[key.name] = key.value; } this.load(result); return this; }; ///////////////////////////////////////////////////// //// ACTIVE RECORD //// relational: https://github.com/lyonbros/composer.js/blob/master/composer.relational.js ///////////////////////////////////////////////////// var ActiveRecord = Module('ActiveRecord', Model).extend({ extended:function(){ //This works OK, it gets called just after it //has been extended. this.stores = []; }, //////////////////////////////////////////////////////////////////////// //////// PERHAPS MOVE THIS INTO A STORE IMP.? //////// WE CAN HAVE LOCALSTORE, RESTSTORE, ETC... //////////////////////////////////////////////////////////////////////// ensureDefaultOptions:function(options){ options = options || {}; if(!_isFunc(options, 'onError')) options.onError = this.proxy(this.onError); return options; }, onError:function(model, errorThrown, xhr, statusText){ this.log(this.__name__+' error: '+errorThrown, ' status ', statusText); }, getService:function(){ if(!this._service) //TODO: Global dependency! this.setService(new jii.REST()); return this._service; }, setService:function(service){ // // var args = Array.prototype.slice.call(arguments,1); // args.unshift(this); // this._service = factory.apply(factory, args); this._service = service; // this._service.subscribe() return this; }, service:function(action, model, options){ options = this.ensureDefaultOptions(options); this.getService().service(action, model, options); }, update:function(id, attributes, options){ var record = this.find(id); if(record) record.updateAttributes(attributes, options); else return null; return record; }, create:function(attributes, options){ options = this.ensureDefaultOptions(options); var record = new this(attributes); //Perhaps, instead of save, we need to load //the attributes, we dont want to trigger an //update/create here! options.skipSync = true; return record.save(options); }, load:function(attributes){ return new this(attributes); }, destroy:function(id, options){ var record = this.find(id); if(record) record.destroy(options); return record; }, change:function(){ /* if(_isFunc(callbackOrParams)){ // return this.bind('change', callbackOrParams); } else { // return this.publish('change', callbackOrParams); }*/ }, fetch:function(id, options){ //TODO: Here, we can have: // id => fk, options REST options // id => object being SEARCH query. options = this.ensureDefaultOptions(options); var model = new this(); if(id) model.id = id; var self = this; options.onSuccess = function(data){ console.log('on fetch success ',arguments); //we should ensure that data is in the right //format. //if(typeof data === 'object') //self.load(data); self.fromJSON(data); }; this.service('read', model, options); }, find:function(idOrGid){ var record = this.records[idOrGid]; if(!record && this.isGid(idOrGid)) return this.findByGid(idOrGid); if(!record) return false; return record.clone(); }, findByPk:function(id){ var record = this.records[id]; if(!record) return false; return record.clone(); }, findByGid:function(gid){ var record = this.grecords[gid]; if(! record) return false; return record.clone(); }, exists:function(id){ return this.findByPk(id) !== false; }, reload:function(values, options){ options = options || {}; if(options.clear) this.reset(); var records = this.fromJSON(values); if(!_isArray(records)) records = [records]; var record; var i = 0, l = records.length; for(; i < l; i++){ record = records[i]; //record.id || (record.id = record.gid); if(record['id'] )this.records[record.id] = record; this.grecords[record.gid] = record; } this.publish('reload', this.clonesArray(records)); return this; }, select:function(filter){ var result = (function(){ var r = this.records; var record; var results = []; for( var id in r){ if(r.hasOwnProperty(id)){ record = r[id]; if(filter(record)) results.push(record); } } return results; }).call(this); return this.clonesArray(result); }, findByAttribute:function(attr, value, grecords){ var r = grecords? this.grecords : this.records; var record, id, rvalue; for( id in r){ if(r.hasOwnProperty(id)){ record = r[id]; rvalue = _result(record,attr); if( rvalue === value) return record.clone(); } } return null; }, findAllByAttribute:function(name, value, options){ return this.select(function(item){ var rvalue = _result(item, name); return ( rvalue === value); }); }, deleteAll:function(){ var r = this.records; var key, value; var result = []; for( key in r){ if(r.hasOwnProperty(key)){ value = r[key]; result.push(delete this.records[key]); } } return result; }, destroyAll:function(){ var r = this.records; var key, value, result = []; for( key in r){ if(r.hasOwnProperty(key)){ value = r[key]; result.push(this.records[key].destroy()); } } return result; } }).include({ service:function(){ this.ctor.service.apply(this.ctor, arguments); }, refresh:function(){ }, fetch:function(options){ options = options || {}; var model = this; var successCallback = options.onSuccess; options.onSuccess = function(resp, status, xhr){ //handle response data model.load(resp); if(successCallback) successCallback(model, resp, options); }; this.service('read',this, options); return this; }, save:function(options){ options = options || {}; console.log('=============== SAVE'); //Validate unless told not to. if(options.validate !== false){ if(this.isInvalid()) this.publish('error',options); } this.publish('beforeSave'); var action = this.isNewRecord() ? 'create' : 'update'; //TODO: Refactor this!!!! if(action === 'update' ) options.skipSync = true; var record = this[action](options); this.publish('save', options); return record; }, create:function(options){ options = options || {}; this.publish('beforeCreate',options); // if(!this.id) this.id = this.gid; var record = this.duplicate(false); //TODO: this.collection.add(this.id) if(this.has('id')) this.constructor.records[this.id] = record; this.constructor.grecords[this.gid] = record; // this.constructor.add(this); var clone = record.clone(); clone.publish('create', options); console.log('::::::::::::::::::::::::::::::: ', arguments.callee.caller); if(options.skipSync) this.service('create', this, options); this.setScenario('update'); return clone; }, update:function(options){ if(this.isNewRecord()) { console.log("JII","Cannot update record, is new."); return; } options = options || {}; this.publish('beforeUpdate',options); //TODO: this.collection.get(this.id); var record = this.constructor.records[this.id]; record.load(this.getAttributes()); var clone = record.clone(); if(options.skipSync) this.service('update',this, options); this.publish('update', options); return clone; }, destroy:function(options){ options = options || {}; this.publish('beforeDestroy', options); if(options.skipDestroy) return this; var model = this; var successCallback = options.onSuccess; options.onSuccess = function(resp){ if(successCallback) successCallback(model, resp, options); }; this.service('destroy', this, options); this.publish('destroy', options); this.destroyed = true; // this.unbind(); return this; } }); ///////////////////////////////////////////////////// //// SYNC LAYER ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// namespace[exportName] = Model; })(jii, 'Model', 'Module', 'PubSub');
mit
tbepler/LRPaGe
src/bepler/lrpage/ebnf/parser/nodes/NameKeywordToken.java
954
package bepler.lrpage.ebnf.parser.nodes; import bepler.lrpage.ebnf.parser.Symbols; import bepler.lrpage.ebnf.parser.Visitor; import bepler.lrpage.ebnf.parser.framework.Symbol; import bepler.lrpage.ebnf.parser.framework.Token; /** * This class was generated by the LRPaGe parser generator v1.0 using the com.sun.codemodel library. * * <P>LRPaGe is available from https://github.com/tbepler/LRPaGe. * <P>CodeModel is available from https://codemodel.java.net/. * */ public class NameKeywordToken extends Token<Visitor> { public NameKeywordToken(String text, int line, int pos) { super(text, line, pos); } public NameKeywordToken() { super(); } @Override public void accept(Visitor visitor) { //do nothing } @Override public Symbol symbol() { return Symbols.NAMEKEYWORD; } @Override public String toString() { return symbol().toString(); } }
mit
squix78/extraleague
src/main/java/ch/squix/extraleague/model/ranking/tasks/EmperorTask.java
1248
package ch.squix.extraleague.model.ranking.tasks; import static com.googlecode.objectify.ObjectifyService.ofy; import java.util.Map; import org.joda.time.LocalDate; import ch.squix.extraleague.model.match.Matches; import ch.squix.extraleague.model.ranking.PlayerRanking; import ch.squix.extraleague.model.ranking.Ranking; import ch.squix.extraleague.model.ranking.badge.BadgeEnum; public class EmperorTask implements RankingTask { @Override public void rankMatches(Map<String, PlayerRanking> playerRankingMap, Matches matches) { LocalDate today = new LocalDate(); LocalDate weekStart = today.dayOfWeek().withMinimumValue(); Ranking weekStartRanking = ofy().load().type(Ranking.class).order("createdDate").filter("createdDate > ", weekStart.toDate()).limit(1).first().now(); if (weekStartRanking != null) { for (PlayerRanking weekStartPlayerRanking : weekStartRanking.getPlayerRankings()) { if (weekStartPlayerRanking.getBadges().contains(BadgeEnum.King.name())) { PlayerRanking playerRanking = playerRankingMap.get(weekStartPlayerRanking.getPlayer()); if (playerRanking != null) { playerRanking.getBadges().add(BadgeEnum.Emperor.name()); } } } } } }
mit
ashutoshrishi/slate
packages/slate-html-serializer/test/deserialize/no-next.js
498
/** @jsx h */ import h from '../helpers/h' export const config = { rules: [ { deserialize(el, next) { switch (el.tagName.toLowerCase()) { case 'p': { return { object: 'block', type: 'paragraph', nodes: next(), } } } }, }, ], } export const input = ` <p>one</p> `.trim() export const output = ( <value> <document> <paragraph /> </document> </value> )
mit
abedurftig/XML2Code
Java-Shared/src/main/java/com/xml2code/java/shared/json/DateJsonSerializer.java
689
package com.xml2code.java.shared.json; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.JsonSerializer; import org.codehaus.jackson.map.SerializerProvider; public class DateJsonSerializer extends JsonSerializer<Date> { @Override public void serialize(Date value, JsonGenerator gen, SerializerProvider provider) throws IOException, JsonProcessingException { SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy"); String formattedDate = formatter.format(value); gen.writeString(formattedDate); } }
mit
carakas/fork-cms-module-generator
src/PhpGenerator/WidgetName/WidgetNameDataTransferObject.php
709
<?php namespace ModuleGenerator\PhpGenerator\WidgetName; final class WidgetNameDataTransferObject { /** @var string */ public $name; /** @var WidgetName|null */ private $widgetNameClass; public function __construct(WidgetName $widgetName = null) { $this->widgetNameClass = $widgetName; if (!$this->widgetNameClass instanceof WidgetName) { return; } $this->name = $this->widgetNameClass->getName(); } public function hasExistingWidgetName(): bool { return $this->widgetNameClass instanceof WidgetName; } public function getWidgetNameClass(): WidgetName { return $this->widgetNameClass; } }
mit
kenshinthebattosai/LinqAn.Google
src/LinqAn.Google/Metrics/AvgEventValue.cs
404
using System.ComponentModel; namespace LinqAn.Google.Metrics { /// <summary> /// The average value of an event. /// </summary> [Description("The average value of an event.")] public class AvgEventValue: Metric<float> { /// <summary> /// Instantiates a <seealso cref="AvgEventValue" />. /// </summary> public AvgEventValue(): base("Avg. Value",false,"ga:avgEventValue") { } } }
mit
MachMX/embbed-example
app.js
112
var input = document.getElementById("link"); var parseButton = document.getElementById("parseButton") function
mit
ozlerhakan/poiji
src/test/java/com/poiji/deserialize/model/TestIllegalAccessInfo.java
234
package com.poiji.deserialize.model; import com.poiji.annotation.ExcelCell; import java.math.BigDecimal; public class TestIllegalAccessInfo { @ExcelCell(1) private final static BigDecimal amount = BigDecimal.valueOf(0); }
mit
stremann/t7h-ci-kit
src/back/bootstrap/preMiddleware.spec.js
798
'use strict'; const proxyquire = require('proxyquire'); describe('bootstrap pre middleware', () => { let cors, bodyParser, app, result; beforeEach(() => { app = { use: env.spy(() => app) }; cors = env.stub().returns({}); bodyParser = { json: env.stub().returns({}) }; result = proxyquire('./preMiddleware', { cors, 'body-parser': bodyParser })(app); }); it('should add cors filter', () => { app.use.should.been.calledWith(cors()); }); it('should add json body parser', () => { app.use.should.been.calledWith(bodyParser.json()); }); it('should return app', () => { result.should.equal(app); }); });
mit
os-alan/cake
src/Cake.Core/IO/ProcessWrapper.cs
1395
using System; using System.Collections.Generic; using System.Diagnostics; using Cake.Core.Diagnostics; namespace Cake.Core.IO { internal sealed class ProcessWrapper : IProcess { private readonly Process _process; private readonly ICakeLog _log; private readonly Func<string, string> _filterOutput; public ProcessWrapper(Process process, ICakeLog log, Func<string, string> filterOutput) { _process = process; _log = log; _filterOutput = filterOutput ?? (source => "[REDACTED]"); } public void WaitForExit() { _process.WaitForExit(); } public bool WaitForExit(int milliseconds) { if (_process.WaitForExit(milliseconds)) { return true; } _process.Refresh(); if (!_process.HasExited) { _process.Kill(); } return false; } public int GetExitCode() { return _process.ExitCode; } public IEnumerable<string> GetStandardOutput() { string line; while ((line = _process.StandardOutput.ReadLine()) != null) { _log.Debug("{0}", _filterOutput(line)); yield return line; } } } }
mit
keltanas/yandex-metrika-bundle
src/keltanas/Bundle/YandexMetrikaBundle/keltanasYandexMetrikaBundle.php
157
<?php namespace keltanas\Bundle\YandexMetrikaBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class keltanasYandexMetrikaBundle extends Bundle { }
mit
astrieanna/phabricator-ruby
test/unit/_lib.rb
146
require File.expand_path('../../_lib', __FILE__) module PhabricatorTests::Unit class Test < PhabricatorTests::Test include Stubs end end
mit
BrendanLeber/adventofcode
2017/06-memory_reallocation/solver.cpp
2358
#include <algorithm> #include <iostream> #include <iterator> #include <limits> #include <vector> bool is_repeat_state(std::vector<int> const& state, std::vector<int> const& banks); void redistribute_blocks(std::vector<int>& banks); // NOLINT int solver_1(std::vector<int> banks); int solver_2(std::vector<int> banks); bool is_repeat_state(std::vector<int> const& state, std::vector<int> const& banks) { return std::equal(std::begin(state), std::end(state), std::begin(banks)); } void redistribute_blocks(std::vector<int>& banks) { // find position of bank with the highest block count size_t pos = 0; int blocks = std::numeric_limits<int>::min(); for (size_t i = 0; i < banks.size(); ++i) { if (banks[i] > blocks) { blocks = banks[i]; pos = i; } } // get the number of blocks in that bank and reset it to zero blocks = banks[pos]; banks[pos] = 0; // redistribute the blocks among the other banks while (blocks > 0) { pos = (pos + 1) % banks.size(); banks[pos] += 1; blocks -= 1; } } int solver_1(std::vector<int> banks) { int num_steps = 0; std::vector<std::vector<int>> states; while (true) { ++num_steps; redistribute_blocks(banks); // have we seen this state before? for (auto const& state : states) { if (is_repeat_state(state, banks)) { return num_steps; } } states.push_back(banks); } } int solver_2(std::vector<int> banks) { std::vector<std::vector<int>> states; while (true) { redistribute_blocks(banks); for (auto const& state : states) { if (std::equal(std::begin(state), std::end(state), std::begin(banks))) { int num_cycles = 0; while (true) { ++num_cycles; redistribute_blocks(banks); if (is_repeat_state(state, banks)) { return num_cycles; } } } } states.push_back(banks); } } int main() { std::vector<int> banks{ std::istream_iterator<int>{ std::cin }, {} }; std::cout << "Part 1: " << solver_1(banks) << '\n'; std::cout << "Part 2: " << solver_2(banks) << '\n'; return 0; }
mit
evanscloud/volunteermatch
lib/volunteermatch/api/metadata.rb
175
module Volunteermatch module API module Metadata def metadata(version = nil) call(:getMetaData, {:version => version}.to_json) end end end end
mit
dubreuia/intellij-plugin-save-actions
src/test/java/com/dubreuia/processors/BuildProcessorTest.java
2230
/* * The MIT License (MIT) * * Copyright (c) 2020 Alexandre DuBreuil * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.dubreuia.processors; import com.dubreuia.model.Action; import org.junit.jupiter.api.Test; import java.util.List; import static com.dubreuia.model.ActionType.build; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; class BuildProcessorTest { @Test void should_processor_have_no_duplicate_action() { List<Action> actions = BuildProcessor.stream().map(Processor::getAction).collect(toList()); assertThat(actions).doesNotHaveDuplicates(); } @Test void should_processor_have_valid_type_and_inspection() { BuildProcessor.stream() .forEach(processor -> assertThat(processor.getAction().getType()).isEqualTo(build)); BuildProcessor.stream() .forEach(processor -> assertThat(((BuildProcessor) processor).getCommand()).isNotNull()); } @Test void should_action_have_java_processor() { Action.stream(build).forEach(action -> assertThat(BuildProcessor.getProcessorForAction(action)).isNotEmpty()); } }
mit
dude719/JetBrains-NASM-Language
gen/com/nasmlanguage/psi/NASMBitwiseORExpr.java
290
// This is a generated file. Not intended for manual editing. package com.nasmlanguage.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface NASMBitwiseORExpr extends NASMExpr { @NotNull List<NASMExpr> getExprList(); }
mit
baldursson/tabbouleh
test/dummy/config/application.rb
930
require File.expand_path('../boot', __FILE__) require 'rails/all' require 'jquery-rails' require 'parsley-rails' Bundler.require(*Rails.groups) require "tabbouleh" module Dummy class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
mit
hxf829/duilibtest
QQDemo/ColorPicker.cpp
2889
#include "stdafx.h" #include <windows.h> #if !defined(UNDER_CE) #include <shellapi.h> #endif #include "win_impl_base.hpp" #include "ColorPicker.hpp" #include "chat_dialog.hpp" static DWORD Colors[5][8] = { { 0xFF000000,0xFFA52A00,0xFF004040,0xFF005500,0xFF00005E,0xFF00008B,0xFF4B0082,0xFF282828 }, { 0xFF8B0000,0xFFFF6820,0xFF8B8B00,0xFF009300,0xFF388E8E,0xFF0000FF,0xFF7B7BC0,0xFF666666 }, { 0xFFFF0000,0xFFFFAD5B,0xFF32CD32,0xFF3CB371,0xFF7FFFD4,0xFF7D9EC0,0xFF800080,0xFF7F7F7F }, { 0xFFFFC0CB,0xFFFFD700,0xFFFFFF00,0xFF00FF00,0xFF40E0D0,0xFFC0FFFF,0xFF480048,0xFFC0C0C0 }, { 0xFFFFE4E1,0xFFD2B48C,0xFFFFFFE0,0xFF98FB98,0xFFAFEEEE,0xFF68838B,0xFFE6E6FA,0xFFA020F0 } }; CColorPicker::CColorPicker(ChatDialog* chat_dialog, POINT ptMouse) : based_point_(ptMouse) , chat_dialog_(chat_dialog) { Create(NULL, _T("color"), WS_POPUP, WS_EX_TOOLWINDOW, 0, 0); ShowWindow(true); } LPCTSTR CColorPicker::GetWindowClassName() const { return _T("ColorWindow"); } void CColorPicker::OnFinalMessage(HWND hWnd) { WindowImplBase::OnFinalMessage(hWnd); delete this; } void CColorPicker::Notify(TNotifyUI& msg) { if (_tcsicmp(msg.sType, _T("click")) == 0) { CControlUI* pOne = static_cast<CControlUI*>(paint_manager_.FindControl(msg.ptMouse)); if (_tcsicmp(pOne->GetClass(), _T("ButtonUI")) == 0) { DWORD nColor = pOne->GetBkColor(); CVerticalLayoutUI* pColorContiner = static_cast<CVerticalLayoutUI*>(paint_manager_.FindControl(_T("color"))); pColorContiner->SetBkColor(nColor); UpdateWindow(m_hWnd); Sleep(500); chat_dialog_->SetTextColor(nColor); } } } void CColorPicker::Init() { CVerticalLayoutUI* pColorContiner = static_cast<CVerticalLayoutUI*>(paint_manager_.FindControl(_T("color"))); for (int i = 0; (i < 5) && (pColorContiner != NULL); i ++) { CHorizontalLayoutUI* pLine = new CHorizontalLayoutUI(); pLine->SetFixedHeight(12); pColorContiner->Add(pLine); for (int j = 0; j < 8; j++) { CButtonUI* pOne = new CButtonUI(); pOne->ApplyAttributeList(_T("bordersize=\"1\" bordercolor=\"#FF000000\" width=\"10\" height=\"10\"")); pOne->SetBkColor(Colors[i][j]); pLine->Add(pOne); if (i < 7) { CControlUI* pMargin = new CControlUI(); pMargin->SetFixedWidth(2); pLine->Add(pMargin); } } } SIZE size = paint_manager_.GetInitSize(); MoveWindow(m_hWnd, based_point_.x - static_cast<LONG>(size.cx / 2), based_point_.y - size.cy, size.cx, size.cy, FALSE); } tString CColorPicker::GetSkinFile() { return _T("color.xml"); } tString CColorPicker::GetSkinFolder() { return tString(CPaintManagerUI::GetInstancePath()) + _T("skin\\"); } LRESULT CColorPicker::OnKillFocus(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { chat_dialog_->SetTextColor(0); Close(); return 0; }
mit
geometryzen/davinci-units
src/davinci-units/math/isScalarG3.ts
203
import GeometricE3 from '../math/GeometricE3'; export default function(m: GeometricE3): boolean { return m.x === 0 && m.y === 0 && m.z === 0 && m.xy === 0 && m.yz === 0 && m.zx === 0 && m.b === 0 }
mit
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_10_01/models/express_route_circuits_routes_table_list_result_py3.py
1286
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class ExpressRouteCircuitsRoutesTableListResult(Model): """Response for ListRoutesTable associated with the Express Route Circuits API. :param value: The list of routes table. :type value: list[~azure.mgmt.network.v2017_10_01.models.ExpressRouteCircuitRoutesTable] :param next_link: The URL to get the next set of results. :type next_link: str """ _attribute_map = { 'value': {'key': 'value', 'type': '[ExpressRouteCircuitRoutesTable]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__(self, *, value=None, next_link: str=None, **kwargs) -> None: super(ExpressRouteCircuitsRoutesTableListResult, self).__init__(**kwargs) self.value = value self.next_link = next_link
mit
Aaylor/Goinfr-O-Mania
src/graphics/VolumeController.java
890
package graphics; import com.sun.javaws.exceptions.InvalidArgumentException; import engine.Settings; import log.IGLog; /** * Created by PixelMan on 28/05/15. */ @SuppressWarnings("DefaultFileTemplate") public class VolumeController extends AbstractVolumeController { public VolumeController(Settings currentSettings) { super(currentSettings, currentSettings.getVolume()); } @Override public void updateSonorVolume(int volume) { try { double optionVolume = new Integer(volume).doubleValue() / 100; IGLog.info("Options updates <volume> : " + optionVolume); currentSettings.setVolume(optionVolume); MainFrame.getCurrentInstance().getMainMusic().setVolume(currentSettings.getVolume()); } catch (InvalidArgumentException e){ IGLog.error("Invalide Sonor Volume"); } } }
mit
Knape/triggerhappy
lib/rampage.js
189
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // import { load, spray } from './spray'; var rampage = function rampage() {}; exports.default = rampage;
mit
slyxster/sabc
fuel/app/modules/office/views/employeesearch.php
378
<form action="/office" method="post"> <input type="hidden" name="action" value="empsearch" /> <input type="hidden" value="<?php echo $_SERVER['REQUEST_URI']; ?>" name="redirect" /> <input type="text" placeholder="Search by Employee ID" maxlength=9 value="" name="employee_id" /> &nbsp; <input type="submit" value="Go" name="submit" class="btn btn-success" /> </form>
mit
DTChuck/HSImage
src/pybind11_opencv_numpy/example/__init__.py
23
from ._example import *
mit
kossov/Telerik-Academy
C#/OOP/ExamPrep/OOP - 25 March 2013 - Evening/2. AcademyEcosystem_Скелет на задачата/AcademyEcosystem/AcademyEcosystem/ExtendedEngine.cs
1941
using AcademyEcosystem.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AcademyEcosystem { public class ExtendedEngine : Engine { protected override void ExecuteBirthCommand(string[] commandWords) { switch (commandWords[1]) { case "wolf": { string name = commandWords[2]; Point position = Point.Parse(commandWords[3]); this.AddOrganism(new Wolf(name, position)); break; } case "lion": { string name = commandWords[2]; Point position = Point.Parse(commandWords[3]); this.AddOrganism(new Lion(name, position)); break; } case "grass": { Point position = Point.Parse(commandWords[2]); this.AddOrganism(new Grass(position)); break; } case "boar": { string name = commandWords[2]; Point position = Point.Parse(commandWords[3]); this.AddOrganism(new Boar(name,position)); break; } case "zombie": { string name = commandWords[2]; Point position = Point.Parse(commandWords[3]); this.AddOrganism(new Zombie(name, position)); break; } default: base.ExecuteBirthCommand(commandWords); break; } } } }
mit
MarcinGoryca/olive
Files/fread.php
767
<?php //Using fopen() with fread() $filename = "../data/example.txt"; $file = fopen($filename, "rb"); $filedata = fread($file, filesize($filename)); fclose($file); $filearray = explode("\n", $filedata); while(list($line, $data) = each($filearray)) { $data = trim($data); echo $data . "<br/>"; } //echo $filedata; ?> <link rel="stylesheet" href="../media/style.css"> <h2>-- Reading a file --</h2> <div class="codeblock"> <pre> <code> //Using fopen() with fread() $filename = "../data/example.txt"; $file = fopen($filename, "rb"); $filedata = fread($file, filesize($filename)); fclose($file); $filearray = explode("\n", $filedata); while(list($line, $data) = each($filearray)) { $data = trim($data); echo $data . "<br/>"; } </code> </pre></div>
mit
pascal-vincent/websocket-notif-lab-android
app/src/main/java/fr/skalit/websocketnotificationpoc/model/TopicMessage.java
998
package fr.skalit.websocketnotificationpoc.model; /** * Created by pascalvincent on 21/05/2016. */ class TopicMessage { public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getPriority() { return priority; } public void setPriority(String priority) { this.priority = priority; } private String content; private String date; private String priority; public TopicMessage(String content, String date, String priority) { this.content = content; this.date = date; this.priority = priority; } @Override public String toString() { return ("content : " + this.content) + ", date : " + this.date + ", priority" + this.priority; } }
mit
DoublePrecisionSoftware/jsontl
test/negative/if.js
750
var data = { "Customer": { "Id": 2, "Name": "Joe", "Type": "VIP" } }; var transform = { "jsontl": { "version": "0.1", "transform": { "Customer": [ { "replace": { "Name": { "with": "Jerry", "if": { "Id": 1, "Type": "None" } } } } ] } } }; var assert = require('assert'); module.exports = function (jsontl) { describe('if condition', function () { before(function () { jsontl.transform(data, transform); }); it('should not execute transform if no criteria are met', function () { assert.notEqual(data.Customer.Name, "Jerry"); }); }); };
mit
boh1996/TwitterAnalytics
v2/application/views/templates/new_string_view.php
652
<div class="form-group string-object" style="min-width:600px;" data-category-id="<?= $cat_id; ?>"> <label class="col-sm-2 control-label"><?= $this->lang->line("admin_add_string"); ?></label> <div class="col-sm-10"> <div class="input-group"> <input type="text" data-category-id="<?= $cat_id; ?>" class="form-control create-string add-string" placeholder="<?= $this->lang->line("admin_add_string"); ?>" > <span class="input-group-btn"> <button data-category-id="<?= $cat_id; ?>" class="btn btn-lg btn-danger button-addon remove-string" type="button"><?= $this->lang->line("admin_remove_item"); ?></button> </span> </div> </div> </div>
mit
crystian/WEBAPP-BUILDER
loader/modules/settings.js
1479
/** * Created by Crystian on 3/2/14. */ loader.settings = (function(){ 'use strict'; var VERSION = 'v'; //jshint maxcomplexity:9 function init(){ var version = get('version'); if(!version){ //FIRST TIME! console.info('First time to here!'); //set defaults values set(VERSION, loader.cfg.version); //nomenclature version //others settings ... } else { if(loader.utils.compareSemVer(loader.cfg.version, version) === 1){ console.warn('New version by revision, migrate data...'); //after all set(VERSION, loader.cfg.version); //trigger an event for others updates document.dispatchEvent(loader.events.newVersionDetected); } //more than once time here. //try to get data } } function set(item, value){ var v = ''; try{ v = JSON.stringify(value); } catch(e){ console.error('Error with stringify: ', item, value, e); } localStorage.setItem(item, v); } function get(item){ var v = {}; try{ v = JSON.parse(localStorage.getItem(item)); } catch(e){ console.error('Error with parse: ', item, e); } return v; } function remove(item){ return localStorage.removeItem(item); } function removeAlldata(){ localStorage.clear(); } return { VERSION: VERSION, init: init, remove: remove, removeAlldata: removeAlldata, set: set, get: get }; }());
mit
724789975/FxLib
Client_Unity/Test/Assets/Scripts/UI/GameEffectCanvas.cs
294
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameEffectCanvas : SingletonObject<GameEffectCanvas> { // Use this for initialization void Start () { CreateInstance(this); } // Update is called once per frame void Update () { } }
mit
redbaty/ETS2.Brake
Overlay/Hook/Common/IOverlayElement.cs
171
using System; namespace Overlay.Hook.Common { public interface IOverlayElement : ICloneable { bool Hidden { get; set; } void Frame(); } }
mit
tslab-sit/asciiart-extractor
src/main/java/jp/ac/shibaura_it/se/tslab/aaextractor/predicate/rls/RLSASCIIArtExtractor.java
2736
package jp.ac.shibaura_it.se.tslab.aaextractor.predicate.rls; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import jp.ac.shibaura_it.se.tslab.aaextractor.Window; import jp.ac.shibaura_it.se.tslab.aaextractor.predicate.PredicateBasedASCIIArtExtractor; import jp.ac.shibaura_it.se.tslab.aaextractor.predicate.Recognizer; import jp.ac.shibaura_it.se.tslab.aaextractor.predicate.SVMIdentityScaler; import jp.ac.shibaura_it.se.tslab.aaextractor.predicate.SVMScaleFile; import jp.ac.shibaura_it.se.tslab.aaextractor.predicate.SVMScaler; import libsvm.svm; import libsvm.svm_model; import weka.classifiers.trees.J48; public class RLSASCIIArtExtractor { public static void printUsage() { System.err.println("ASCIIArtExtractor [-s scale] <recognizer_type> <model> <width> <file>"); } /** * TextArtExtractor model file * @param args command line arguments */ public static void main(String[] args) { SVMScaler scaler = new SVMIdentityScaler(); int argIndex=0; if (args.length == 6) { if (!args[argIndex++].equals("-s")) { printUsage(); System.exit(1); } String scaleFileName = args[argIndex++]; try { scaler = new SVMScaleFile(scaleFileName); } catch (Exception e) { System.err.println(e.getMessage()); System.exit(1); } } else if (args.length != 4) { printUsage(); System.exit(1); } Recognizer recognizer = null; ArrayList<String> contents = new ArrayList<String>(); int width=1; try { String format=args[argIndex++]; if (format.equals("j48") || format.equals("J48")) { if (scaler instanceof SVMScaleFile) { printUsage(); System.exit(1); } J48 j48 = (J48)weka.core.SerializationHelper.read(args[argIndex++]); recognizer = new RLSJ48(j48); } else if (format.equals("svm") || format.equals("SVM")) { svm_model model = svm.svm_load_model(args[argIndex++]); recognizer = new RLSSVM(model, scaler); } else { System.err.println("<recognizer_type> must be j48 or svm"); System.exit(1); } // width width = Integer.parseInt(args[argIndex++]); // BufferedReader br = new BufferedReader(new FileReader(args[argIndex++])); String line; while((line = br.readLine()) != null) { contents.add(line); } br.close(); } catch (Exception e) { System.err.println(e.getMessage()); System.exit(1); } PredicateBasedASCIIArtExtractor extractor = new PredicateBasedASCIIArtExtractor(recognizer, width, contents); List<Window> windows = extractor.extract(); System.out.print(windows.size()); for(Window w: windows) { System.out.print("," + w.getStartingLine() + "," + w.getEndLine()); } System.out.println(); } }
mit
l8on/affiance
test/unit/lib/hook/pre-commit/Spectral.test.js
2386
'use strict'; const testHelper = require('../../../../test_helper'); const expect = testHelper.expect; const sinon = testHelper.sinon; const Spectral = testHelper.requireSourceModule(module); const Config = testHelper.requireSourceModule(module, 'lib/config'); const HookContextPreCommit = testHelper.requireSourceModule(module, 'lib/hook-context/pre-commit'); describe('Spectral', function() { beforeEach('setup hook context', function() { this.sandbox = sinon.sandbox.create(); this.config = new Config({}); this.context = new HookContextPreCommit(this.config, [], {}); this.hook = new Spectral(this.config, this.context); this.result = { status: 0, stderr: '', stdout: '' }; this.sandbox.stub(this.hook, 'spawnPromiseOnApplicableFiles').returns(Promise.resolve(this.result)); }); afterEach('restore sandbox', function() { this.sandbox.restore(); }); it('passes when there are no messages output', function() { this.result.stdout = ''; return this.hook.run().then((hookResults) => { expect(hookResults).to.equal('pass'); }); }); it('warns when there are messages output', function() { this.result.stdout = [ '/path/to/file.js:10:2 warning rule-name "This is a warning message"' ].join('\n'); return this.hook.run().then((hookResults) => { expect(hookResults).to.have.length(1); expect(hookResults[0]).to.have.property('content', '/path/to/file.js:10:2 warning rule-name "This is a warning message"'); expect(hookResults[0]).to.have.property('file', '/path/to/file.js'); expect(hookResults[0]).to.have.property('line', 10); expect(hookResults[0]).to.have.property('type', 'warning'); }); }); it('fails when there is an error in the output', function() { this.result.status = 1; this.result.stdout = [ '/path/to/file.js:20:2 error rule-name "This is an error message"' ].join('\n'); return this.hook.run().then((hookResults) => { expect(hookResults).to.have.length(1); expect(hookResults[0]).to.have.property('content', '/path/to/file.js:20:2 error rule-name "This is an error message"'); expect(hookResults[0]).to.have.property('file', '/path/to/file.js'); expect(hookResults[0]).to.have.property('line', 20); expect(hookResults[0]).to.have.property('type', 'error'); }); }); });
mit
jaakon/PHP-DI
tests/UnitTest/Definition/Source/ReflectionBasedAutowiringTest.php
1894
<?php declare(strict_types=1); namespace DI\Test\UnitTest\Definition\Source; use DI\Definition\EntryReference; use DI\Definition\ObjectDefinition; use DI\Definition\ObjectDefinition\MethodInjection; use DI\Definition\Source\ReflectionBasedAutowiring; use DI\Test\UnitTest\Definition\Source\Fixtures\AutowiringFixture; use DI\Test\UnitTest\Definition\Source\Fixtures\AutowiringFixtureChild; /** * @covers \DI\Definition\Source\ReflectionBasedAutowiring */ class ReflectionBasedAutowiringTest extends \PHPUnit_Framework_TestCase { public function testUnknownClass() { $source = new ReflectionBasedAutowiring(); $this->assertNull($source->autowire('foo')); } public function testConstructor() { $definition = (new ReflectionBasedAutowiring)->autowire(AutowiringFixture::class); $this->assertInstanceOf(ObjectDefinition::class, $definition); $constructorInjection = $definition->getConstructorInjection(); $this->assertInstanceOf(MethodInjection::class, $constructorInjection); $parameters = $constructorInjection->getParameters(); $this->assertCount(1, $parameters); $param1 = $parameters[0]; $this->assertEquals(new EntryReference(AutowiringFixture::class), $param1); } public function testConstructorInParentClass() { $definition = (new ReflectionBasedAutowiring)->autowire(AutowiringFixtureChild::class); $this->assertInstanceOf(ObjectDefinition::class, $definition); $constructorInjection = $definition->getConstructorInjection(); $this->assertInstanceOf(MethodInjection::class, $constructorInjection); $parameters = $constructorInjection->getParameters(); $this->assertCount(1, $parameters); $param1 = $parameters[0]; $this->assertEquals(new EntryReference(AutowiringFixture::class), $param1); } }
mit
isxGames/Lavish.UI
Lavish.UI/lguitabcontrol.cs
1122
/* * Lavish.UI: A .NET wrapper for LavishSofts LavishGUI objects * Copyright (c) 2007 isxGames & CyberTech (cybertech@gmail.com) * * Repository located at https://github.com/isxGames/Lavish.UI */ using System; using InnerSpaceAPI; using LavishScriptAPI; namespace Lavish.UI { public class lguitabcontrol : lguielement { public lguitabcontrol() : base(LavishScript.Objects.GetObject("LavishGUI")) { } public lguitabcontrol(LavishScriptObject Copy) : base(Copy) { } public lguifont Font { get { return GetMember<lguifont>("Font"); } } public Int32 Tabs { get { return GetMember<Int32>("Tabs"); } } public lguitab SelectedTab { get { return GetMember<lguitab>("SelectedTab"); } } public lguitab Tab(Int32 TabID) { return GetMember<lguitab>("SelectedTab", new string[] { TabID.ToString() }); } public lguitab Tab(String TabName) { return GetMember<lguitab>("SelectedTab", new string[] { TabName }); } public Boolean AddTab(String TabName) { return ExecuteMethod("AddTab", new string[] { TabName }); } } }
mit
nifty-site-manager/nsm
ProjectInfo.cpp
134871
#include "ProjectInfo.h" #if defined __APPLE__ || defined __linux__ const std::string promptStr = "⥤ "; #else const std::string promptStr = "=> "; #endif int create_default_html_template(const Path& templatePath) { templatePath.ensureDirExists(); std::ofstream ofs(templatePath.str()); ofs << "<html>" << std::endl; ofs << "\t<head>" << std::endl; ofs << "\t\t@input(\"" << templatePath.dir << "head.content\")" << std::endl; ofs << "\t</head>" << std::endl << std::endl; ofs << "\t<body>" << std::endl; ofs << "\t\t@content" << std::endl; ofs << "\t</body>" << std::endl; ofs << "</html>" << std::endl << std::endl; ofs.close(); ofs.open(Path(templatePath.dir, "head.content").str()); ofs << "<title>empty site - $[title]</title>" << std::endl; ofs.close(); return 0; } int create_blank_template(const Path& templatePath) { templatePath.ensureDirExists(); std::ofstream ofs(templatePath.str()); ofs << "@content" << std::endl; ofs.close(); return 0; } int create_config_file(const Path& configPath, const std::string& outputExt, bool global) { configPath.ensureDirExists(); ProjectInfo project; if(!global) { project.contentDir = "content/"; project.contentExt = ".content"; project.outputDir = "output/"; project.outputExt = outputExt; project.scriptExt = ".f"; } if(global) { project.defaultTemplate = Path(app_dir() + "/.nift/template/", "global.template"); create_default_html_template(project.defaultTemplate); } else if(outputExt == ".html" || outputExt == ".php") project.defaultTemplate = Path("template/", "page.template"); else project.defaultTemplate = Path("template/", "project.template"); project.backupScripts = 1; project.lolcatDefault = 0; project.lolcatCmd = "nift lolcat-cc -f"; project.buildThreads = -1; project.paginateThreads = -1; project.incrMode = INCR_MOD; project.terminal = "normal"; project.unixTextEditor = "gedit"; project.winTextEditor = "notepad"; if(!global) { if(dir_exists(".git/")) //should really be checking if outputDir exists and has .git directory { if(get_pb(project.outputBranch)) { start_err(std::cout) << "failed to get present branch" << std::endl; return 1; } project.rootBranch = project.outputBranch; } else project.rootBranch = project.outputBranch = "##unset##"; } project.save_config(configPath.str(), global); return 0; } bool upgradeProject() { start_warn(std::cout) << "attempting to upgrade project for newer version of Nift" << std::endl; if(rename(".siteinfo/", ".nsm/")) { start_err(std::cout) << "upgrade: failed to move config directory '.siteinfo/' to '.nsm/'" << std::endl; return 1; } if(rename(".nsm/nsm.config", ".nsm/nift.config")) { start_err(std::cout) << "upgrade: failed to move config file '.nsm/nsm.config' to '.nsm/nift.config'" << std::endl; return 1; } if(rename(".nsm/pages.list", ".nsm/tracking.list")) { start_err(std::cout) << "upgrade: failed to move pages list file '.nsm/pages.list' to tracking list file '.nsm/tracking.list'" << std::endl; return 1; } ProjectInfo project; if(project.open_local_config(1)) { start_err(std::cout) << "upgrade: failed, was unable to open configuration file" << std::endl; return 1; } else if(project.open_tracking(1)) //this needs to change { start_err(std::cout) << "upgrade: failed, was unable to open tracking list" << std::endl; return 1; } //need to update output extension files Path oldExtPath, newExtPath; for(auto tInfo=project.trackedAll.begin(); tInfo!=project.trackedAll.end(); tInfo++) { oldExtPath = newExtPath = tInfo->outputPath.getInfoPath(); oldExtPath.file = oldExtPath.file.substr(0, oldExtPath.file.find_first_of('.')) + ".pageExt"; newExtPath.file = newExtPath.file.substr(0, newExtPath.file.find_first_of('.')) + ".outputExt"; if(file_exists(oldExtPath.str())) { if(rename(oldExtPath.str().c_str(), newExtPath.str().c_str())) { start_err(std::cout) << "upgrade: failed to move output extension file " << quote(oldExtPath.str()) << " to new extension file " << quote(newExtPath.str()) << std::endl; return 1; } } } std::cout << "Successfully upgraded project configuration for newer version of Nift" << std::endl; std::cout << c_light_blue << "note" << c_white << ": the syntax to input page and project/site information has also changed, please check the content files page of the docs" << std::endl; return 0; } int ProjectInfo::open(const bool& addMsg) { if(open_local_config(addMsg)) return 1; if(open_tracking(addMsg)) return 1; return 0; } int ProjectInfo::open_config(const Path& configPath, const bool& global, const bool& addMsg) { if(!file_exists(configPath.str())) { if(global) create_config_file(configPath, ".html", 1); else { start_err(std::cout) << "open_config(): could not load Nift project config file as '" << get_pwd() << "/.nsm/nift.config' does not exist" << std::endl; return 1; } } if(addMsg) { std::cout << "loading "; if(global) std::cout << "global "; else std::cout << "project "; std::cout << "config file: " << configPath << std::endl; //std::cout << std::flush; std::fflush(stdout); } contentDir = outputDir = ""; backupScripts = 1; buildThreads = paginateThreads = 0; incrMode = INCR_MOD; contentExt = outputExt = scriptExt = unixTextEditor = winTextEditor = rootBranch = outputBranch = ""; defaultTemplate = Path("", ""); //reads Nift config file std::ifstream ifs(configPath.str()); bool configChanged = 0; std::string inLine, inType, str = ""; int lineNo = 0; while(getline(ifs, inLine)) { lineNo++; if(!is_whitespace(inLine) && inLine.size() && inLine[0] != '#') { std::istringstream iss(inLine); iss >> inType; if(inType == "contentDir") { read_quoted(iss, contentDir); contentDir = comparable(contentDir); } else if(inType == "contentExt") read_quoted(iss, contentExt); else if(inType == "outputDir") { read_quoted(iss, outputDir); outputDir = comparable(outputDir); } else if(inType == "siteDir") //can delete this later { read_quoted(iss, outputDir); outputDir = comparable(outputDir); configChanged = 1; //start_warn(std::cout, Path(".nsm/", "nift.config"), lineNo) << "updated siteDir to outputDir" << std::endl; } else if(inType == "outputExt") read_quoted(iss, outputExt); else if(inType == "pageExt") //can delete this later { read_quoted(iss, outputExt); configChanged = 1; //start_warn(std::cout, Path(".nsm/", "nift.config"), lineNo) << "updated pageExt to outputExt" << std::endl; } else if(inType == "scriptExt") read_quoted(iss, scriptExt); else if(inType == "defaultTemplate") defaultTemplate.read_file_path_from(iss); else if(inType == "backupScripts") iss >> backupScripts; else if(inType == "lolcatDefault" || inType == "lolcat") //carry over from poor naming choices iss >> lolcatDefault; else if(inType == "lolcatCmd") read_quoted(iss, lolcatCmd); else if(inType == "buildThreads") iss >> buildThreads; else if(inType == "paginateThreads") iss >> paginateThreads; else if(inType == "incrementalMode") iss >> incrMode; else if(inType == "terminal") { read_quoted(iss, terminal); #if defined _WIN32 || defined _WIN64 if(terminal == "ps" || terminal == "powershell") use_powershell_colours(); #endif } else if(inType == "unixTextEditor") read_quoted(iss, unixTextEditor); else if(inType == "winTextEditor") read_quoted(iss, winTextEditor); else if(inType == "rootBranch") read_quoted(iss, rootBranch); else if(inType == "outputBranch") read_quoted(iss, outputBranch); else if(inType == "siteBranch") // can delete this later { read_quoted(iss, outputBranch); configChanged = 1; std::cout << std::endl; start_warn(std::cout, configPath, lineNo) << "updated siteBranch to outputBranch" << std::endl; } else { continue; //if we throw error here can't compile projects for newer versions with older versions of Nift //std::cout << std::endl; //start_err(std::cout, configPath, lineNo) << "do not recognise confirguration parameter " << inType << std::endl; //return 1; } iss >> str; if(str != "" && str[0] != '#') { start_err(std::cout, configPath, lineNo) << "was not expecting anything on this line from " << c_light_blue << quote(str) << c_white << " onwards" << std::endl; std::cout << c_aqua << "note: " << c_white << "you can comment out the remainder of a line with #" << std::endl; ifs.close(); return 1; } } } ifs.close(); add_colour(); if(!global) { if(contentDir == "") { start_err(std::cout, configPath) << "content directory not specified" << std::endl; return 1; } if(contentExt == "" || contentExt[0] != '.') { start_err(std::cout, configPath) << "content extension must start with a fullstop" << std::endl; return 1; } if(outputDir == "") { start_err(std::cout, configPath) << "output directory not specified" << std::endl; return 1; } if(outputExt == "" || outputExt[0] != '.') { start_err(std::cout, configPath) << "output extension must start with a fullstop" << std::endl; return 1; } if(scriptExt != "" && scriptExt [0] != '.') { start_err(std::cout, configPath) << "script extension must start with a fullstop" << std::endl; return 1; } else if(scriptExt == "") { start_warn(std::cout, configPath) << "script extension not detected, set to default of '.f'" << std::endl; scriptExt = ".f"; configChanged = 1; } } if(buildThreads == 0) { start_warn(std::cout, configPath) << "number of build threads not detected or invalid, set to default of -1 (number of cores)" << std::endl; buildThreads = -1; configChanged = 1; } if(paginateThreads == 0) { start_warn(std::cout, configPath) << "number of paginate threads not detected or invalid, set to default of -1 (number of cores)" << std::endl; paginateThreads = -1; configChanged = 1; } if(lolcatCmd.size() == 0) { start_warn(std::cout, configPath) << "no config detected for whether to use lolcat by default for REPL sessions" << std::endl; lolcatDefault = 0; lolcatCmd = "nift lolcat-cc -f"; configChanged = 1; } //code to set unixTextEditor if not present if(unixTextEditor == "") { start_warn(std::cout, configPath) << "unix text editor not detected, set to default of 'nano'" << std::endl; unixTextEditor = "nano"; configChanged = 1; } //code to set winTextEditor if not present if(winTextEditor == "") { start_warn(std::cout, configPath) << "windows text editor not detected, set to default of 'notepad'" << std::endl; winTextEditor = "notepad"; configChanged = 1; } if(!global) { //code to figure out rootBranch and outputBranch if not present if(rootBranch == "" || outputBranch == "") { start_warn(std::cout, configPath) << "root or output branch not detected, have attempted to determine them, ensure values in config file are correct" << std::endl; if(dir_exists(".git")) { std::set<std::string> branches; if(get_git_branches(branches)) { start_err(std::cout, configPath) << "open_config: failed to retrieve git branches" << std::endl; return 1; } if(branches.count("stage")) { rootBranch = "stage"; outputBranch = "master"; } else rootBranch = outputBranch = "master"; } else rootBranch = outputBranch = "##unset##"; configChanged = 1; } } //clear_console_line(); if(configChanged) save_config(configPath.str(), global); return 0; } int ProjectInfo::open_global_config(const bool& addMsg) { return open_config(Path(app_dir() + "/.nift/", "nift.config"), 1, addMsg); } int ProjectInfo::open_local_config(const bool& addMsg) { return open_config(Path(".nsm/", "nift.config"), 0, addMsg); } int ProjectInfo::open_tracking(const bool& addMsg) { if(addMsg) std::cout << "loading project tracking file: " << Path(".nsm/", "tracking.list") << std::endl; //std::cout << std::flush; std::fflush(stdout); trackedAll.clear(); if(!file_exists(".nsm/tracking.list")) { start_err(std::cout) << "open_tracking(): could not load tracking information as '" << get_pwd() << "/.nsm/tracking.list' does not exist" << std::endl; return 1; } //reads tracking list file std::ifstream ifs(".nsm/tracking.list"), ifsx; Name inName; Title inTitle; Path inTemplatePath; std::string inExt; while(read_quoted(ifs, inName)) { inTitle.read_quoted_from(ifs); inTemplatePath.read_file_path_from(ifs); TrackedInfo inInfo = make_info(inName, inTitle, inTemplatePath); //checks for non-default content extension Path extPath = inInfo.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".contExt"; if(file_exists(extPath.str())) { ifsx.open(extPath.str()); ifsx >> inExt; inInfo.contentPath.file = inInfo.contentPath.file.substr(0, inInfo.contentPath.file.find_first_of('.')) + inExt; ifsx.close(); } //checks for non-default output extension extPath = inInfo.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".outputExt"; if(file_exists(extPath.str())) { ifsx.open(extPath.str()); ifsx >> inExt; inInfo.outputPath.file = inInfo.outputPath.file.substr(0, inInfo.outputPath.file.find_first_of('.')) + inExt; ifsx.close(); } //checks that content and template files aren't the same if(inInfo.contentPath == inInfo.templatePath) { start_err(std::cout) << "failed to open .nsm/tracking.list" << std::endl; std::cout << c_light_blue << "reason: " << c_white << quote(inInfo.name) << " has same content and template path " << inInfo.templatePath << std::endl; ifs.close(); return 1; } //makes sure there's no duplicate entries in tracking.list if(trackedAll.count(inInfo) > 0) { TrackedInfo cInfo = *(trackedAll.find(inInfo)); start_err(std::cout) << "failed to load " << Path(".nsm/", "tracking.list") << std::endl; std::cout << c_light_blue << "reason: " << c_white << "duplicate entry for " << inInfo.name << std::endl; std::cout << c_light_blue << promptStr << c_white << "first entry:" << std::endl; std::cout << " title: " << cInfo.title << std::endl; std::cout << " output path: " << cInfo.outputPath << std::endl; std::cout << " content path: " << cInfo.contentPath << std::endl; std::cout << "template path: " << cInfo.templatePath << std::endl; std::cout << c_light_blue << promptStr << c_white << "second entry:" << std::endl; std::cout << " title: " << inInfo.title << std::endl; std::cout << " output path: " << inInfo.outputPath << std::endl; std::cout << " content path: " << inInfo.contentPath << std::endl; std::cout << "template path: " << inInfo.templatePath << std::endl; ifs.close(); return 1; } trackedAll.insert(inInfo); } ifs.close(); //clear_console_line(); return 0; } Path ProjectInfo::execrc_path(const std::string& exec, const std::string& execrc_ext) { return Path(app_dir() + "/.nift/", exec + "rc." + execrc_ext); } Path ProjectInfo::execrc_path(const std::string& exec, const char& execrc_ext) { return Path(app_dir() + "/.nift/", exec + "rc." + execrc_ext); } int ProjectInfo::save_config(const std::string& configPathStr, const bool& global) { std::ofstream ofs(configPathStr); if(!global) { ofs << "contentDir " << quote(contentDir) << "\n"; ofs << "contentExt " << quote(contentExt) << "\n"; ofs << "outputDir " << quote(outputDir) << "\n"; ofs << "outputExt " << quote(outputExt) << "\n"; ofs << "scriptExt " << quote(scriptExt) << "\n"; } ofs << "defaultTemplate " << quote(defaultTemplate.str()) << "\n\n"; ofs << "backupScripts " << backupScripts << "\n\n"; ofs << "lolcatDefault " << lolcatDefault << "\n\n"; ofs << "lolcatCmd " << quote(lolcatCmd) << "\n\n"; ofs << "buildThreads " << buildThreads << "\n\n"; ofs << "paginateThreads " << paginateThreads << "\n\n"; ofs << "incrementalMode " << incrMode << "\n\n"; ofs << "terminal " << quote(terminal) << "\n\n"; ofs << "unixTextEditor " << quote(unixTextEditor) << "\n"; ofs << "winTextEditor " << quote(winTextEditor) << "\n\n"; if(!global) { ofs << "rootBranch " << quote(rootBranch) << "\n"; ofs << "outputBranch " << quote(outputBranch) << "\n"; } ofs.close(); return 0; } int ProjectInfo::save_global_config() { return save_config(app_dir() + "/.nift/nift.config", 1); } int ProjectInfo::save_local_config() { return save_config(".nsm/nift.config", 0); } int ProjectInfo::save_tracking() { std::ofstream ofs(".nsm/tracking.list"); for(auto tInfo=trackedAll.begin(); tInfo!=trackedAll.end(); tInfo++) ofs << *tInfo << "\n\n"; ofs.close(); return 0; } TrackedInfo ProjectInfo::make_info(const Name& name) { TrackedInfo trackedInfo; trackedInfo.name = name; Path nameAsPath; nameAsPath.set_file_path_from(unquote(name)); trackedInfo.contentPath = Path(contentDir + nameAsPath.dir, nameAsPath.file + contentExt); trackedInfo.outputPath = Path(outputDir + nameAsPath.dir, nameAsPath.file + outputExt); trackedInfo.title = name; trackedInfo.templatePath = defaultTemplate; //checks for non-default extensions std::string inExt; Path extPath = trackedInfo.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".contExt"; if(file_exists(extPath.str())) { std::ifstream ifs(extPath.str()); getline(ifs, inExt); ifs.close(); trackedInfo.contentPath.file = trackedInfo.contentPath.file.substr(0, trackedInfo.contentPath.file.find_first_of('.')) + inExt; } extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".outputExt"; if(file_exists(extPath.str())) { std::ifstream ifs(extPath.str()); getline(ifs, inExt); ifs.close(); trackedInfo.outputPath.file = trackedInfo.outputPath.file.substr(0, trackedInfo.outputPath.file.find_first_of('.')) + inExt; } return trackedInfo; } TrackedInfo ProjectInfo::make_info(const Name& name, const Title& title) { TrackedInfo trackedInfo; trackedInfo.name = name; Path nameAsPath; nameAsPath.set_file_path_from(unquote(name)); trackedInfo.contentPath = Path(contentDir + nameAsPath.dir, nameAsPath.file + contentExt); trackedInfo.outputPath = Path(outputDir + nameAsPath.dir, nameAsPath.file + outputExt); trackedInfo.title = title; trackedInfo.templatePath = defaultTemplate; //checks for non-default extensions std::string inExt; Path extPath = trackedInfo.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".contExt"; if(file_exists(extPath.str())) { std::ifstream ifs(extPath.str()); getline(ifs, inExt); ifs.close(); trackedInfo.contentPath.file = trackedInfo.contentPath.file.substr(0, trackedInfo.contentPath.file.find_first_of('.')) + inExt; } extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".outputExt"; if(file_exists(extPath.str())) { std::ifstream ifs(extPath.str()); getline(ifs, inExt); ifs.close(); trackedInfo.outputPath.file = trackedInfo.outputPath.file.substr(0, trackedInfo.outputPath.file.find_first_of('.')) + inExt; } return trackedInfo; } TrackedInfo ProjectInfo::make_info(const Name& name, const Title& title, const Path& templatePath) { TrackedInfo trackedInfo; trackedInfo.name = name; Path nameAsPath; nameAsPath.set_file_path_from(unquote(name)); trackedInfo.contentPath = Path(contentDir + nameAsPath.dir, nameAsPath.file + contentExt); trackedInfo.outputPath = Path(outputDir + nameAsPath.dir, nameAsPath.file + outputExt); trackedInfo.title = title; trackedInfo.templatePath = templatePath; //checks for non-default extensions std::string inExt; Path extPath = trackedInfo.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".contExt"; if(file_exists(extPath.str())) { std::ifstream ifs(extPath.str()); getline(ifs, inExt); ifs.close(); trackedInfo.contentPath.file = trackedInfo.contentPath.file.substr(0, trackedInfo.contentPath.file.find_first_of('.')) + inExt; } extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".outputExt"; if(file_exists(extPath.str())) { std::ifstream ifs(extPath.str()); getline(ifs, inExt); ifs.close(); trackedInfo.outputPath.file = trackedInfo.outputPath.file.substr(0, trackedInfo.outputPath.file.find_first_of('.')) + inExt; } return trackedInfo; } TrackedInfo make_info(const Name& name, const Title& title, const Path& templatePath, const Directory& contentDir, const Directory& outputDir, const std::string& contentExt, const std::string& outputExt) { TrackedInfo trackedInfo; trackedInfo.name = name; Path nameAsPath; nameAsPath.set_file_path_from(unquote(name)); trackedInfo.contentPath = Path(contentDir + nameAsPath.dir, nameAsPath.file + contentExt); trackedInfo.outputPath = Path(outputDir + nameAsPath.dir, nameAsPath.file + outputExt); trackedInfo.title = title; trackedInfo.templatePath = templatePath; return trackedInfo; } TrackedInfo ProjectInfo::get_info(const Name& name) { TrackedInfo trackedInfo; trackedInfo.name = name; auto result = trackedAll.find(trackedInfo); if(result != trackedAll.end()) return *result; trackedInfo.name = "##not-found##"; return trackedInfo; } int ProjectInfo::info(const std::vector<Name>& names) { std::cout << c_light_blue << promptStr << c_white << "info on specified names:" << std::endl; for(auto name=names.begin(); name!=names.end(); name++) { if(name != names.begin()) std::cout << std::endl; TrackedInfo cInfo; cInfo.name = *name; if(trackedAll.count(cInfo)) { cInfo = *(trackedAll.find(cInfo)); std::cout << " name: " << c_green << quote(cInfo.name) << c_white << std::endl; std::cout << " title: " << cInfo.title << std::endl; std::cout << " output path: " << cInfo.outputPath << std::endl; std::cout << " output ext: " << quote(get_output_ext(cInfo)) << std::endl; std::cout << " content path: " << cInfo.contentPath << std::endl; std::cout << " content ext: " << quote(get_cont_ext(cInfo)) << std::endl; std::cout << " script ext: " << quote(get_script_ext(cInfo)) << std::endl; std::cout << "template path: " << cInfo.templatePath << std::endl; } else std::cout << "Nift is not tracking " << *name << std::endl; } return 0; } int ProjectInfo::info_all() { if(file_exists(".nsm/.watchinfo/watching.list")) { WatchList wl; if(wl.open()) { start_err(std::cout) << "info-all: failed to open watch list" << std::endl; return 1; } std::cout << c_light_blue << promptStr << c_white << "all watched directories:" << std::endl; for(auto wd=wl.dirs.begin(); wd!=wl.dirs.end(); wd++) { if(wd != wl.dirs.begin()) std::cout << std::endl; std::cout << " watch directory: " << c_green << quote(wd->watchDir) << c_white << std::endl; for(auto ext=wd->contExts.begin(); ext!=wd->contExts.end(); ext++) { std::cout << "content extension: " << quote(*ext) << std::endl; std::cout << " template path: " << wd->templatePaths.at(*ext) << std::endl; std::cout << " output extension: " << wd->outputExts.at(*ext) << std::endl; } } } std::cout << c_light_blue << promptStr << c_white << "all tracked names:" << std::endl; for(auto trackedInfo=trackedAll.begin(); trackedInfo!=trackedAll.end(); trackedInfo++) { if(trackedInfo != trackedAll.begin()) std::cout << std::endl; std::cout << " name: " << c_green << quote(trackedInfo->name) << c_white << std::endl; std::cout << " title: " << trackedInfo->title << std::endl; std::cout << " output path: " << trackedInfo->outputPath << std::endl; std::cout << " output ext: " << quote(get_output_ext(*trackedInfo)) << std::endl; std::cout << " content path: " << trackedInfo->contentPath << std::endl; std::cout << " content ext: " << quote(get_cont_ext(*trackedInfo)) << std::endl; std::cout << " script ext: " << quote(get_script_ext(*trackedInfo)) << std::endl; std::cout << "template path: " << trackedInfo->templatePath << std::endl; } return 0; } int ProjectInfo::info_names() { std::cout << c_light_blue << promptStr << c_white << "all tracked names:" << std::endl; for(auto trackedInfo=trackedAll.begin(); trackedInfo!=trackedAll.end(); trackedInfo++) std::cout << " " << c_green << trackedInfo->name << c_white << std::endl; return 0; } int ProjectInfo::info_tracking() { std::cout << c_light_blue << promptStr << c_white << "all tracked info:" << std::endl; for(auto trackedInfo=trackedAll.begin(); trackedInfo!=trackedAll.end(); trackedInfo++) { if(trackedInfo != trackedAll.begin()) std::cout << std::endl; std::cout << " name: " << c_green << quote(trackedInfo->name) << c_white << std::endl; std::cout << " title: " << trackedInfo->title << std::endl; std::cout << " output path: " << trackedInfo->outputPath << std::endl; std::cout << " output ext: " << quote(get_output_ext(*trackedInfo)) << std::endl; std::cout << " content path: " << trackedInfo->contentPath << std::endl; std::cout << " content ext: " << quote(get_cont_ext(*trackedInfo)) << std::endl; std::cout << " script ext: " << quote(get_script_ext(*trackedInfo)) << std::endl; std::cout << "template path: " << trackedInfo->templatePath << std::endl; } return 0; } int ProjectInfo::info_watching() { if(file_exists(".nsm/.watchinfo/watching.list")) { WatchList wl; if(wl.open()) { start_err(std::cout) << "info-watching: failed to open watch list" << std::endl; return 1; } std::cout << c_light_blue << promptStr << c_white << "all watched directories:" << std::endl; for(auto wd=wl.dirs.begin(); wd!=wl.dirs.end(); wd++) { if(wd != wl.dirs.begin()) std::cout << std::endl; std::cout << " watch directory: " << c_green << quote(wd->watchDir) << c_white << std::endl; for(auto ext=wd->contExts.begin(); ext!=wd->contExts.end(); ext++) { std::cout << "content extension: " << quote(*ext) << std::endl; std::cout << " template path: " << wd->templatePaths.at(*ext) << std::endl; std::cout << " output extension: " << wd->outputExts.at(*ext) << std::endl; } } } else { std::cout << "not watching any directories" << std::endl; } return 0; } int ProjectInfo::set_incr_mode(const std::string& modeStr) { if(modeStr == "mod") { if(incrMode == INCR_MOD) { start_err(std::cout) << "set_incr_mode: incremental mode is already " << quote(modeStr) << std::endl; return 1; } incrMode = INCR_MOD; int ret_val = remove_hash_files(); if(ret_val) return ret_val; } else if(modeStr == "hash") { if(incrMode == INCR_HASH) { start_err(std::cout) << "set_incr_mode: incremental mode is already " << quote(modeStr) << std::endl; return 1; } incrMode = INCR_HASH; } else if(modeStr == "hybrid") { if(incrMode == INCR_HYB) { start_err(std::cout) << "set_incr_mode: incremental mode is already " << quote(modeStr) << std::endl; return 1; } incrMode = INCR_HYB; } else { start_err(std::cout) << "set_incr_mode: do not recognise incremental mode " << quote(modeStr) << std::endl; return 1; } save_local_config(); std::cout << "successfully changed incremental mode to " << quote(modeStr) << std::endl; return 0; } int ProjectInfo::remove_hash_files() { open_tracking(1); std::cout << "removing hashes.." << std::endl; Path dep, infoPath; std::string str; for(auto cInfo=trackedAll.begin(); cInfo!=trackedAll.end(); ++cInfo) { //gets path of info file from last time output file was built infoPath = cInfo->outputPath.getInfoPath(); //checks whether info path exists if(file_exists(infoPath.str())) { std::ifstream infoStream(infoPath.str()); std::string timeDateLine; Name prevName; Title prevTitle; Path prevTemplatePath; // reads date/time, name, title and template path getline(infoStream, str); getline(infoStream, str); getline(infoStream, str); getline(infoStream, str); while(dep.read_file_path_from(infoStream)) { if(file_exists(dep.str())) { int ret_val = remove_path(dep.getHashPath()); if(ret_val) return ret_val; } } } } return 0; } std::string ProjectInfo::get_ext(const TrackedInfo& trackedInfo, const std::string& extType) { std::string ext; //checks for non-default extension Path extPath = trackedInfo.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + extType; if(file_exists(extPath.str())) { std::ifstream ifs(extPath.str()); getline(ifs, ext); ifs.close(); } else if(extType == ".contExt") ext = contentExt; else if(extType == ".outputExt") ext = outputExt; else if(extType == ".scriptExt") ext = scriptExt; return ext; } std::string ProjectInfo::get_cont_ext(const TrackedInfo& trackedInfo) { return get_ext(trackedInfo, ".contExt"); } std::string ProjectInfo::get_output_ext(const TrackedInfo& trackedInfo) { return get_ext(trackedInfo, ".outputExt"); } std::string ProjectInfo::get_script_ext(const TrackedInfo& trackedInfo) { return get_ext(trackedInfo, ".scriptExt"); } bool ProjectInfo::tracking(const TrackedInfo& trackedInfo) { return trackedAll.count(trackedInfo); } bool ProjectInfo::tracking(const Name& name) { TrackedInfo trackedInfo; trackedInfo.name = name; return trackedAll.count(trackedInfo); } int ProjectInfo::track(const Name& name, const Title& title, const Path& templatePath) { if(name.find('.') != std::string::npos) { start_err(std::cout, std::string("track")) << "names cannot contain '.'" << std::endl; std::cout << c_light_blue << "note: " << c_white << "you can add post-build scripts to move built/output files to paths containing . other than for extensions if you want" << std::endl; return 1; } else if(name == "" || title.str == "" || templatePath.str() == "") { start_err(std::cout, std::string("track")) << "name, title and template path must all be non-empty strings" << std::endl; return 1; } if(unquote(name)[unquote(name).size()-1] == '/' || unquote(name)[unquote(name).size()-1] == '\\') { start_err(std::cout, std::string("track")) << "name " << quote(name) << " cannot end in '/' or '\\'" << std::endl; return 1; } else if( (unquote(name).find('"') != std::string::npos && unquote(name).find('\'') != std::string::npos) || (unquote(title.str).find('"') != std::string::npos && unquote(title.str).find('\'') != std::string::npos) || (unquote(templatePath.str()).find('"') != std::string::npos && unquote(templatePath.str()).find('\'') != std::string::npos) ) { start_err(std::cout, std::string("track")) << "name, title and template path cannot contain both single and double quotes" << std::endl; return 1; } TrackedInfo newInfo = make_info(name, title, templatePath); if(newInfo.contentPath == newInfo.templatePath) { start_err(std::cout, std::string("track")) << "content and template paths cannot be the same, not tracked" << std::endl; return 1; } if(trackedAll.count(newInfo) > 0) { TrackedInfo cInfo = *(trackedAll.find(newInfo)); start_err(std::cout, std::string("track")) << "Nift is already tracking " << newInfo.outputPath << std::endl; std::cout << c_light_blue << promptStr << c_white << "current tracked details:" << std::endl; std::cout << " title: " << cInfo.title << std::endl; std::cout << " output path: " << cInfo.outputPath << std::endl; std::cout << " content path: " << cInfo.contentPath << std::endl; std::cout << "template path: " << cInfo.templatePath << std::endl; return 1; } //throws error if template path doesn't exist if(!file_exists(newInfo.templatePath.str())) { start_err(std::cout) << "template path " << newInfo.templatePath << " does not exist" << std::endl; return 1; } if(path_exists(newInfo.outputPath.str())) { start_err(std::cout) << "new output path " << newInfo.outputPath << " already exists" << std::endl; return 1; } if(!file_exists(newInfo.contentPath.str())) { newInfo.contentPath.ensureFileExists(); //chmod(newInfo.contentPath.str().c_str(), 0666); } //ensures directories for output file and info file exist //newInfo.outputPath.ensureDirExists(); //newInfo.outputPath.getInfoPath().ensureDirExists(); //inserts new info into set of trackedAll trackedAll.insert(newInfo); //saves new tracking list to .nsm/tracking.list save_tracking(); //informs user that addition was successful std::cout << "successfully tracking " << newInfo.name << std::endl; return 0; } int ProjectInfo::track_from_file(const std::string& filePath) { if(!file_exists(filePath)) { start_err(std::cout) << "track-from-file: track-file " << quote(filePath) << " does not exist" << std::endl; return 1; } Name name; Title title; Path templatePath; std::string cExt, oExt, str; int noAdded = 0; std::ifstream ifs(filePath); std::vector<TrackedInfo> toTrackVec; TrackedInfo newInfo; while(getline(ifs, str)) { std::istringstream iss(str); name = ""; title.str = ""; cExt = ""; templatePath = Path("", ""); oExt = ""; if(read_quoted(iss, name)) if(read_quoted(iss, title.str)) if(read_quoted(iss, cExt)) if(templatePath.read_file_path_from(iss)) read_quoted(iss, oExt); if(name == "" || name[0] == '#') continue; if(title.str == "") title.str = name; if(cExt == "") cExt = contentExt; if(templatePath == Path("", "")) templatePath = defaultTemplate; if(oExt == "") oExt = outputExt; if(name.find('.') != std::string::npos) { start_err(std::cout) << "name " << quote(name) << " cannot contain '.'" << std::endl; std::cout << c_light_blue << "note: " << c_white << "you can add post-build scripts to move built built/output files to paths containing . other than for extensions if you want" << std::endl; return 1; } else if(name == "" || title.str == "" || cExt == "" || oExt == "") { start_err(std::cout) << "names, titles, content extensions and output extensions must all be non-empty strings" << std::endl; return 1; } if(unquote(name)[unquote(name).size()-1] == '/' || unquote(name)[unquote(name).size()-1] == '\\') { start_err(std::cout) << "name " << quote(name) << " cannot end in '/' or '\\'" << std::endl; return 1; } else if( (unquote(name).find('"') != std::string::npos && unquote(name).find('\'') != std::string::npos) || (unquote(title.str).find('"') != std::string::npos && unquote(title.str).find('\'') != std::string::npos) || (unquote(templatePath.str()).find('"') != std::string::npos && unquote(templatePath.str()).find('\'') != std::string::npos) ) { start_err(std::cout) << "names, titles and template paths cannot contain both single and double quotes" << std::endl; return 1; } if(cExt == "" || cExt[0] != '.') { start_err(std::cout) << "track-from-file: content extension " << quote(cExt) << " must start with a fullstop" << std::endl; return 1; } else if(oExt == "" || oExt[0] != '.') { start_err(std::cout) << "track-from-file: output extension " << quote(oExt) << " must start with a fullstop" << std::endl; return 1; } newInfo = make_info(name, title, templatePath); if(cExt != contentExt) newInfo.contentPath.file = newInfo.contentPath.file.substr(0, newInfo.contentPath.file.find_first_of('.')) + cExt; if(oExt != outputExt) newInfo.outputPath.file = newInfo.outputPath.file.substr(0, newInfo.outputPath.file.find_first_of('.')) + oExt; if(newInfo.contentPath == newInfo.templatePath) { start_err(std::cout) << "content and template paths cannot be the same, " << newInfo.name << " not tracked" << std::endl; return 1; } if(trackedAll.count(newInfo) > 0) { TrackedInfo cInfo = *(trackedAll.find(newInfo)); start_err(std::cout) << "Nift is already tracking " << newInfo.outputPath << std::endl; std::cout << c_light_blue << promptStr << c_white << "current tracked details:" << std::endl; std::cout << " title: " << cInfo.title << std::endl; std::cout << " output path: " << cInfo.outputPath << std::endl; std::cout << " content path: " << cInfo.contentPath << std::endl; std::cout << "template path: " << cInfo.templatePath << std::endl; return 1; } //throws error if template path doesn't exist bool blankTemplate = 0; if(newInfo.templatePath.str() == "") blankTemplate = 1; if(!blankTemplate && !file_exists(newInfo.templatePath.str())) { start_err(std::cout) << "template path " << newInfo.templatePath << " does not exist" << std::endl; return 1; } if(path_exists(newInfo.outputPath.str())) { start_err(std::cout) << "new output path " << newInfo.outputPath << " already exists" << std::endl; return 1; } toTrackVec.push_back(newInfo); } int pos; for(size_t i=0; i<toTrackVec.size(); i++) { newInfo = toTrackVec[i]; pos = newInfo.contentPath.file.find_first_of('.'); cExt = newInfo.contentPath.file.substr(pos, newInfo.contentPath.file.size() -1); pos = newInfo.outputPath.file.find_first_of('.'); oExt = newInfo.outputPath.file.substr(pos, newInfo.outputPath.file.size() -1); if(cExt != contentExt) { Path extPath = newInfo.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".contExt"; extPath.ensureFileExists(); std::ofstream ofs(extPath.str()); ofs << cExt << std::endl; ofs.close(); } if(oExt != outputExt) { Path extPath = newInfo.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".outputExt"; extPath.ensureFileExists(); std::ofstream ofs(extPath.str()); ofs << oExt << std::endl; ofs.close(); } if(!file_exists(newInfo.contentPath.str())) newInfo.contentPath.ensureFileExists(); //ensures directories for output file and info file exist //newInfo.outputPath.ensureDirExists(); //newInfo.outputPath.getInfoPath().ensureDirExists(); //inserts new info into trackedAll set trackedAll.insert(newInfo); noAdded++; } ifs.close(); //saves new tracking list to .nsm/tracking.list save_tracking(); std::cout << "successfully tracked: " << noAdded << std::endl; return 0; } int ProjectInfo::track_dir(const Path& dirPath, const std::string& cExt, const Path& templatePath, const std::string& oExt) { if(dirPath.file != "") { start_err(std::cout) << "track-dir: directory path " << dirPath << " is to a file not a directory" << std::endl; return 1; } else if(dirPath.comparableStr().substr(0, contentDir.size()) != contentDir) { start_err(std::cout) << "track-dir: cannot track files from directory " << dirPath << " as it is not a subdirectory of the project-wide content directory " << quote(contentDir) << std::endl; return 1; } else if(!dir_exists(dirPath.str())) { start_err(std::cout) << "track-dir: directory path " << dirPath << " does not exist" << std::endl; return 1; } if(cExt == "" || cExt[0] != '.') { start_err(std::cout) << "track-dir: content extension " << quote(cExt) << " must start with a fullstop" << std::endl; return 1; } else if(oExt == "" || oExt[0] != '.') { start_err(std::cout) << "track-dir: output extension " << quote(oExt) << " must start with a fullstop" << std::endl; return 1; } bool blankTemplate = 0; if(templatePath.str() == "") blankTemplate = 1; if(!blankTemplate && !file_exists(templatePath.str())) { start_err(std::cout) << "track-dir: template path " << templatePath << " does not exist" << std::endl; return 1; } std::vector<InfoToTrack> to_track; std::string ext; std::string contDir2dirPath = ""; if(comparable(dirPath.dir).size() > comparable(contentDir).size()) contDir2dirPath = dirPath.dir.substr(contentDir.size(), dirPath.dir.size()-contentDir.size()); Name name; size_t pos; std::vector<std::string> files = lsVec(dirPath.dir.c_str()); for(size_t f=0; f<files.size(); f++) { pos = files[f].find_first_of('.'); if(pos != std::string::npos) { ext = files[f].substr(pos, files[f].size()-pos); name = contDir2dirPath + files[f].substr(0, pos); if(cExt == ext) if(!tracking(name)) to_track.push_back(InfoToTrack(name, Title(name), templatePath, cExt, oExt)); } } if(to_track.size()) track(to_track); return 0; } int ProjectInfo::track(const Name& name, const Title& title, const Path& templatePath, const std::string& cExt, const std::string& oExt) { if(name.find('.') != std::string::npos) { start_err(std::cout) << "names cannot contain '.'" << std::endl; std::cout << c_light_blue << "note: " << c_white << "you can add post-build scripts to move built/output files to paths containing . other than for extensions if you want" << std::endl; return 1; } else if(name == "" || title.str == "" || cExt == "" || oExt == "") { start_err(std::cout) << "name, title, content extension and output extension must all be non-empty strings" << std::endl; return 1; } if(unquote(name)[unquote(name).size()-1] == '/' || unquote(name)[unquote(name).size()-1] == '\\') { start_err(std::cout) << "name " << quote(name) << " cannot end in '/' or '\\'" << std::endl; return 1; } else if( (unquote(name).find('"') != std::string::npos && unquote(name).find('\'') != std::string::npos) || (unquote(title.str).find('"') != std::string::npos && unquote(title.str).find('\'') != std::string::npos) || (unquote(templatePath.str()).find('"') != std::string::npos && unquote(templatePath.str()).find('\'') != std::string::npos) ) { start_err(std::cout) << "name, title and template path cannot contain both single and double quotes" << std::endl; return 1; } if(cExt == "" || cExt[0] != '.') { start_err(std::cout) << "track: content extension " << quote(cExt) << " must start with a fullstop" << std::endl; return 1; } else if(oExt == "" || oExt[0] != '.') { start_err(std::cout) << "track: output extension " << quote(oExt) << " must start with a fullstop" << std::endl; return 1; } TrackedInfo newInfo = make_info(name, title, templatePath); if(cExt != contentExt) newInfo.contentPath.file = newInfo.contentPath.file.substr(0, newInfo.contentPath.file.find_first_of('.')) + cExt; if(oExt != outputExt) newInfo.outputPath.file = newInfo.outputPath.file.substr(0, newInfo.outputPath.file.find_first_of('.')) + oExt; if(newInfo.contentPath == newInfo.templatePath) { start_err(std::cout) << "content and template paths cannot be the same, " << newInfo.name << " not tracked" << std::endl; return 1; } if(trackedAll.count(newInfo) > 0) { TrackedInfo cInfo = *(trackedAll.find(newInfo)); start_err(std::cout) << "Nift is already tracking " << newInfo.outputPath << std::endl; std::cout << c_light_blue << promptStr << c_white << "current tracked details:" << std::endl; std::cout << " title: " << cInfo.title << std::endl; std::cout << " output path: " << cInfo.outputPath << std::endl; std::cout << " content path: " << cInfo.contentPath << std::endl; std::cout << "template path: " << cInfo.templatePath << std::endl; return 1; } //throws error if template path doesn't exist bool blankTemplate = 0; if(newInfo.templatePath.str() == "") blankTemplate = 1; if(!blankTemplate && !file_exists(newInfo.templatePath.str())) { start_err(std::cout) << "template path " << newInfo.templatePath << " does not exist" << std::endl; return 1; } if(path_exists(newInfo.outputPath.str())) { start_err(std::cout) << "new output path " << newInfo.outputPath << " already exists" << std::endl; return 1; } if(cExt != contentExt) { Path extPath = newInfo.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".contExt"; extPath.ensureFileExists(); std::ofstream ofs(extPath.str()); ofs << cExt << std::endl; ofs.close(); } if(oExt != outputExt) { Path extPath = newInfo.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".outputExt"; extPath.ensureFileExists(); std::ofstream ofs(extPath.str()); ofs << oExt << std::endl; ofs.close(); } if(!file_exists(newInfo.contentPath.str())) { newInfo.contentPath.ensureFileExists(); //chmod(newInfo.contentPath.str().c_str(), 0666); } //ensures directories for output file and info file exist //newInfo.outputPath.ensureDirExists(); //newInfo.outputPath.getInfoPath().ensureDirExists(); //inserts new info into trackedAll set trackedAll.insert(newInfo); //saves new tracking list to .nsm/tracking.list save_tracking(); //informs user that addition was successful std::cout << "successfully tracking " << newInfo.name << std::endl; return 0; } int ProjectInfo::track(const std::vector<InfoToTrack>& toTrack) { Name name; Title title; Path templatePath; std::string cExt, oExt; for(size_t p=0; p<toTrack.size(); p++) { name = toTrack[p].name; title = toTrack[p].title; templatePath = toTrack[p].templatePath; cExt = toTrack[p].contExt; oExt = toTrack[p].outputExt; if(name.find('.') != std::string::npos) { start_err(std::cout) << "name " << quote(name) << " cannot contain '.'" << std::endl; std::cout << c_light_blue << "note: " << c_white << "you can add post-build scripts to move built/output files to paths containing . other than for extensions if you want" << std::endl; return 1; } else if(name == "" || title.str == "" || cExt == "" || oExt == "") { start_err(std::cout) << "names, titles, content extensions and output extensions must all be non-empty strings" << std::endl; return 1; } if(unquote(name)[unquote(name).size()-1] == '/' || unquote(name)[unquote(name).size()-1] == '\\') { start_err(std::cout) << "name " << quote(name) << " cannot end in '/' or '\\'" << std::endl; return 1; } else if( (unquote(name).find('"') != std::string::npos && unquote(name).find('\'') != std::string::npos) || (unquote(title.str).find('"') != std::string::npos && unquote(title.str).find('\'') != std::string::npos) || (unquote(templatePath.str()).find('"') != std::string::npos && unquote(templatePath.str()).find('\'') != std::string::npos) ) { start_err(std::cout) << "names, titles and template paths cannot contain both single and double quotes" << std::endl; return 1; } if(cExt == "" || cExt[0] != '.') { start_err(std::cout) << "track-dir: content extension " << quote(cExt) << " must start with a fullstop" << std::endl; return 1; } else if(oExt == "" || oExt[0] != '.') { start_err(std::cout) << "track-dir: output extension " << quote(oExt) << " must start with a fullstop" << std::endl; return 1; } TrackedInfo newInfo = make_info(name, title, templatePath); if(cExt != contentExt) newInfo.contentPath.file = newInfo.contentPath.file.substr(0, newInfo.contentPath.file.find_first_of('.')) + cExt; if(oExt != outputExt) newInfo.outputPath.file = newInfo.outputPath.file.substr(0, newInfo.outputPath.file.find_first_of('.')) + oExt; if(newInfo.contentPath == newInfo.templatePath) { start_err(std::cout) << "content and template paths cannot be the same, not tracked" << std::endl; return 1; } if(trackedAll.count(newInfo) > 0) { TrackedInfo cInfo = *(trackedAll.find(newInfo)); start_err(std::cout) << "Nift is already tracking " << newInfo.outputPath << std::endl; std::cout << c_light_blue << promptStr << c_white << "current tracked details:" << std::endl; std::cout << " title: " << cInfo.title << std::endl; std::cout << " output path: " << cInfo.outputPath << std::endl; std::cout << " content path: " << cInfo.contentPath << std::endl; std::cout << "template path: " << cInfo.templatePath << std::endl; return 1; } //throws error if template path doesn't exist bool blankTemplate = 0; if(newInfo.templatePath.str() == "") blankTemplate = 1; if(!blankTemplate && !file_exists(newInfo.templatePath.str())) { start_err(std::cout) << "template path " << newInfo.templatePath << " does not exist" << std::endl; return 1; } if(path_exists(newInfo.outputPath.str())) { start_err(std::cout) << "new output path " << newInfo.outputPath << " already exists" << std::endl; return 1; } } for(size_t p=0; p<toTrack.size(); p++) { name = toTrack[p].name; title = toTrack[p].title; templatePath = toTrack[p].templatePath; cExt = toTrack[p].contExt; oExt = toTrack[p].outputExt; TrackedInfo newInfo = make_info(name, title, templatePath); if(cExt != contentExt) { newInfo.contentPath.file = newInfo.contentPath.file.substr(0, newInfo.contentPath.file.find_first_of('.')) + cExt; Path extPath = newInfo.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".contExt"; extPath.ensureFileExists(); std::ofstream ofs(extPath.str()); ofs << cExt << std::endl; ofs.close(); } if(oExt != outputExt) { newInfo.outputPath.file = newInfo.outputPath.file.substr(0, newInfo.outputPath.file.find_first_of('.')) + oExt; Path extPath = newInfo.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".outputExt"; extPath.ensureFileExists(); std::ofstream ofs(extPath.str()); ofs << oExt << std::endl; ofs.close(); } if(!file_exists(newInfo.contentPath.str())) { newInfo.contentPath.ensureFileExists(); //chmod(newInfo.contentPath.str().c_str(), 0666); } //ensures directories for output file and info file exist //newInfo.outputPath.ensureDirExists(); //newInfo.outputPath.getInfoPath().ensureDirExists(); //inserts new info into trackedAll set trackedAll.insert(newInfo); //informs user that addition was successful std::cout << "successfully tracking " << newInfo.name << std::endl; } //saves new tracking list to .nsm/tracking.list save_tracking(); return 0; } int ProjectInfo::untrack(const Name& nameToUntrack) { //checks that name is being tracked if(!tracking(nameToUntrack)) { start_err(std::cout) << "Nift is not tracking " << nameToUntrack << std::endl; return 1; } TrackedInfo toErase = get_info(nameToUntrack); //removes the extension files if they exist Path extPath = toErase.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".contExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".outputExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".scriptExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } //removes info file and containing dirs if now empty if(file_exists(toErase.outputPath.getInfoPath().str())) { chmod(toErase.outputPath.getInfoPath().str().c_str(), 0666); remove_path(toErase.outputPath.getInfoPath()); } //removes output file and containing dirs if now empty if(file_exists(toErase.outputPath.str())) { chmod(toErase.outputPath.str().c_str(), 0666); remove_path(toErase.outputPath); } //removes info from trackedAll set trackedAll.erase(toErase); //saves new tracking list to .nsm/tracking.list save_tracking(); //informs user that name was successfully untracked std::cout << "successfully untracked " << nameToUntrack << std::endl; return 0; } int ProjectInfo::untrack(const std::vector<Name>& namesToUntrack) { TrackedInfo toErase; Path extPath; for(size_t p=0; p<namesToUntrack.size(); p++) { //checks that name is being tracked if(!tracking(namesToUntrack[p])) { start_err(std::cout) << "Nift is not tracking " << namesToUntrack[p] << std::endl; return 1; } } for(size_t p=0; p<namesToUntrack.size(); p++) { toErase = get_info(namesToUntrack[p]); //removes the extension files if they exist Path extPath = toErase.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".contExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".outputExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".scriptExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } //removes info file and containing dirs if now empty if(file_exists(toErase.outputPath.getInfoPath().str())) { chmod(toErase.outputPath.getInfoPath().str().c_str(), 0666); remove_path(toErase.outputPath.getInfoPath()); } //removes output file and containing dirs if now empty if(file_exists(toErase.outputPath.str())) { chmod(toErase.outputPath.str().c_str(), 0666); remove_path(toErase.outputPath); } //removes info from trackedAll set trackedAll.erase(toErase); //informs user that name was successfully untracked std::cout << "successfully untracked " << namesToUntrack[p] << std::endl; } //saves new tracking list to .nsm/tracking.list save_tracking(); return 0; } int ProjectInfo::untrack_from_file(const std::string& filePath) { if(!file_exists(filePath)) { start_err(std::cout) << "untrack-from-file: untrack-file " << quote(filePath) << " does not exist" << std::endl; return 1; } Name nameToUntrack; int noUntracked = 0; std::string str; std::ifstream ifs(filePath); std::vector<TrackedInfo> toEraseVec; while(getline(ifs, str)) { std::istringstream iss(str); read_quoted(iss, nameToUntrack); if(nameToUntrack == "" || nameToUntrack[0] == '#') continue; //checks that name is being tracked if(!tracking(nameToUntrack)) { start_err(std::cout) << "Nift is not tracking " << nameToUntrack << std::endl; return 1; } toEraseVec.push_back(get_info(nameToUntrack)); } TrackedInfo toErase; for(size_t i=0; i<toEraseVec.size(); i++) { toErase = toEraseVec[i]; //removes the extension files if they exist Path extPath = toErase.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".contExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".outputExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".scriptExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } //removes info file and containing dirs if now empty if(file_exists(toErase.outputPath.getInfoPath().str())) { chmod(toErase.outputPath.getInfoPath().str().c_str(), 0666); remove_path(toErase.outputPath.getInfoPath()); } //removes output file and containing dirs if now empty if(file_exists(toErase.outputPath.str())) { chmod(toErase.outputPath.str().c_str(), 0666); remove_path(toErase.outputPath); } //removes info from trackedAll set trackedAll.erase(toErase); noUntracked++; } ifs.close(); //saves new tracking list to .nsm/tracking.list save_tracking(); std::cout << "successfully untracked count: " << noUntracked << std::endl; return 0; } int ProjectInfo::untrack_dir(const Path& dirPath, const std::string& cExt) { if(dirPath.file != "") { start_err(std::cout) << "untrack-dir: directory path " << dirPath << " is to a file not a directory" << std::endl; return 1; } else if(dirPath.comparableStr().substr(0, contentDir.size()) != contentDir) { start_err(std::cout) << "untrack-dir: cannot untrack from directory " << dirPath << " as it is not a subdirectory of the project-wide content directory " << quote(contentDir) << std::endl; return 1; } else if(!dir_exists(dirPath.str())) { start_err(std::cout) << "untrack-dir: directory path " << dirPath << " does not exist" << std::endl; return 1; } if(cExt == "" || cExt[0] != '.') { start_err(std::cout) << "untrack-dir: content extension " << quote(cExt) << " must start with a fullstop" << std::endl; return 1; } std::vector<Name> namesToUntrack; std::string ext; std::string contDir2dirPath = ""; if(comparable(dirPath.dir).size() > comparable(contentDir).size()) contDir2dirPath = dirPath.dir.substr(contentDir.size(), dirPath.dir.size()-contentDir.size()); Name name; size_t pos; std::vector<std::string> files = lsVec(dirPath.dir.c_str()); for(size_t f=0; f<files.size(); f++) { pos = files[f].find_first_of('.'); if(pos != std::string::npos) { ext = files[f].substr(pos, files[f].size()-pos); name = contDir2dirPath + files[f].substr(0, pos); if(cExt == ext) if(tracking(name)) namesToUntrack.push_back(name); } } if(namesToUntrack.size()) untrack(namesToUntrack); return 0; } int ProjectInfo::rm_from_file(const std::string& filePath) { if(!file_exists(filePath)) { start_err(std::cout) << "rm-from-file: rm-file " << quote(filePath) << " does not exist" << std::endl; return 1; } Name nameToRemove; int noRemoved = 0; std::string str; std::ifstream ifs(filePath); std::vector<TrackedInfo> toEraseVec; while(getline(ifs, str)) { std::istringstream iss(str); read_quoted(iss, nameToRemove); if(nameToRemove == "" || nameToRemove[0] == '#') continue; //checks that name is being tracked if(!tracking(nameToRemove)) { start_err(std::cout) << "Nift is not tracking " << nameToRemove << std::endl; return 1; } toEraseVec.push_back(get_info(nameToRemove)); } TrackedInfo toErase; for(size_t i=0; i<toEraseVec.size(); i++) { toErase = toEraseVec[i]; //removes the extension files if they exist Path extPath = toErase.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".contExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".outputExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".scriptExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } //removes info file and containing dirs if now empty if(file_exists(toErase.outputPath.getInfoPath().str())) { chmod(toErase.outputPath.getInfoPath().str().c_str(), 0666); remove_path(toErase.outputPath.getInfoPath()); } //removes output file and containing dirs if now empty if(file_exists(toErase.outputPath.str())) { chmod(toErase.outputPath.str().c_str(), 0666); remove_path(toErase.outputPath); } //removes content file and containing dirs if now empty if(file_exists(toErase.contentPath.str())) { chmod(toErase.contentPath.str().c_str(), 0666); remove_path(toErase.contentPath); } //removes toErase from trackedAll set trackedAll.erase(toErase); noRemoved++; } ifs.close(); //saves new tracking list to .nsm/tracking.list save_tracking(); std::cout << "successfully removed: " << noRemoved << std::endl; return 0; } int ProjectInfo::rm_dir(const Path& dirPath, const std::string& cExt) { if(dirPath.file != "") { start_err(std::cout) << "rm-dir: directory path " << dirPath << " is to a file not a directory" << std::endl; return 1; } else if(dirPath.comparableStr().substr(0, contentDir.size()) != contentDir) { start_err(std::cout) << "rm-dir: cannot remove from directory " << dirPath << " as it is not a subdirectory of the project-wide content directory " << quote(contentDir) << std::endl; return 1; } else if(!dir_exists(dirPath.str())) { start_err(std::cout) << "rm-dir: directory path " << dirPath << " does not exist" << std::endl; return 1; } if(cExt == "" || cExt[0] != '.') { start_err(std::cout) << "rm-dir: content extension " << quote(cExt) << " must start with a fullstop" << std::endl; return 1; } std::vector<Name> namesToRemove; std::string ext; std::string contDir2dirPath = ""; if(comparable(dirPath.dir).size() > comparable(contentDir).size()) contDir2dirPath = dirPath.dir.substr(contentDir.size(), dirPath.dir.size()-contentDir.size()); Name name; size_t pos; std::vector<std::string> files = lsVec(dirPath.dir.c_str()); for(size_t f=0; f<files.size(); f++) { pos = files[f].find_first_of('.'); if(pos != std::string::npos) { ext = files[f].substr(pos, files[f].size()-pos); name = contDir2dirPath + files[f].substr(0, pos); if(cExt == ext) if(tracking(name)) namesToRemove.push_back(name); } } if(namesToRemove.size()) rm(namesToRemove); return 0; } int ProjectInfo::rm(const Name& nameToRemove) { //checks that name is being tracked if(!tracking(nameToRemove)) { start_err(std::cout) << "Nift is not tracking " << nameToRemove << std::endl; return 1; } TrackedInfo toErase = get_info(nameToRemove); //removes the extension files if they exist Path extPath = toErase.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".contExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".outputExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".scriptExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } //removes info file and containing dirs if now empty if(file_exists(toErase.outputPath.getInfoPath().str())) { chmod(toErase.outputPath.getInfoPath().str().c_str(), 0666); remove_path(toErase.outputPath.getInfoPath()); } //removes output file and containing dirs if now empty if(file_exists(toErase.outputPath.str())) { chmod(toErase.outputPath.str().c_str(), 0666); remove_path(toErase.outputPath); } //removes content file and containing dirs if now empty if(file_exists(toErase.contentPath.str())) { chmod(toErase.contentPath.str().c_str(), 0666); remove_path(toErase.contentPath); } //removes info from trackedAll set trackedAll.erase(toErase); //saves new tracking list to .nsm/tracking.list save_tracking(); //informs user that removal was successful std::cout << "successfully removed " << nameToRemove << std::endl; return 0; } int ProjectInfo::rm(const std::vector<Name>& namesToRemove) { TrackedInfo toErase; Path extPath; for(size_t p=0; p<namesToRemove.size(); p++) { //checks that name is being tracked if(!tracking(namesToRemove[p])) { start_err(std::cout) << "Nift is not tracking " << namesToRemove[p] << std::endl; return 1; } } for(size_t p=0; p<namesToRemove.size(); p++) { toErase = get_info(namesToRemove[p]); //removes the extension files if they exist extPath = toErase.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".contExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".outputExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".scriptExt"; if(file_exists(extPath.str())) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } //removes info file and containing dirs if now empty if(file_exists(toErase.outputPath.getInfoPath().str())) { chmod(toErase.outputPath.getInfoPath().str().c_str(), 0666); remove_path(toErase.outputPath.getInfoPath()); } //removes output file and containing dirs if now empty if(file_exists(toErase.outputPath.str())) { chmod(toErase.outputPath.str().c_str(), 0666); remove_path(toErase.outputPath); } //removes content file and containing dirs if now empty if(file_exists(toErase.contentPath.str())) { chmod(toErase.contentPath.str().c_str(), 0666); remove_path(toErase.contentPath); } //removes info from trackedAll set trackedAll.erase(toErase); //informs user that toErase was successfully removed std::cout << "successfully removed " << namesToRemove[p] << std::endl; } //saves new tracking list to .nsm/tracking.list save_tracking(); return 0; } int ProjectInfo::mv(const Name& oldName, const Name& newName) { if(newName.find('.') != std::string::npos) { start_err(std::cout) << "new name cannot contain '.'" << std::endl; return 1; } else if(newName == "") { start_err(std::cout) << "new name must be a non-empty string" << std::endl; return 1; } else if(unquote(newName).find('"') != std::string::npos && unquote(newName).find('\'') != std::string::npos) { start_err(std::cout) << "new name cannot contain both single and double quotes" << std::endl; return 1; } else if(!tracking(oldName)) //checks old name is being tracked { start_err(std::cout) << "Nift is not tracking " << oldName << std::endl; return 1; } else if(tracking(newName)) //checks new name isn't already tracked { start_err(std::cout) << "Nift is already tracking " << newName << std::endl; return 1; } TrackedInfo oldInfo = get_info(oldName); Path oldExtPath = oldInfo.outputPath.getInfoPath(); std::string cContExt = contentExt, cOutputExt = outputExt; oldExtPath.file = oldExtPath.file.substr(0, oldExtPath.file.find_first_of('.')) + ".contExt"; if(file_exists(oldExtPath.str())) { std::ifstream ifs(oldExtPath.str()); getline(ifs, cContExt); ifs.close(); } oldExtPath.file = oldExtPath.file.substr(0, oldExtPath.file.find_first_of('.')) + ".outputExt"; if(file_exists(oldExtPath.str())) { std::ifstream ifs(oldExtPath.str()); getline(ifs, cOutputExt); ifs.close(); } TrackedInfo newInfo; newInfo.name = newName; newInfo.contentPath.set_file_path_from(contentDir + newName + cContExt); newInfo.outputPath.set_file_path_from(outputDir + newName + cOutputExt); if(get_title(oldInfo.name) == oldInfo.title.str) newInfo.title = get_title(newName); else newInfo.title = oldInfo.title; newInfo.templatePath = oldInfo.templatePath; if(path_exists(newInfo.contentPath.str())) { start_err(std::cout) << "new content path " << newInfo.contentPath << " already exists" << std::endl; return 1; } else if(path_exists(newInfo.outputPath.str())) { start_err(std::cout) << "new output path " << newInfo.outputPath << " already exists" << std::endl; return 1; } //moves content file newInfo.contentPath.ensureDirExists(); if(rename(oldInfo.contentPath.str().c_str(), newInfo.contentPath.str().c_str())) { start_err(std::cout) << "mv: failed to move " << oldInfo.contentPath << " to " << newInfo.contentPath << std::endl; return 1; } //moves extension files if they exist Path newExtPath = newInfo.outputPath.getInfoPath(); oldExtPath.file = oldExtPath.file.substr(0, oldExtPath.file.find_first_of('.')) + ".contExt"; if(file_exists(oldExtPath.str())) { newExtPath.file = newExtPath.file.substr(0, newExtPath.file.find_first_of('.')) + ".contExt"; newExtPath.ensureDirExists(); chmod(oldExtPath.str().c_str(), 0666); if(rename(oldExtPath.str().c_str(), newExtPath.str().c_str())) { start_err(std::cout) << "mv: failed to move " << oldExtPath << " to " << newExtPath << std::endl; return 1; } } oldExtPath.file = oldExtPath.file.substr(0, oldExtPath.file.find_first_of('.')) + ".outputExt"; if(file_exists(oldExtPath.str())) { newExtPath.file = newExtPath.file.substr(0, newExtPath.file.find_first_of('.')) + ".outputExt"; newExtPath.ensureDirExists(); chmod(oldExtPath.str().c_str(), 0666); if(rename(oldExtPath.str().c_str(), newExtPath.str().c_str())) { start_err(std::cout) << "mv: failed to move " << oldExtPath << " to " << newExtPath << std::endl; return 1; } } oldExtPath.file = oldExtPath.file.substr(0, oldExtPath.file.find_first_of('.')) + ".scriptExt"; if(file_exists(oldExtPath.str())) { newExtPath.file = newExtPath.file.substr(0, newExtPath.file.find_first_of('.')) + ".scriptExt"; newExtPath.ensureDirExists(); chmod(oldExtPath.str().c_str(), 0666); if(rename(oldExtPath.str().c_str(), newExtPath.str().c_str())) { start_err(std::cout) << "mv: failed to move " << oldExtPath << " to " << newExtPath << std::endl; return 1; } } //removes info file and containing dirs if now empty if(file_exists(oldInfo.outputPath.getInfoPath().str())) { chmod(oldInfo.outputPath.getInfoPath().str().c_str(), 0666); remove_path(oldInfo.outputPath.getInfoPath()); } //removes output file and containing dirs if now empty if(file_exists(oldInfo.outputPath.str())) { chmod(oldInfo.outputPath.str().c_str(), 0666); remove_path(oldInfo.outputPath); } //removes oldInfo from trackedAll trackedAll.erase(oldInfo); //adds newInfo to trackedAll trackedAll.insert(newInfo); //saves new tracking list to .nsm/tracking.list save_tracking(); //informs user that name was successfully moved std::cout << "successfully moved " << oldName << " to " << newName << std::endl; return 0; } int ProjectInfo::cp(const Name& trackedName, const Name& newName) { if(newName.find('.') != std::string::npos) { start_err(std::cout) << "new name cannot contain '.'" << std::endl; return 1; } else if(newName == "") { start_err(std::cout) << "new name must be a non-empty string" << std::endl; return 1; } else if(unquote(newName).find('"') != std::string::npos && unquote(newName).find('\'') != std::string::npos) { start_err(std::cout) << "new name cannot contain both single and double quotes" << std::endl; return 1; } else if(!tracking(trackedName)) //checks old name is being tracked { start_err(std::cout) << "Nift is not tracking " << trackedName << std::endl; return 1; } else if(tracking(newName)) //checks new name isn't already tracked { start_err(std::cout) << "Nift is already tracking " << newName << std::endl; return 1; } TrackedInfo trackedInfo = get_info(trackedName); Path oldExtPath = trackedInfo.outputPath.getInfoPath(); std::string cContExt = contentExt, cOutputExt = outputExt; oldExtPath.file = oldExtPath.file.substr(0, oldExtPath.file.find_first_of('.')) + ".contExt"; if(file_exists(oldExtPath.str())) { std::ifstream ifs(oldExtPath.str()); getline(ifs, cContExt); ifs.close(); } oldExtPath.file = oldExtPath.file.substr(0, oldExtPath.file.find_first_of('.')) + ".outputExt"; if(file_exists(oldExtPath.str())) { std::ifstream ifs(oldExtPath.str()); getline(ifs, cOutputExt); ifs.close(); } TrackedInfo newInfo; newInfo.name = newName; newInfo.contentPath.set_file_path_from(contentDir + newName + cContExt); newInfo.outputPath.set_file_path_from(outputDir + newName + cOutputExt); if(get_title(trackedInfo.name) == trackedInfo.title.str) newInfo.title = get_title(newName); else newInfo.title = trackedInfo.title; newInfo.templatePath = trackedInfo.templatePath; if(path_exists(newInfo.contentPath.str())) { start_err(std::cout) << "new content path " << newInfo.contentPath << " already exists" << std::endl; return 1; } else if(path_exists(newInfo.outputPath.str())) { start_err(std::cout) << "new output path " << newInfo.outputPath << " already exists" << std::endl; return 1; } //copies content file std::mutex os_mtx; Path emptyPath("", ""); if(cpFile(trackedInfo.contentPath.str(), newInfo.contentPath.str(), -1, emptyPath, std::cout, 0, &os_mtx)) { start_err(std::cout) << "cp: failed to copy " << trackedInfo.contentPath << " to " << newInfo.contentPath << std::endl; return 1; } //copies extension files if they exist Path newExtPath = newInfo.outputPath.getInfoPath(); oldExtPath.file = oldExtPath.file.substr(0, oldExtPath.file.find_first_of('.')) + ".contExt"; if(file_exists(oldExtPath.str())) { newExtPath.file = newExtPath.file.substr(0, newExtPath.file.find_first_of('.')) + ".contExt"; newExtPath.ensureDirExists(); if(cpFile(oldExtPath.str(), newExtPath.str(), -1, emptyPath, std::cout, 0, &os_mtx)) { start_err(std::cout) << "cp: failed to copy " << oldExtPath << " to " << newExtPath << std::endl; return 1; } chmod(newExtPath.str().c_str(), 0444); } oldExtPath.file = oldExtPath.file.substr(0, oldExtPath.file.find_first_of('.')) + ".outputExt"; if(file_exists(oldExtPath.str())) { newExtPath.file = newExtPath.file.substr(0, newExtPath.file.find_first_of('.')) + ".outputExt"; newExtPath.ensureDirExists(); if(cpFile(oldExtPath.str(), newExtPath.str(), -1, emptyPath, std::cout, 0, &os_mtx)) { start_err(std::cout) << "cp: failed to copy " << oldExtPath << " to " << newExtPath << std::endl; return 1; } chmod(newExtPath.str().c_str(), 0444); } oldExtPath.file = oldExtPath.file.substr(0, oldExtPath.file.find_first_of('.')) + ".scriptExt"; if(file_exists(oldExtPath.str())) { newExtPath.file = newExtPath.file.substr(0, newExtPath.file.find_first_of('.')) + ".scriptExt"; newExtPath.ensureDirExists(); if(cpFile(oldExtPath.str(), newExtPath.str(), -1, emptyPath, std::cout, 0, &os_mtx)) { start_err(std::cout) << "cp: failed to copy " << oldExtPath << " to " << newExtPath << std::endl; return 1; } chmod(newExtPath.str().c_str(), 0444); } //adds newInfo to trackedAll trackedAll.insert(newInfo); //saves new tracking list to .nsm/tracking.list save_tracking(); //informs user that name was successfully moved std::cout << "successfully copied " << trackedName << " to " << newName << std::endl; return 0; } int ProjectInfo::new_title(const Name& name, const Title& newTitle) { if(newTitle.str == "") { start_err(std::cout) << "new title must be a non-empty string" << std::endl; return 1; } else if(unquote(newTitle.str).find('"') != std::string::npos && unquote(newTitle.str).find('\'') != std::string::npos) { start_err(std::cout) << "new title cannot contain both single and double quotes" << std::endl; return 1; } TrackedInfo cInfo; cInfo.name = name; if(trackedAll.count(cInfo)) { cInfo = *(trackedAll.find(cInfo)); trackedAll.erase(cInfo); cInfo.title = newTitle; trackedAll.insert(cInfo); //saves new tracking list to .nsm/tracking.list save_tracking(); //informs user that title was successfully changed std::cout << "successfully changed title to " << quote(newTitle.str) << std::endl; } else { start_err(std::cout) << "Nift is not tracking " << quote(name) << std::endl; return 1; } return 0; } int ProjectInfo::new_template(const Path& newTemplatePath) { bool blankTemplate = 0; if(newTemplatePath == Path("", "")) blankTemplate = 1; else if(unquote(newTemplatePath.str()).find('"') != std::string::npos && unquote(newTemplatePath.str()).find('\'') != std::string::npos) { start_err(std::cout) << "new template path cannot contain both single and double quotes" << std::endl; return 1; } else if(defaultTemplate == newTemplatePath) { start_err(std::cout) << "default template path is already " << defaultTemplate << std::endl; return 1; } Name name; Title title; Path oldTemplatePath; rename(".nsm/tracking.list", ".nsm/tracking.list-old"); std::ifstream ifs(".nsm/tracking.list-old"); std::ofstream ofs(".nsm/tracking.list"); while(read_quoted(ifs, name)) { title.read_quoted_from(ifs); oldTemplatePath.read_file_path_from(ifs); ofs << quote(name) << std::endl; ofs << title << std::endl; if(oldTemplatePath == defaultTemplate) ofs << newTemplatePath << std::endl << std::endl; else ofs << oldTemplatePath << std::endl << std::endl; } ifs.close(); ofs.close(); remove_file(Path(".nsm/", "tracking.list-old")); //sets new template defaultTemplate = newTemplatePath; //saves new default template to Nift config file save_local_config(); //warns user if new template path doesn't exist if(!blankTemplate && !file_exists(newTemplatePath.str())) std::cout << "warning: new template path " << newTemplatePath << " does not exist" << std::endl; std::cout << "successfully changed default template to " << newTemplatePath << std::endl; return 0; } int ProjectInfo::new_template(const Name& name, const Path& newTemplatePath) { bool blankTemplate = 0; if(newTemplatePath == Path("", "")) blankTemplate = 1; else if(unquote(newTemplatePath.str()).find('"') != std::string::npos && unquote(newTemplatePath.str()).find('\'') != std::string::npos) { start_err(std::cout) << "new template path cannot contain both single and double quotes" << std::endl; return 1; } TrackedInfo cInfo; cInfo.name = name; if(trackedAll.count(cInfo)) { cInfo = *(trackedAll.find(cInfo)); if(cInfo.templatePath == newTemplatePath) { start_err(std::cout) << "template path for " << name << " is already " << newTemplatePath << std::endl; return 1; } trackedAll.erase(cInfo); cInfo.templatePath = newTemplatePath; trackedAll.insert(cInfo); //saves new tracking list to .nsm/tracking.list save_tracking(); //warns user if new template path doesn't exist if(!blankTemplate && !file_exists(newTemplatePath.str())) std::cout << "warning: new template path " << newTemplatePath << " does not exist" << std::endl; } else { start_err(std::cout) << "Nift is not tracking " << name << std::endl; return 1; } return 0; } int ProjectInfo::new_output_dir(const Directory& newOutputDir) { if(newOutputDir == "") { start_err(std::cout) << "new output directory cannot be the empty string" << std::endl; return 1; } else if(unquote(newOutputDir).find('"') != std::string::npos && unquote(newOutputDir).find('\'') != std::string::npos) { start_err(std::cout) << "new output directory cannot contain both single and double quotes" << std::endl; return 1; } if(newOutputDir[newOutputDir.size()-1] != '/' && newOutputDir[newOutputDir.size()-1] != '\\') { start_err(std::cout) << "new output directory should end in \\ or /" << std::endl; return 1; } if(newOutputDir == outputDir) { start_err(std::cout) << "output directory is already " << quote(newOutputDir) << std::endl; return 1; } if(path_exists(newOutputDir) || path_exists(newOutputDir.substr(0, newOutputDir.size()-1))) { start_err(std::cout) << "new output directory location " << quote(newOutputDir) << " already exists" << std::endl; return 1; } std::string newInfoDir = ".nsm/" + newOutputDir; if(path_exists(newInfoDir) || path_exists(newInfoDir.substr(0, newInfoDir.size()-1))) { start_err(std::cout) << "new info directory location " << quote(newInfoDir) << " already exists" << std::endl; return 1; } std::string parDir = "../", rootDir = "/", projectRootDir = get_pwd(), pwd = get_pwd(); int ret_val = chdir(outputDir.c_str()); if(ret_val) { start_err(std::cout) << "new_output_dir(" << quote(newOutputDir) << "): failed to change directory to " << quote(outputDir) << " from " << quote(get_pwd()) << std::endl; return ret_val; } ret_val = chdir(parDir.c_str()); if(ret_val) { start_err(std::cout) << "new_output_dir(" << quote(newOutputDir) << "): failed to change directory to " << quote(parDir) << " from " << quote(get_pwd()) << std::endl; return ret_val; } std::string delDir = get_pwd(); ret_val = chdir(projectRootDir.c_str()); if(ret_val) { start_err(std::cout) << "new_output_dir(" << quote(newOutputDir) << "): failed to change directory to " << quote(projectRootDir) << " from " << quote(get_pwd()) << std::endl; return ret_val; } //moves output directory to temp location rename(outputDir.c_str(), ".temp_output_dir"); //ensures new output directory exists Path(newOutputDir, Filename("")).ensureDirExists(); //moves output directory to final location rename(".temp_output_dir", newOutputDir.c_str()); //deletes any remaining empty directories if(remove_path(Path(delDir, ""))) { start_err(std::cout) << "new_output_dir(" << quote(newOutputDir) << "): failed to remove " << quote(delDir) << std::endl; return 1; } //changes back to project root directory ret_val = chdir(projectRootDir.c_str()); if(ret_val) { start_err(std::cout) << "new_output_dir(" << quote(newOutputDir) << "): failed to change directory to " << quote(projectRootDir) << " from " << quote(get_pwd()) << std::endl; return ret_val; } ret_val = chdir((".nsm/" + outputDir).c_str()); if(ret_val) { start_err(std::cout) << "new_output_dir(" << quote(newOutputDir) << "): failed to change directory to " << quote(".nsm/" + outputDir) << " from " << quote(get_pwd()) << std::endl; return ret_val; } ret_val = chdir(parDir.c_str()); if(ret_val) { start_err(std::cout) << "new_output_dir(" << quote(newOutputDir) << "): failed to change directory to " << quote(parDir) << " from " << quote(get_pwd()) << std::endl; return ret_val; } delDir = get_pwd(); ret_val = chdir(projectRootDir.c_str()); if(ret_val) { start_err(std::cout) << "new_output_dir(" << quote(newOutputDir) << "): failed to change directory to " << quote(projectRootDir) << " from " << quote(get_pwd()) << std::endl; return ret_val; } //moves old info directory to temp location rename((".nsm/" + outputDir).c_str(), ".temp_info_dir"); //ensures new info directory exists Path(".nsm/" + newOutputDir, Filename("")).ensureDirExists(); //moves old info directory to final location rename(".temp_info_dir", (".nsm/" + newOutputDir).c_str()); //deletes any remaining empty directories if(remove_path(Path(delDir, ""))) { start_err(std::cout) << "new_output_dir(" << quote(newOutputDir) << "): failed to remove " << quote(delDir) << std::endl; return 1; } //changes back to project root directory ret_val = chdir(projectRootDir.c_str()); if(ret_val) { start_err(std::cout) << "new_output_dir(" << quote(newOutputDir) << "): failed to change directory to " << quote(projectRootDir) << " from " << quote(get_pwd()) << std::endl; return ret_val; } //sets new output directory outputDir = newOutputDir; //saves new output directory to Nift config file save_local_config(); std::cout << "successfully changed output directory to " << quote(newOutputDir) << std::endl; return 0; } int ProjectInfo::new_content_dir(const Directory& newContDir) { if(newContDir == "") { start_err(std::cout) << "new content directory cannot be the empty string" << std::endl; return 1; } else if(unquote(newContDir).find('"') != std::string::npos && unquote(newContDir).find('\'') != std::string::npos) { start_err(std::cout) << "new content directory cannot contain both single and double quotes" << std::endl; return 1; } if(newContDir[newContDir.size()-1] != '/' && newContDir[newContDir.size()-1] != '\\') { start_err(std::cout) << "new content directory should end in \\ or /" << std::endl; return 1; } if(newContDir == contentDir) { start_err(std::cout) << "content directory is already " << quote(newContDir) << std::endl; return 1; } if(path_exists(newContDir) || path_exists(newContDir.substr(0, newContDir.size()-1))) { start_err(std::cout) << "new content directory location " << quote(newContDir) << " already exists" << std::endl; return 1; } std::string parDir = "../", rootDir = "/", projectRootDir = get_pwd(), pwd = get_pwd(); int ret_val = chdir(contentDir.c_str()); if(ret_val) { start_err(std::cout) << "new_content_dir(" << quote(newContDir) << "): failed to change directory to " << quote(contentDir) << " from " << quote(get_pwd()) << std::endl; return ret_val; } ret_val = chdir(parDir.c_str()); if(ret_val) { start_err(std::cout) << "new_content_dir(" << quote(newContDir) << "): failed to change directory to " << quote(parDir) << " from " << quote(get_pwd()) << std::endl; return ret_val; } std::string delDir = get_pwd(); ret_val = chdir(projectRootDir.c_str()); if(ret_val) { start_err(std::cout) << "new_content_dir(" << quote(newContDir) << "): failed to change directory to " << quote(projectRootDir) << " from " << quote(get_pwd()) << std::endl; return ret_val; } //moves content directory to temp location rename(contentDir.c_str(), ".temp_content_dir"); //ensures new content directory exists Path(newContDir, Filename("")).ensureDirExists(); //moves content directory to final location rename(".temp_content_dir", newContDir.c_str()); //deletes any remaining empty directories if(remove_path(Path(delDir, ""))) { start_err(std::cout) << "new_content_dir(" << quote(newContDir) << "): failed to remove " << quote(delDir) << std::endl; return 1; } //changes back to project root directory ret_val = chdir(projectRootDir.c_str()); if(ret_val) { start_err(std::cout) << "new_content_dir(" << quote(newContDir) << "): failed to change directory to " << quote(projectRootDir) << " from " << quote(get_pwd()) << std::endl; return ret_val; } //sets new content directory contentDir = newContDir; //saves new content directory to Nift config file save_local_config(); std::cout << "successfully changed content directory to " << quote(newContDir) << std::endl; return 0; } int ProjectInfo::new_content_ext(const std::string& newExt) { if(newExt == "" || newExt[0] != '.') { start_err(std::cout) << "content extension must start with a fullstop" << std::endl; return 1; } if(newExt == contentExt) { start_err(std::cout) << "content extension is already " << quote(contentExt) << std::endl; return 1; } Path newContPath, extPath; for(auto trackedInfo=trackedAll.begin(); trackedInfo!=trackedAll.end(); trackedInfo++) { newContPath = trackedInfo->contentPath; newContPath.file = newContPath.file.substr(0, newContPath.file.find_first_of('.')) + newExt; if(path_exists(newContPath.str())) { start_err(std::cout) << "new content path " << newContPath << " already exists" << std::endl; return 1; } } for(auto trackedInfo=trackedAll.begin(); trackedInfo!=trackedAll.end(); trackedInfo++) { //checks for non-default content extension extPath = trackedInfo->outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".contExt"; if(file_exists(extPath.str())) { std::ifstream ifs(extPath.str()); std::string oldExt; read_quoted(ifs, oldExt); ifs.close(); if(oldExt == newExt) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } } else { //moves the content file if(file_exists(trackedInfo->contentPath.str())) //should we throw an error here if it doesn't exit? { newContPath = trackedInfo->contentPath; newContPath.file = newContPath.file.substr(0, newContPath.file.find_first_of('.')) + newExt; if(newContPath.str() != trackedInfo->contentPath.str()) rename(trackedInfo->contentPath.str().c_str(), newContPath.str().c_str()); } } } contentExt = newExt; save_local_config(); //informs user that content extension was successfully changed std::cout << "successfully changed content extension to " << quote(newExt) << std::endl; return 0; } int ProjectInfo::new_content_ext(const Name& name, const std::string& newExt) { if(newExt == "" || newExt[0] != '.') { start_err(std::cout) << "content extension must start with a fullstop" << std::endl; return 1; } TrackedInfo cInfo = get_info(name); Path newContPath, extPath; std::string oldExt; int pos; if(trackedAll.count(cInfo)) { pos = cInfo.contentPath.file.find_first_of('.'); oldExt = cInfo.contentPath.file.substr(pos, cInfo.contentPath.file.size() - pos); if(oldExt == newExt) { start_err(std::cout) << "content extension for " << quote(name) << " is already " << quote(oldExt) << std::endl; return 1; } //throws error if new content file already exists newContPath = cInfo.contentPath; newContPath.file = newContPath.file.substr(0, newContPath.file.find_first_of('.')) + newExt; if(path_exists(newContPath.str())) { start_err(std::cout) << "new content path " << newContPath << " already exists" << std::endl; return 1; } //moves the content file if(file_exists(cInfo.contentPath.str())) { if(newContPath.str() != cInfo.contentPath.str()) rename(cInfo.contentPath.str().c_str(), newContPath.str().c_str()); } extPath = cInfo.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".contExt"; if(newExt != contentExt) { //makes sure we can write to ext file chmod(extPath.str().c_str(), 0644); extPath.ensureFileExists(); std::ofstream ofs(extPath.str()); ofs << newExt << "\n"; ofs.close(); //makes sure user can't edit ext file chmod(extPath.str().c_str(), 0444); } else { chmod(extPath.str().c_str(), 0644); if(file_exists(extPath.str()) && remove_path(extPath)) { start_err(std::cout) << "faield to remove content extension path " << extPath << std::endl; return 1; } } } else { start_err(std::cout) << "Nift is not tracking " << quote(name) << std::endl; return 1; } return 0; } int ProjectInfo::new_output_ext(const std::string& newExt) { if(newExt == "" || newExt[0] != '.') { start_err(std::cout) << "output extension must start with a fullstop" << std::endl; return 1; } if(newExt == outputExt) { start_err(std::cout) << "output extension is already " << quote(outputExt) << std::endl; return 1; } Path newOutputPath, extPath; for(auto trackedInfo=trackedAll.begin(); trackedInfo!=trackedAll.end(); trackedInfo++) { newOutputPath = trackedInfo->outputPath; newOutputPath.file = newOutputPath.file.substr(0, newOutputPath.file.find_first_of('.')) + newExt; if(path_exists(newOutputPath.str())) { start_err(std::cout) << "new output path " << newOutputPath << " already exists" << std::endl; return 1; } } for(auto trackedInfo=trackedAll.begin(); trackedInfo!=trackedAll.end(); trackedInfo++) { //checks for non-default output extension extPath = trackedInfo->outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".outputExt"; if(file_exists(extPath.str())) { std::ifstream ifs(extPath.str()); std::string oldExt; read_quoted(ifs, oldExt); ifs.close(); if(oldExt == newExt) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } } else { //moves the output file if(file_exists(trackedInfo->outputPath.str())) { newOutputPath = trackedInfo->outputPath; newOutputPath.file = newOutputPath.file.substr(0, newOutputPath.file.find_first_of('.')) + newExt; if(newOutputPath.str() != trackedInfo->outputPath.str()) rename(trackedInfo->outputPath.str().c_str(), newOutputPath.str().c_str()); } } } outputExt = newExt; save_local_config(); //informs user that output extension was successfully changed std::cout << "successfully changed output extension to " << quote(newExt) << std::endl; return 0; } int ProjectInfo::new_output_ext(const Name& name, const std::string& newExt) { if(newExt == "" || newExt[0] != '.') { start_err(std::cout) << "output extension must start with a fullstop" << std::endl; return 1; } TrackedInfo cInfo = get_info(name); Path newOutputPath, extPath; std::string oldExt; int pos; if(trackedAll.count(cInfo)) { //checks for non-default output extension pos = cInfo.outputPath.file.find_first_of('.'); oldExt = cInfo.outputPath.file.substr(pos, cInfo.outputPath.file.size() - pos); if(oldExt == newExt) { start_err(std::cout) << "output extension for " << quote(name) << " is already " << quote(oldExt) << std::endl; return 1; } //throws error if new output file already exists newOutputPath = cInfo.outputPath; newOutputPath.file = newOutputPath.file.substr(0, newOutputPath.file.find_first_of('.')) + newExt; if(path_exists(newOutputPath.str())) { start_err(std::cout) << "new output path " << newOutputPath << " already exists" << std::endl; return 1; } //moves the output file if(file_exists(cInfo.outputPath.str())) { if(newOutputPath.str() != cInfo.outputPath.str()) rename(cInfo.outputPath.str().c_str(), newOutputPath.str().c_str()); } extPath = cInfo.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".outputExt"; if(newExt != outputExt) { //makes sure we can write to ext file chmod(extPath.str().c_str(), 0644); extPath.ensureFileExists(); std::ofstream ofs(extPath.str()); ofs << newExt << "\n"; ofs.close(); //makes sure user can't edit ext file chmod(extPath.str().c_str(), 0444); } else { chmod(extPath.str().c_str(), 0644); if(file_exists(extPath.str()) && remove_path(extPath)) { start_err(std::cout) << "faield to remove output extension path " << extPath << std::endl; return 1; } } } else { start_err(std::cout) << "Nift is not tracking " << quote(name) << std::endl; return 1; } return 0; } int ProjectInfo::new_script_ext(const std::string& newExt) { if(newExt != "" && newExt[0] != '.') { start_err(std::cout) << "non-empty script extension must start with a fullstop" << std::endl; return 1; } if(newExt == scriptExt) { start_err(std::cout) << "script extension is already " << quote(scriptExt) << std::endl; return 1; } Path extPath; for(auto trackedInfo=trackedAll.begin(); trackedInfo!=trackedAll.end(); trackedInfo++) { //checks for non-default script extension extPath = trackedInfo->outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".scriptExt"; if(file_exists(extPath.str())) { std::ifstream ifs(extPath.str()); std::string oldExt; read_quoted(ifs, oldExt); ifs.close(); if(oldExt == newExt) { chmod(extPath.str().c_str(), 0666); remove_path(extPath); } } } scriptExt = newExt; save_local_config(); //informs user that script extension was successfully changed std::cout << "successfully changed script extension to " << quote(newExt) << std::endl; return 0; } int ProjectInfo::new_script_ext(const Name& name, const std::string& newExt) { if(newExt != "" && newExt[0] != '.') { start_err(std::cout) << "non-empty script extension must start with a fullstop" << std::endl; return 1; } TrackedInfo cInfo = get_info(name); Path extPath; std::string oldExt; if(trackedAll.count(cInfo)) { extPath = cInfo.outputPath.getInfoPath(); extPath.file = extPath.file.substr(0, extPath.file.find_first_of('.')) + ".scriptExt"; if(file_exists(extPath.str())) { std::ifstream ifs(extPath.str()); getline(ifs, oldExt); ifs.close(); } else oldExt = scriptExt; if(oldExt == newExt) { start_err(std::cout) << "script extension for " << quote(name) << " is already " << quote(oldExt) << std::endl; return 1; } if(newExt != scriptExt) { //makes sure we can write to ext file chmod(extPath.str().c_str(), 0644); extPath.ensureFileExists(); std::ofstream ofs(extPath.str()); ofs << newExt << "\n"; ofs.close(); //makes sure user can't edit ext file chmod(extPath.str().c_str(), 0444); } else { chmod(extPath.str().c_str(), 0644); if(file_exists(extPath.str()) && remove_path(extPath)) { start_err(std::cout) << "faield to remove script extension path " << extPath << std::endl; return 1; } } } else { start_err(std::cout) << "Nift is not tracking " << quote(name) << std::endl; return 1; } return 0; } int ProjectInfo::no_build_threads(int no_threads) { if(no_threads == 0) { start_err(std::cout) << "number of build threads must be a non-zero integer (use negative numbers for a multiple of the number of cores on the machine)" << std::endl; return 1; } if(no_threads == buildThreads) { start_err(std::cout) << "number of build threads is already " << buildThreads << std::endl; return 1; } buildThreads = no_threads; save_local_config(); if(buildThreads < 0) std::cout << "successfully changed number of build threads to " << no_threads << " (" << -buildThreads*std::thread::hardware_concurrency() << " on this machine)" << std::endl; else std::cout << "successfully changed number of build threads to " << no_threads << std::endl; return 0; } int ProjectInfo::no_paginate_threads(int no_threads) { if(no_threads == 0) { start_err(std::cout) << "number of paginate threads must be a non-zero integer (use negative numbers for a multiple of the number of cores on the machine)" << std::endl; return 1; } if(no_threads == paginateThreads) { start_err(std::cout) << "number of paginate threads is already " << paginateThreads << std::endl; return 1; } paginateThreads = no_threads; save_local_config(); if(paginateThreads < 0) std::cout << "successfully changed number of paginate threads to " << no_threads << " (" << -paginateThreads*std::thread::hardware_concurrency() << " on this machine)" << std::endl; else std::cout << "successfully changed number of paginate threads to " << no_threads << std::endl; return 0; } int ProjectInfo::check_watch_dirs() { if(file_exists(".nsm/.watchinfo/watching.list")) { WatchList wl; if(wl.open()) { start_err(std::cout) << "failed to open watch list '.nsm/.watchinfo/watching.list'" << std::endl; return 1; } for(auto wd=wl.dirs.begin(); wd!=wl.dirs.end(); wd++) { std::string file, watchDirFilesStr = ".nsm/.watchinfo/" + strip_trailing_slash(wd->watchDir) + ".tracked"; TrackedInfo cInfo; //can delete this later std::string watchDirFilesStrOld = ".nsm/.watchinfo/" + replace_slashes(wd->watchDir) + ".tracked"; if(file_exists(watchDirFilesStrOld)) { Path(watchDirFilesStr).ensureDirExists(); if(rename(watchDirFilesStrOld.c_str(), watchDirFilesStr.c_str())) { start_err(std::cout) << "failed to rename " << quote(watchDirFilesStrOld) << " to " << quote(watchDirFilesStr) << std::endl; return 1; } } std::ifstream ifs(watchDirFilesStr); std::vector<Name> namesToRemove; while(read_quoted(ifs, file)) { cInfo = get_info(file); if(cInfo.name != "##not-found##") if(!file_exists(cInfo.contentPath.str())) namesToRemove.push_back(file); } ifs.close(); if(namesToRemove.size()) rm(namesToRemove); std::vector<InfoToTrack> to_track; std::set<Name> names_tracked; std::string ext; Name name; size_t pos; std::vector<std::string> files = lsVec(wd->watchDir.c_str()); for(size_t f=0; f<files.size(); f++) { pos = files[f].find_first_of('.'); if(pos != std::string::npos) { ext = files[f].substr(pos, files[f].size()-pos); if(wd->watchDir.size() == contentDir.size()) name = files[f].substr(0, pos); else name = wd->watchDir.substr(contentDir.size(), wd->watchDir.size()-contentDir.size()) + files[f].substr(0, pos); if(wd->contExts.count(ext)) //we are watching the extension { if(names_tracked.count(name)) { start_err(std::cout) << "watch: two content files with name '" << name << "', one with extension " << quote(ext) << std::endl; return 1; } if(!tracking(name)) to_track.push_back(InfoToTrack(name, Title(name), wd->templatePaths.at(ext), ext, wd->outputExts.at(ext))); names_tracked.insert(name); } } } if(to_track.size()) if(track(to_track)) return 1; //makes sure we can write to watchDir tracked file chmod(watchDirFilesStr.c_str(), 0644); std::ofstream ofs(watchDirFilesStr); for(auto tracked_name=names_tracked.begin(); tracked_name != names_tracked.end(); tracked_name++) ofs << quote(*tracked_name) << std::endl; ofs.close(); //makes sure user can't accidentally write to watchDir tracked file chmod(watchDirFilesStr.c_str(), 0444); } } return 0; } std::mutex os_mtx; std::mutex fail_mtx, built_mtx, set_mtx; std::set<Name> failedNames, builtNames; std::set<TrackedInfo>::iterator nextInfo; Timer timer; std::atomic<int> counter, noFinished, noPagesToBuild, noPagesFinished; std::atomic<double> estNoPagesFinished; std::atomic<int> cPhase; const int DUMMY_PHASE = 1; const int UPDATE_PHASE = 2; const int BUILD_PHASE = 3; const int END_PHASE = 4; void build_progress(const int& no_to_build, const int& addBuildStatus) { if(!addBuildStatus) return; #if defined __NO_PROGRESS__ return; #endif int phaseToCheck = cPhase; int total_no_to_build, no_to_build_length, cFinished; while(1) { os_mtx.lock(); total_no_to_build = no_to_build + noPagesToBuild; no_to_build_length = std::to_string(total_no_to_build).size(); cFinished = noFinished + estNoPagesFinished; if(cPhase != phaseToCheck || cFinished >= total_no_to_build) { os_mtx.unlock(); break; } clear_console_line(); double cTime = timer.getTime(); std::string remStr = int_to_timestr(cTime*(double)total_no_to_build/(double)(cFinished+1) - cTime); size_t cWidth = console_width(); if(19 + 2*no_to_build_length + remStr.size() <= cWidth) { if(cFinished < total_no_to_build) std::cout << c_light_blue << "progress: " << c_white << cFinished << "/" << total_no_to_build << " " << (100*cFinished)/total_no_to_build << "% (" << remStr << ")"; } else if(17 + remStr.size() <= cWidth) { if(cFinished < total_no_to_build) std::cout << c_light_blue << "progress: " << c_white << (100*cFinished)/total_no_to_build << "% (" << remStr << ")"; } else if(9 + remStr.size() <= cWidth) { if(cFinished < total_no_to_build) std::cout << c_light_blue << ": " << c_white << (100*cFinished)/total_no_to_build << "% (" << remStr << ")"; } else if(4 <= cWidth) { if(cFinished < total_no_to_build) std::cout << c_light_blue << (100*cFinished)/total_no_to_build << "%" << c_white; } //std::cout << std::flush; if(addBuildStatus == 1) { std::fflush(stdout); usleep(200000); } else { std::cout << std::endl; usleep(990000); } //usleep(2000000); //usleep(200000); clear_console_line(); os_mtx.unlock(); //usleep(4000000); usleep(10000); } } std::atomic<size_t> paginationCounter; void pagination_thread(const Pagination& pagesInfo, const std::string& paginateName, const std::string& outputExt, const Path& mainOutputPath) { std::string pageStr; size_t cPageNo; while(1) { cPageNo = paginationCounter++; if(cPageNo >= pagesInfo.noPages) break; std::istringstream iss(pagesInfo.pages[cPageNo]); std::string issLine; int fileLineNo = 0; pageStr = pagesInfo.splitFile.first; while(!iss.eof()) { getline(iss, issLine); if(0 < fileLineNo++) pageStr += "\n" + pagesInfo.indentAmount; pageStr += issLine; } pageStr += pagesInfo.splitFile.second; Path outputPath = mainOutputPath; if(cPageNo) outputPath.file = paginateName + std::to_string(cPageNo+1) + outputExt; chmod(outputPath.str().c_str(), 0666); //removing file here gives significant speed improvements //same improvements NOT observed for output files or info files at scale //not sure why! remove_file(outputPath); std::ofstream ofs(outputPath.str()); ofs << pageStr << "\n"; ofs.close(); chmod(outputPath.str().c_str(), 0444); estNoPagesFinished = estNoPagesFinished + 0.55; noPagesFinished++; } } void build_thread(std::ostream& eos, const int& no_paginate_threads, std::set<TrackedInfo>* trackedAll, const int& no_to_build, const Directory& ContentDir, const Directory& OutputDir, const std::string& ContentExt, const std::string& OutputExt, const std::string& ScriptExt, const Path& DefaultTemplate, const bool& BackupScripts, const std::string& UnixTextEditor, const std::string& WinTextEditor) { Parser parser(trackedAll, &os_mtx, ContentDir, OutputDir, ContentExt, OutputExt, ScriptExt, DefaultTemplate, BackupScripts, UnixTextEditor, WinTextEditor); std::set<TrackedInfo>::iterator cInfo; while(counter < no_to_build) { set_mtx.lock(); if(counter >= no_to_build) { set_mtx.unlock(); return; } counter++; cInfo = nextInfo++; set_mtx.unlock(); int result = parser.build(*cInfo, estNoPagesFinished, noPagesToBuild, eos); //more pagination here parser.pagesInfo.noPages = parser.pagesInfo.pages.size(); if(parser.pagesInfo.noPages) { Path outputPathBackup = parser.toBuild.outputPath; std::string innerPageStr; std::set<Path> antiDepsOfReadPath; for(size_t p=0; p<parser.pagesInfo.noPages; ++p) { if(p) parser.toBuild.outputPath.file = parser.pagesInfo.paginateName + std::to_string(p+1) + parser.outputExt; antiDepsOfReadPath.clear(); parser.pagesInfo.cPageNo = p+1; innerPageStr = parser.pagesInfo.templateStr; result = parser.parse_replace('n', innerPageStr, "pagination template string", parser.pagesInfo.callPath, antiDepsOfReadPath, parser.pagesInfo.templateLineNo, "paginate.template", parser.pagesInfo.templateCallLineNo, eos); if(result) { if(!parser.consoleLocked) parser.os_mtx->lock(); start_err(eos, parser.pagesInfo.callPath, parser.pagesInfo.callLineNo) << "paginate: failed here" << std::endl; parser.os_mtx->unlock(); break; } parser.pagesInfo.pages[p] = innerPageStr; estNoPagesFinished = estNoPagesFinished + 0.4; } //pagination threads std::vector<std::thread> threads; for(int i=0; i<no_paginate_threads; i++) threads.push_back(std::thread(pagination_thread, parser.pagesInfo, parser.pagesInfo.paginateName, parser.outputExt, outputPathBackup)); for(int i=0; i<no_paginate_threads; i++) threads[i].join(); } if(result) { fail_mtx.lock(); failedNames.insert(cInfo->name); fail_mtx.unlock(); } else { built_mtx.lock(); builtNames.insert(cInfo->name); built_mtx.unlock(); } noFinished++; } } /*int ProjectInfo::build_untracked(std::ostream& os, const int& addBuildStatus, const std::set<TrackedInfo> infoToBuild) { }*/ int ProjectInfo::build_names(std::ostream& os, const int& addBuildStatus, const std::vector<Name>& namesToBuild) { if(check_watch_dirs()) return 1; std::set<Name> untrackedNames, failedNames; std::set<TrackedInfo> trackedInfoToBuild; for(auto name=namesToBuild.begin(); name != namesToBuild.end(); ++name) { if(tracking(*name)) trackedInfoToBuild.insert(get_info(*name)); else untrackedNames.insert(*name); } Parser parser(&trackedAll, &os_mtx, contentDir, outputDir, contentExt, outputExt, scriptExt, defaultTemplate, backupScripts, unixTextEditor, winTextEditor); //checks for pre-build scripts if(parser.run_script(os, Path("", "pre-build" + scriptExt), backupScripts, 1)) return 1; nextInfo = trackedInfoToBuild.begin(); counter = noFinished = estNoPagesFinished = noPagesFinished = 0; os_mtx.lock(); if(addBuildStatus) // should we check if os is std::cout? clear_console_line(); os << "building files.." << std::endl; os_mtx.unlock(); if(addBuildStatus) timer.start(); int no_threads; if(buildThreads < 0) no_threads = -buildThreads*std::thread::hardware_concurrency(); else no_threads = buildThreads; int no_paginate_threads; if(paginateThreads < 0) no_paginate_threads = -paginateThreads*std::thread::hardware_concurrency(); else no_paginate_threads = paginateThreads; setIncrMode(incrMode); std::vector<std::thread> threads; for(int i=0; i<no_threads; i++) threads.push_back(std::thread(build_thread, std::ref(std::cout), no_paginate_threads, &trackedAll, trackedInfoToBuild.size(), contentDir, outputDir, contentExt, outputExt, scriptExt, defaultTemplate, backupScripts, unixTextEditor, winTextEditor)); cPhase = BUILD_PHASE; std::thread thrd(build_progress, trackedInfoToBuild.size(), addBuildStatus); for(int i=0; i<no_threads; i++) threads[i].join(); cPhase = END_PHASE; thrd.detach(); //can't lock console here because it gets stalled from build_progress if(addBuildStatus) clear_console_line(); if(failedNames.size() || untrackedNames.size()) { if(noPagesFinished) os << "paginated files: " << noPagesFinished << std::endl; if(builtNames.size() == 1) os << builtNames.size() << " specified file built successfully" << std::endl; else os << builtNames.size() << " specified files built successfully" << std::endl; } if(failedNames.size()) { size_t noToDisplay = std::max(5, -5 + (int)console_height()); os << c_light_blue << promptStr << c_white << "failed to build:" << std::endl; if(failedNames.size() < noToDisplay) { for(auto fName=failedNames.begin(); fName != failedNames.end(); fName++) os << " " << c_red << *fName << c_white << std::endl; } else { size_t x=0; for(auto fName=failedNames.begin(); x < noToDisplay; fName++, x++) os << " " << c_red << *fName << c_white << std::endl; os << " and " << failedNames.size() - noToDisplay << " more" << std::endl; } } if(untrackedNames.size()) { size_t noToDisplay = std::max(5, -5 + (int)console_height()); os << c_light_blue << promptStr << c_white << "not tracking:" << std::endl; if(untrackedNames.size() < noToDisplay) { for(auto uName=untrackedNames.begin(); uName != untrackedNames.end(); uName++) os << " " << c_red << *uName << c_white << std::endl; } else { size_t x=0; for(auto uName=untrackedNames.begin(); x < noToDisplay; uName++, x++) os << " " << c_red << *uName << c_white << std::endl; os << " and " << untrackedNames.size() - noToDisplay << " more" << std::endl; } } if(failedNames.size() == 0 && untrackedNames.size() == 0) { #if defined __APPLE__ || defined __linux__ const std::string pkgStr = "📦 "; #else //*nix const std::string pkgStr = ":: "; #endif if(noPagesFinished) os << "paginated files: " << noPagesFinished << std::endl; std::cout << c_light_blue << pkgStr << c_white << "all " << namesToBuild.size() << " specified files built successfully" << std::endl; //checks for post-build scripts if(parser.run_script(os, Path("", "post-build" + scriptExt), backupScripts, 1)) return 1; } return 0; } int ProjectInfo::build_all(std::ostream& os, const int& addBuildStatus) { if(check_watch_dirs()) return 1; if(trackedAll.size() == 0) { std::cout << "Nift does not have anything tracked" << std::endl; return 0; } Parser parser(&trackedAll, &os_mtx, contentDir, outputDir, contentExt, outputExt, scriptExt, defaultTemplate, backupScripts, unixTextEditor, winTextEditor); //checks for pre-build scripts if(parser.run_script(os, Path("", "pre-build" + scriptExt), backupScripts, 1)) return 1; nextInfo = trackedAll.begin(); counter = noFinished = estNoPagesFinished = noPagesFinished = 0; os_mtx.lock(); if(addBuildStatus) clear_console_line(); std::cout << "building project.." << std::endl; os_mtx.unlock(); if(addBuildStatus) timer.start(); int no_threads; if(buildThreads < 0) no_threads = -buildThreads*std::thread::hardware_concurrency(); else no_threads = buildThreads; int no_paginate_threads; if(paginateThreads < 0) no_paginate_threads = -paginateThreads*std::thread::hardware_concurrency(); else no_paginate_threads = paginateThreads; setIncrMode(incrMode); std::vector<std::thread> threads; for(int i=0; i<no_threads; i++) threads.push_back(std::thread(build_thread, std::ref(std::cout), no_paginate_threads, &trackedAll, trackedAll.size(), contentDir, outputDir, contentExt, outputExt, scriptExt, defaultTemplate, backupScripts, unixTextEditor, winTextEditor)); cPhase = BUILD_PHASE; std::thread thrd(build_progress, trackedAll.size(), addBuildStatus); for(int i=0; i<no_threads; i++) threads[i].join(); cPhase = END_PHASE; thrd.detach(); //can't lock console here because it gets stalled from build_progress if(addBuildStatus) clear_console_line(); if(failedNames.size() > 0) { if(noPagesFinished) os << "paginated files: " << noPagesFinished << std::endl; if(builtNames.size() == 1) os << builtNames.size() << " file built successfully" << std::endl; else os << builtNames.size() << " files built successfully" << std::endl; size_t noToDisplay = std::max(5, -5 + (int)console_height()); os << c_light_blue << promptStr << c_white << "failed to build:" << std::endl; if(failedNames.size() < noToDisplay) { for(auto fName=failedNames.begin(); fName != failedNames.end(); fName++) os << " " << c_red << *fName << c_white << std::endl; } else { size_t x=0; for(auto fName=failedNames.begin(); x < noToDisplay; fName++, x++) os << " " << c_red << *fName << c_white << std::endl; os << " and " << failedNames.size() - noToDisplay << " more" << std::endl; } } else { #if defined __APPLE__ || defined __linux__ const std::string pkgStr = "📦 "; #else //*nix const std::string pkgStr = ":: "; #endif if(noPagesFinished) os << "paginated files: " << noPagesFinished << std::endl; os << c_light_blue << pkgStr << c_white << "all " << noFinished << " tracked files built successfully" << std::endl; //checks for post-build scripts if(parser.run_script(os, Path("", "post-build" + scriptExt), backupScripts, 1)) return 1; } return 0; } std::mutex problem_mtx, updated_mtx, mod_hash_mtx, modified_mtx, removed_mtx; std::set<Name> problemNames; std::set<TrackedInfo> updatedInfo; std::set<Path> modifiedFiles, removedFiles; void dep_thread(std::ostream& os, const bool& addExpl, const int& incrMode, const int& no_to_check, const Directory& contentDir, const Directory& outputDir, const std::string& contentExt, const std::string& outputExt) { std::set<TrackedInfo>::iterator cInfo; while(counter < no_to_check) { set_mtx.lock(); if(counter >= no_to_check) { set_mtx.unlock(); return; } counter++; cInfo = nextInfo++; set_mtx.unlock(); //checks whether content and template files exist if(!file_exists(cInfo->contentPath.str())) { if(addExpl) { os_mtx.lock(); os << cInfo->name << ": content file " << cInfo->contentPath << " does not exist" << std::endl; os_mtx.unlock(); } problem_mtx.lock(); problemNames.insert(cInfo->name); problem_mtx.unlock(); continue; } if(!file_exists(cInfo->templatePath.str())) { if(addExpl) { os_mtx.lock(); os << cInfo->name << ": template file " << cInfo->templatePath << " does not exist" << std::endl; os_mtx.unlock(); } problem_mtx.lock(); problemNames.insert(cInfo->name); problem_mtx.unlock(); continue; } //gets path of info file from last time output file was built Path infoPath = cInfo->outputPath.getInfoPath(); //checks whether info path exists if(!file_exists(infoPath.str())) { if(addExpl) { os_mtx.lock(); os << cInfo->outputPath << ": yet to be built" << std::endl; os_mtx.unlock(); } updated_mtx.lock(); updatedInfo.insert(*cInfo); updated_mtx.unlock(); continue; } else { std::ifstream infoStream(infoPath.str()); std::string timeDateLine; Name prevName; Title prevTitle; Path prevTemplatePath; getline(infoStream, timeDateLine); read_quoted(infoStream, prevName); prevTitle.read_quoted_from(infoStream); prevTemplatePath.read_file_path_from(infoStream); TrackedInfo prevInfo = make_info(prevName, prevTitle, prevTemplatePath, contentDir, outputDir, contentExt, outputExt); //note we haven't checked for non-default content/output extension, pretty sure we don't need to here if(cInfo->name != prevInfo.name) { if(addExpl) { os_mtx.lock(); os << cInfo->outputPath << ": name changed to " << cInfo->name << " from " << prevInfo.name << std::endl; os_mtx.unlock(); } updated_mtx.lock(); updatedInfo.insert(*cInfo); updated_mtx.unlock(); continue; } if(cInfo->title != prevInfo.title) { if(addExpl) { os_mtx.lock(); os << cInfo->outputPath << ": title changed to " << cInfo->title << " from " << prevInfo.title << std::endl; os_mtx.unlock(); } updated_mtx.lock(); updatedInfo.insert(*cInfo); updated_mtx.unlock(); continue; } if(cInfo->templatePath != prevInfo.templatePath) { if(addExpl) { os_mtx.lock(); os << cInfo->outputPath << ": template path changed to " << cInfo->templatePath << " from " << prevInfo.templatePath << std::endl; os_mtx.unlock(); } updated_mtx.lock(); updatedInfo.insert(*cInfo); updated_mtx.unlock(); continue; } Path dep; while(dep.read_file_path_from(infoStream)) { if(!file_exists(dep.str())) { if(addExpl) { os_mtx.lock(); os << cInfo->outputPath << ": dep path " << dep << " removed since last build" << std::endl; os_mtx.unlock(); } removed_mtx.lock(); removedFiles.insert(dep); removed_mtx.unlock(); updated_mtx.lock(); updatedInfo.insert(*cInfo); updated_mtx.unlock(); break; } else if(incrMode != INCR_HASH && dep.modified_after(infoPath)) { if(addExpl) { os_mtx.lock(); os << cInfo->outputPath << ": dep path " << dep << " modified since last build" << std::endl; os_mtx.unlock(); } modified_mtx.lock(); modifiedFiles.insert(dep); modified_mtx.unlock(); updated_mtx.lock(); updatedInfo.insert(*cInfo); updated_mtx.unlock(); break; } else if(incrMode != INCR_MOD) { //gets path of info file from last time output file was built Path hashPath = dep.getHashPath(); std::string hashPathStr = hashPath.str(); if(!file_exists(hashPathStr)) { if(addExpl) { os_mtx.lock(); os << cInfo->outputPath << ": " << "hash file " << hashPath << " does not exist" << std::endl; os_mtx.unlock(); } updated_mtx.lock(); updatedInfo.insert(*cInfo); updated_mtx.unlock(); break; } else if((unsigned) std::atoi(string_from_file(hashPathStr).c_str()) != FNVHash(string_from_file(dep.str()))) { if(addExpl) { os_mtx.lock(); os << cInfo->outputPath << ": dep path " << dep << " modified since last build" << std::endl; os_mtx.unlock(); } modified_mtx.lock(); modifiedFiles.insert(dep); modified_mtx.unlock(); updated_mtx.lock(); updatedInfo.insert(*cInfo); updated_mtx.unlock(); break; } } } infoStream.close(); //checks for user-defined dependencies Path depsPath = cInfo->contentPath; depsPath.file = depsPath.file.substr(0, depsPath.file.find_first_of('.')) + ".deps"; if(file_exists(depsPath.str())) { std::ifstream depsFile(depsPath.str()); while(dep.read_file_path_from(depsFile)) { if(!path_exists(dep.str())) { if(addExpl) { os_mtx.lock(); os << cInfo->outputPath << ": user defined dep path " << dep << " does not exist" << std::endl; os_mtx.unlock(); } removed_mtx.lock(); removedFiles.insert(dep); removed_mtx.unlock(); updated_mtx.lock(); updatedInfo.insert(*cInfo); updated_mtx.unlock(); break; } else if(dep.modified_after(infoPath)) { if(addExpl) { os_mtx.lock(); os << cInfo->outputPath << ": user defined dep path " << dep << " modified since last build" << std::endl; os_mtx.unlock(); } modified_mtx.lock(); modifiedFiles.insert(dep); modified_mtx.unlock(); updated_mtx.lock(); updatedInfo.insert(*cInfo); updated_mtx.unlock(); break; } } } } noFinished++; } } int ProjectInfo::build_updated(std::ostream& os, const int& addBuildStatus, const bool& addExpl, const bool& basicOpt) { if(check_watch_dirs()) return 1; if(trackedAll.size() == 0) { os_mtx.lock(); os << "Nift does not have anything tracked" << std::endl; os_mtx.unlock(); return 0; } builtNames.clear(); failedNames.clear(); problemNames.clear(); updatedInfo.clear(); modifiedFiles.clear(); removedFiles.clear(); int no_threads; if(buildThreads < 0) no_threads = -buildThreads*std::thread::hardware_concurrency(); else no_threads = buildThreads; //no_threads = std::min(no_threads, int(trackedAll.size())); int no_paginate_threads; if(paginateThreads < 0) no_paginate_threads = -paginateThreads*std::thread::hardware_concurrency(); else no_paginate_threads = paginateThreads; nextInfo = trackedAll.begin(); counter = noFinished = estNoPagesFinished = noPagesFinished = 0; if(addBuildStatus) { os_mtx.lock(); os << "checking for updates.." << std::endl; os_mtx.unlock(); timer.start(); } std::vector<std::thread> threads; for(int i=0; i<no_threads; i++) threads.push_back(std::thread(dep_thread, std::ref(os), addExpl, incrMode, trackedAll.size(), contentDir, outputDir, contentExt, outputExt)); cPhase = UPDATE_PHASE; std::thread thrd(build_progress, trackedAll.size(), addBuildStatus); for(int i=0; i<no_threads; i++) threads[i].join(); cPhase = DUMMY_PHASE; thrd.detach(); if(addBuildStatus) clear_console_line(); size_t noToDisplay = std::max(5, -5 + (int)console_height()); if(!basicOpt) { if(removedFiles.size() > 0) { os << c_light_blue << promptStr << c_white << "removed dependency files:" << std::endl; if(removedFiles.size() < noToDisplay) { for(auto rFile=removedFiles.begin(); rFile != removedFiles.end(); rFile++) os << " " << *rFile << std::endl; } else { size_t x=0; for(auto rFile=removedFiles.begin(); x < noToDisplay; rFile++, x++) os << " " << *rFile << std::endl; os << " and " << removedFiles.size() - noToDisplay << " more" << std::endl; } } if(modifiedFiles.size() > 0) { os << c_light_blue << promptStr << c_white << "modified dependency files:" << std::endl; if(modifiedFiles.size() < noToDisplay) { for(auto uFile=modifiedFiles.begin(); uFile != modifiedFiles.end(); uFile++) os << " " << *uFile << std::endl; } else { size_t x=0; for(auto uFile=modifiedFiles.begin(); x < noToDisplay; uFile++, x++) os << " " << *uFile << std::endl; os << " and " << modifiedFiles.size() - noToDisplay << " more" << std::endl; } } if(problemNames.size() > 0) { os << c_light_blue << promptStr << c_white << "missing content/template file:" << std::endl; if(problemNames.size() < noToDisplay) { for(auto pName=problemNames.begin(); pName != problemNames.end(); pName++) os << " " << c_red << *pName << c_white << std::endl; } else { size_t x=0; for(auto pName=problemNames.begin(); x < noToDisplay; pName++, x++) os << " " << c_red << *pName << c_white << std::endl; os << " and " << problemNames.size() - noToDisplay << " more" << std::endl; } } } if(updatedInfo.size() > 0) { if(!basicOpt) { os << c_light_blue << promptStr << c_white << "need building:" << std::endl; if(updatedInfo.size() < noToDisplay) { for(auto uInfo=updatedInfo.begin(); uInfo != updatedInfo.end(); uInfo++) os << " " << uInfo->outputPath << std::endl; } else { size_t x=0; for(auto uInfo=updatedInfo.begin(); x < noToDisplay; uInfo++, x++) os << " " << uInfo->outputPath << std::endl; os << " and " << updatedInfo.size() - noToDisplay << " more" << std::endl; } } Parser parser(&trackedAll, &os_mtx, contentDir, outputDir, contentExt, outputExt, scriptExt, defaultTemplate, backupScripts, unixTextEditor, winTextEditor); //checks for pre-build scripts if(parser.run_script(os, Path("", "pre-build" + scriptExt), backupScripts, 1)) return 1; setIncrMode(incrMode); nextInfo = updatedInfo.begin(); counter = noFinished = 0; //os_mtx.lock(); if(addBuildStatus) clear_console_line(); os << "building updated files.." << std::endl; //os_mtx.unlock(); if(addBuildStatus) timer.start(); threads.clear(); for(int i=0; i<no_threads; i++) threads.push_back(std::thread(build_thread, std::ref(os), no_paginate_threads, &trackedAll, updatedInfo.size(), contentDir, outputDir, contentExt, outputExt, scriptExt, defaultTemplate, backupScripts, unixTextEditor, winTextEditor)); cPhase = BUILD_PHASE; std::thread thrd(build_progress, updatedInfo.size(), addBuildStatus); for(int i=0; i<no_threads; i++) threads[i].join(); cPhase = END_PHASE; thrd.detach(); if(addBuildStatus) clear_console_line(); if(failedNames.size() > 0) { if(noPagesFinished) os << "paginated files: " << noPagesFinished << std::endl; if(builtNames.size() == 1) os << builtNames.size() << " file built successfully" << std::endl; else os << builtNames.size() << " files built successfully" << std::endl; os << c_light_blue << promptStr << c_white << "failed to build:" << std::endl; if(failedNames.size() < noToDisplay) { for(auto fName=failedNames.begin(); fName != failedNames.end(); fName++) os << " " << c_red << *fName << c_white << std::endl; } else { size_t x=0; for(auto fName=failedNames.begin(); x < noToDisplay; fName++, x++) os << " " << c_red << *fName << c_white << std::endl; os << " and " << failedNames.size() - noToDisplay << " more" << std::endl; } } else { if(basicOpt) { #if defined __APPLE__ || defined __linux__ const std::string pkgStr = "📦 "; #else //*nix const std::string pkgStr = ":: "; #endif if(noPagesFinished) os << "paginated files: " << noPagesFinished << std::endl; if(builtNames.size() == 1) std::cout << c_light_blue << pkgStr << c_white << builtNames.size() << " updated file built successfully" << std::endl; else std::cout << c_light_blue << pkgStr << c_white << builtNames.size() << " updated files built successfully" << std::endl; } else if(builtNames.size() > 0) { #if defined __APPLE__ || defined __linux__ const std::string pkgStr = "📦 "; #else // FreeBSD/Windows const std::string pkgStr = ":: "; #endif if(noPagesFinished) os << "paginated files: " << noPagesFinished << std::endl; os << c_light_blue << pkgStr << c_white << "successfully built:" << std::endl; if(builtNames.size() < noToDisplay) { for(auto bName=builtNames.begin(); bName != builtNames.end(); bName++) os << " " << c_green << *bName << c_white << std::endl; } else { size_t x=0; for(auto bName=builtNames.begin(); x < noToDisplay; bName++, x++) os << " " << c_green << *bName << c_white << std::endl; os << " and " << builtNames.size() - noToDisplay << " more" << std::endl; } } //checks for post-build scripts if(parser.run_script(os, Path("", "post-build" + scriptExt), backupScripts, 1)) return 1; } } if(updatedInfo.size() == 0 && problemNames.size() == 0 && failedNames.size() == 0) os << "all " << trackedAll.size() << " tracked files are already up to date" << std::endl; builtNames.clear(); failedNames.clear(); return 0; } int ProjectInfo::status(std::ostream& os, const int& addBuildStatus, const bool& addExpl, const bool& basicOpt) { if(check_watch_dirs()) return 1; if(trackedAll.size() == 0) { std::cout << "Nift does not have anything tracked" << std::endl; return 0; } builtNames.clear(); failedNames.clear(); problemNames.clear(); updatedInfo.clear(); modifiedFiles.clear(); removedFiles.clear(); int no_threads; if(buildThreads < 0) no_threads = -buildThreads*std::thread::hardware_concurrency(); else no_threads = buildThreads; nextInfo = trackedAll.begin(); counter = noFinished = 0; os_mtx.lock(); std::cout << "checking for updates.." << std::endl; os_mtx.unlock(); if(addBuildStatus) timer.start(); std::vector<std::thread> threads; for(int i=0; i<no_threads; i++) threads.push_back(std::thread(dep_thread, std::ref(os), addExpl, incrMode, trackedAll.size(), contentDir, outputDir, contentExt, outputExt)); cPhase = UPDATE_PHASE; std::thread thrd(build_progress, trackedAll.size(), addBuildStatus); for(int i=0; i<no_threads; i++) threads[i].join(); cPhase = END_PHASE; thrd.detach(); if(addBuildStatus) clear_console_line(); size_t noToDisplay = std::max(5, -5 + (int)console_height()); if(!basicOpt) { if(removedFiles.size() > 0) { os << c_light_blue << promptStr << c_white << "removed dependency files:" << std::endl; if(removedFiles.size() < noToDisplay) { for(auto rFile=removedFiles.begin(); rFile != removedFiles.end(); rFile++) os << " " << *rFile << std::endl; } else { size_t x=0; for(auto rFile=removedFiles.begin(); x < noToDisplay; rFile++, x++) os << " " << *rFile << std::endl; os << " and " << removedFiles.size() - noToDisplay << " more" << std::endl; } } if(modifiedFiles.size() > 0) { os << c_light_blue << promptStr << c_white << "modified dependency files:" << std::endl; if(modifiedFiles.size() < noToDisplay) { for(auto uFile=modifiedFiles.begin(); uFile != modifiedFiles.end(); uFile++) os << " " << *uFile << std::endl; } else { size_t x=0; for(auto uFile=modifiedFiles.begin(); x < noToDisplay; uFile++, x++) os << " " << *uFile << std::endl; os << " and " << modifiedFiles.size() - noToDisplay << " more" << std::endl; } } if(problemNames.size() > 0) { os << c_light_blue << promptStr << c_white << "missing content/template file:" << std::endl; if(problemNames.size() < noToDisplay) { for(auto pName=problemNames.begin(); pName != problemNames.end(); pName++) os << " " << c_red << *pName << c_white << std::endl; } else { size_t x=0; for(auto pName=problemNames.begin(); x < noToDisplay; pName++, x++) os << " " << c_red << *pName << c_white << std::endl; os << " and " << problemNames.size() - noToDisplay << " more" << std::endl; } } } if(updatedInfo.size() > 0) { if(!basicOpt) { os << c_light_blue << promptStr << c_white << "need building:" << std::endl; if(updatedInfo.size() < noToDisplay) { for(auto uInfo=updatedInfo.begin(); uInfo != updatedInfo.end(); uInfo++) os << " " << uInfo->outputPath << std::endl; } else { size_t x=0; for(auto uInfo=updatedInfo.begin(); x < noToDisplay; uInfo++, x++) os << " " << uInfo->outputPath << std::endl; os << " and " << updatedInfo.size() - noToDisplay << " more" << std::endl; } } } if(updatedInfo.size() == 0 && problemNames.size() == 0 && failedNames.size() == 0) os << "all " << trackedAll.size() << " tracked files are already up to date" << std::endl; failedNames.clear(); return 0; }
mit
tpitale/mail_room
lib/mail_room/arbitration.rb
255
module MailRoom module Arbitration def [](name) require_relative("./arbitration/#{name}") case name when "redis" Arbitration::Redis else Arbitration::Noop end end module_function :[] end end
mit
silverfield/pythonsessions
s03_input_and_while/input_and_while.py
1340
# print positive integers up to 47 (excluding) x = 1 while x < 47: print(x) x = x + 1 print("------------------------------------------") # print all odd numbers up to 50 x = 1 while x < 50: if x % 2 == 1: print(x) x += 1 # concise way of incrementing x print("------------------------------------------") # example of a while loop where no iteration will be executed while 1 == 0: print("this should never happen") print("------------------------------------------") # example of never-ending while loop # while 1 == 1: # print("this is forever repeated") print("------------------------------------------") # will prompt the user for lines of input, put them to list and print the list at the end print("Write several lines and terminate with stop (and ENTER). ") l = [] inp = input() while inp != "stop": l.append(inp) inp = input() # be careful not to forget this line - the program will take on too much memory and slow down you PC print("You've entered: " + str(l)) # concise way of printing a list print("------------------------------------------") # reads in numbers separated by space and computes their sum s = input("Write numbers separated by space (no space after last one). At the end, press enter. ") l = [int(i) for i in s.split(' ')] print("The sum is: " + str(sum(l)))
mit
AusDTO/gov-au-beta
app/controllers/editorial/sections_controller.rb
834
module Editorial class SectionsController < EditorialController before_action :find_section before_action ->() { authorize! :read, @section }, unless: :skip_view_section_auth? decorates_assigned :section decorates_assigned :users, with: UserDecorator layout 'editorial_section' def show @filter = %w(my_pages submissions).detect { |f| f == params[:filter] } with_caching(@section) end # TODO this should be a show/index on another resource. def collaborators @pending = Request.where(section: @section, state: :requested) @users = @section.users with_caching([*@pending, *@users]) end protected def skip_view_section_auth? false end private def find_section @section = Section.find params[:section_id] end end end
mit
lawrence0819/nodedm
test/DockerMachineTest.ts
6767
import {dm, MachineStatus} from '../index' import * as chai from 'chai'; import {expect} from 'chai'; import chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); console.log ("!!! Warning !!!") console.log ("!!! This test will remove all existing docker machine and cannot be revert !!!") describe('DockerMachine', () => { describe('#create', () => { var options = { 'driver': 'virtualbox', 'virtualbox-memory': '512' }; it('should create virtualbox VM and named vbox0, vbox1, vbox2, vbox3', (done) => expect(dm.create(['vbox0', 'vbox1', 'vbox2', 'vbox3'], options)).to.eventually .deep.equal({ vbox0: true, vbox1: true, vbox2: true, vbox3: true }).notify(done)); }); describe('#ls', () => { it('should return list of machine', (done) => expect(dm.ls()) .to.eventually.deep.property('[0].name', 'vbox0').notify(done)); it('should return list of machine', (done) => expect(dm.ls()) .to.eventually.deep.property('[0].driver', 'virtualbox').notify(done)); it('should return list of machine name only', (done) => expect(dm.ls({q: ''})) .to.eventually.deep.equal(['vbox0', 'vbox1', 'vbox2', 'vbox3']).notify(done)); }); describe('#inspect', () => { it('should return vbox0 inspect object', (done) => expect(dm.inspect('vbox0')) .to.eventually.property('DriverName', 'virtualbox').notify(done)); }); describe('#ip', () => { it('should return vbox0 ip', (done) => expect(dm.ip('vbox0')) .to.eventually.match(/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/ig).notify(done)); }); describe('#url', () => { it('should return vbox0 url', (done) => expect(dm.url('vbox0')) .to.eventually.match(/^tcp:\/\/(?:[0-9]{1,3}\.){3}[0-9]{1,3}:[0-9]+$/ig).notify(done)); }); describe('#config', () => { it('should return vbox0 config', (done) => expect(dm.config('vbox0')) .to.eventually.not.empty.notify(done)); }); describe('#env', () => { it('should return vbox0 env', (done) => expect(dm.env('vbox0', {shell: 'cmd'})) .to.eventually.not.empty.notify(done)); }); describe('#ssh', () => { it('should return vbox0 `pwd` result', (done) => expect(dm.ssh('vbox0', 'pwd')) .to.eventually.equal('/home/docker').notify(done)); }); describe('#sshAll', () => { it('should return all `pwd` result', (done) => expect(dm.sshAll('pwd')) .to.eventually.deep.equal({ vbox0: '/home/docker', vbox1: '/home/docker', vbox2: '/home/docker', vbox3: '/home/docker' }).notify(done)); }); describe('#upgrade', () => { it('should upgrade vbox0', (done) => expect(dm.upgrade('vbox0')).to.eventually.equal(true).notify(done)); }); describe('#regenerateCert', () => { it('should regenerate cert for vbox0', (done) => expect(dm.regenerateCert('vbox0')).to.eventually.equal(true).notify(done)); }); describe('#stop', () => { it('should stop vbox1', (done) => expect(dm.stop('vbox1')) .to.eventually.equal(true).notify(done)); it('should stop vbox2', (done) => expect(dm.stop('vbox2')) .to.eventually.equal(true).notify(done)); it('should stop vbox3', (done) => expect(dm.stop('vbox3')) .to.eventually.equal(true).notify(done)); }); describe('#remove', () => { it('should remove vbox3', (done) => expect(dm.rm('vbox3')) .to.eventually.equal(true).notify(done)); }); describe('#start', () => { it('should start vbox2', (done) => expect(dm.start('vbox2')) .to.eventually.equal(true).notify(done)); }); describe('#status', () => { it('should return running status when name is vbox0', (done) => expect(dm.status('vbox0')) .to.eventually.equal(MachineStatus.RUNNING).notify(done)); it('should return stopped status when name is vbox1', (done) => expect(dm.status('vbox1')) .to.eventually.equal(MachineStatus.STOPPED).notify(done)); it('should return running status when name is vbox2', (done) => expect(dm.status('vbox2')) .to.eventually.equal(MachineStatus.RUNNING).notify(done)); it('should return not exist status when name is vbox3', (done) => expect(dm.status('vbox3')) .to.eventually.equal(MachineStatus.NOT_EXIST).notify(done)); it('should return vbox0, vbox1, vbox2, vbox 3 status', (done) => expect(dm.status(['vbox0', 'vbox1', 'vbox2', 'vbox3'])) .to.eventually.deep.equal({ vbox0: MachineStatus.RUNNING, vbox1: MachineStatus.STOPPED, vbox2: MachineStatus.RUNNING, vbox3: MachineStatus.NOT_EXIST }).notify(done)); }); describe('#kill', () => { it('should kill vbox0, vbox2', (done) => expect(dm.kill(['vbox0', 'vbox2'])) .to.eventually.deep.equal({ vbox0: true, vbox2: true }).notify(done)); }); describe('#remove', () => { it('should remove vbox0, vbox1, vbox2', (done) => expect(dm.rm(['vbox0', 'vbox1', 'vbox2'])) .to.eventually.deep.equal({ vbox0: true, vbox1: true, vbox2: true }).notify(done)); }); describe('#create swarm', () => { var options = { driver: 'virtualbox', 'virtualbox-memory': '512', 'swarm-master': '', 'swarm-discovery': 'token://1234' } it('should create swarm master and named vbox0', (done) => expect(dm.create('vbox0', options)).to.eventually .deep.equal(true).notify(done)); it('should create swarm slave and named vbox1, vobx2, vbox3', (done) => { delete options['swarm-master']; expect(dm.create(['vbox1', 'vbox2', 'vbox3'], options)).to.eventually .deep.equal({ vbox1: true, vbox2: true, vbox3: true }).notify(done); }); }); describe('#list', () => { it('should return list and swarm master is vbox0 ', (done) => expect(dm.ls()) .to.eventually.deep.property('[1].swarm', 'vbox0').notify(done)); }); describe('#killAll', () => { it('should kill all vbox', (done) => expect(dm.killAll()) .to.eventually.deep.equal({ vbox0: true, vbox1: true, vbox2: true, vbox3: true }).notify(done)); }); describe('#removeAll', () => { it('should remove all vbox', (done) => expect(dm.rmAll()) .to.eventually.deep.equal({ vbox0: true, vbox1: true, vbox2: true, vbox3: true }).notify(done)); }); });
mit
maginemu/webpay-node
lib/error.js
3771
'use strict'; var WebPayError = function WebPayError(message, status, errorResponse) { Error.apply(this, [message]); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.message = message; this.status = status; this.errorResponse = errorResponse; }; WebPayError.prototype = new Error(); WebPayError.prototype.constructor = WebPayError; WebPayError.prototype.toString = function toString() { return this.name + ': ' + this.message; }; var ApiConnectionError = function ApiConnectionError(message, cause) { if (typeof message === 'undefined' || message === null) { message = cause.message; } WebPayError.apply(this, [message]); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.cause = cause; }; ApiConnectionError.prototype = new WebPayError(); ApiConnectionError.prototype.constructor = ApiConnectionError; var ApiError = function ApiError(status, errorResponse) { if (typeof errorResponse === 'undefined') { errorResponse = {}; } WebPayError.apply(this, [errorResponse.message, status, errorResponse]); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.type = errorResponse.type; }; ApiError.prototype = new WebPayError(); ApiError.prototype.constructor = ApiError; var AuthenticationError = function AuthenticationError(status, errorResponse) { if (typeof errorResponse === 'undefined') { errorResponse = {}; } WebPayError.apply(this, [errorResponse.message, status, errorResponse]); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; }; AuthenticationError.prototype = new WebPayError(); AuthenticationError.prototype.constructor = AuthenticationError; var CardError = function CardError(status, errorResponse) { if (typeof errorResponse === 'undefined') { errorResponse = {}; } WebPayError.apply(this, [errorResponse.message, status, errorResponse]); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.type = errorResponse.type; this.code = errorResponse.code; this.param = errorResponse.param; }; CardError.prototype = new WebPayError(); CardError.prototype.constructor = CardError; var InvalidRequestError = function InvalidRequestError(status, errorResponse) { WebPayError.apply(this, [errorResponse.message, status, errorResponse]); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.type = errorResponse.type; this.param = errorResponse.param; }; InvalidRequestError.prototype = new WebPayError(); InvalidRequestError.prototype.constructor = InvalidRequestError; function errorFromJsonResponse(status, data) { if (typeof data === 'object' && data.error) { var errorResponse = data.error; switch (status) { case 400: case 404: return new InvalidRequestError(status, errorResponse); case 401: return new AuthenticationError(status, errorResponse); case 402: return new CardError(status, errorResponse); default: return new ApiError(status, errorResponse); } } else { return new ApiConnectionError('Unexpected response: data does not an object containing \'error\' field'); } } function invalidIdError() { return new InvalidRequestError(null, { type: 'invalid_request_error', message: 'ID must not be empty', param: 'id' }); } module.exports = { ApiConnectionError: ApiConnectionError, ApiError: ApiError, AuthenticationError: AuthenticationError, CardError: CardError, InvalidRequestError: InvalidRequestError, WebPayError: WebPayError, fromJsonResponse: errorFromJsonResponse, invalidIdError: invalidIdError };
mit
maccman/stylo
public/assets/app/models/properties/color.module.js
5295
(function() { if (!this.require) { var modules = {}, cache = {}; var require = function(name, root) { var path = expand(root, name), indexPath = expand(path, './index'), module, fn; module = cache[path] || cache[indexPath]; if (module) { return module; } else if (fn = modules[path] || modules[path = indexPath]) { module = {id: path, exports: {}}; cache[path] = module.exports; fn(module.exports, function(name) { return require(name, dirname(path)); }, module); return cache[path] = module.exports; } else { throw 'module ' + name + ' not found'; } }; var expand = function(root, name) { var results = [], parts, part; // If path is relative if (/^\.\.?(\/|$)/.test(name)) { parts = [root, name].join('/').split('/'); } else { parts = name.split('/'); } for (var i = 0, length = parts.length; i < length; i++) { part = parts[i]; if (part == '..') { results.pop(); } else if (part != '.' && part != '') { results.push(part); } } return results.join('/'); }; var dirname = function(path) { return path.split('/').slice(0, -1).join('/'); }; this.require = function(name) { return require(name, ''); }; this.require.define = function(bundle) { for (var key in bundle) { modules[key] = bundle[key]; } }; this.require.modules = modules; this.require.cache = cache; } return this.require; }).call(this); this.require.define({"app/models/properties/color":function(exports, require, module){(function() { var Color, Property, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }; Property = require('app/models/property'); Color = (function(_super) { __extends(Color, _super); Color.name = 'Color'; Color.regex = /(?:#([0-9a-f]{3,6})|rgba?\(([^)]+)\))/i; Color.fromHex = function(hex) { var b, g, r; if (hex[0] === '#') { hex = hex.substring(1, 7); } if (hex.length === 3) { hex = hex.charAt(0) + hex.charAt(0) + hex.charAt(1) + hex.charAt(1) + hex.charAt(2) + hex.charAt(2); } r = parseInt(hex.substring(0, 2), 16); g = parseInt(hex.substring(2, 4), 16); b = parseInt(hex.substring(4, 6), 16); return new this(r, g, b); }; Color.fromString = function(str) { var a, b, g, hex, match, r, rgba, _ref; match = str.match(this.regex); if (!match) { return null; } if (hex = match[1]) { return this.fromHex(hex); } else if (rgba = match[2]) { _ref = rgba.split(/\s*,\s*/), r = _ref[0], g = _ref[1], b = _ref[2], a = _ref[3]; return new this(r, g, b, a); } }; Color.White = function(alpha) { return new Color(255, 255, 255, alpha); }; Color.Black = function(alpha) { return new Color(0, 0, 0, alpha); }; Color.Transparent = function() { return new Color; }; function Color(r, g, b, a) { if (a == null) { a = 1; } if (r != null) { this.r = parseInt(r, 10); } if (g != null) { this.g = parseInt(g, 10); } if (b != null) { this.b = parseInt(b, 10); } this.a = parseFloat(a); } Color.prototype.toHex = function() { var a; if (!((this.r != null) && (this.g != null) && (this.b != null))) { return 'transparent'; } a = (this.b | this.g << 8 | this.r << 16).toString(16); a = '#' + '000000'.substr(0, 6 - a.length) + a; return a.toUpperCase(); }; Color.prototype.isTransparent = function() { return !this.a; }; Color.prototype.set = function(values) { var key, value; for (key in values) { value = values[key]; this[key] = value; } return this; }; Color.prototype.rgb = function() { var result; return result = { r: this.r, g: this.g, b: this.b }; }; Color.prototype.rgba = function() { var result; return result = { r: this.r, g: this.g, b: this.b, a: this.a }; }; Color.prototype.clone = function() { return new this.constructor(this.r, this.g, this.b, this.a); }; Color.prototype.toString = function() { if ((this.r != null) && (this.g != null) && (this.b != null)) { if ((this.a != null) && this.a !== 1) { return "rgba(" + this.r + ", " + this.g + ", " + this.b + ", " + this.a + ")"; } else { return this.toHex(); } } else { return 'transparent'; } }; Color.prototype.id = module.id; Color.prototype.toValue = function() { return [this.r, this.g, this.b, this.a]; }; return Color; })(Property); module.exports = Color; }).call(this); ;}});
mit
dotcool/mvideo
src/com/ejia/abplayer/view/FileUtils.java
11306
package com.ejia.abplayer.view; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import android.os.Environment; import android.os.StatFs; import android.util.Log; import com.ejia.abplayer.util.StringUtils; public class FileUtils { // http://www.fileinfo.com/filetypes/video , "dat" , "bin" , "rms" public static final String[] VIDEO_EXTENSIONS = { "264", "3g2", "3gp", "3gp2", "3gpp", "3gpp2", "3mm", "3p2", "60d", "aep", "ajp", "amv", "amx", "arf", "asf", "asx", "avb", "avd", "avi", "avs", "avs", "axm", "bdm", "bdmv", "bik", "bix", "bmk", "box", "bs4", "bsf", "byu", "camre", "clpi", "cpi", "cvc", "d2v", "d3v", "dav", "dce", "dck", "ddat", "dif", "dir", "divx", "dlx", "dmb", "dmsm", "dmss", "dnc", "dpg", "dream", "dsy", "dv", "dv-avi", "dv4", "dvdmedia", "dvr-ms", "dvx", "dxr", "dzm", "dzp", "dzt", "evo", "eye", "f4p", "f4v", "fbr", "fbr", "fbz", "fcp", "flc", "flh", "fli", "flv", "flx", "gl", "grasp", "gts", "gvi", "gvp", "hdmov", "hkm", "ifo", "imovi", "imovi", "iva", "ivf", "ivr", "ivs", "izz", "izzy", "jts", "lsf", "lsx", "m15", "m1pg", "m1v", "m21", "m21", "m2a", "m2p", "m2t", "m2ts", "m2v", "m4e", "m4u", "m4v", "m75", "meta", "mgv", "mj2", "mjp", "mjpg", "mkv", "mmv", "mnv", "mod", "modd", "moff", "moi", "moov", "mov", "movie", "mp21", "mp21", "mp2v", "mp4", "mp4v", "mpe", "mpeg", "mpeg4", "mpf", "mpg", "mpg2", "mpgin", "mpl", "mpls", "mpv", "mpv2", "mqv", "msdvd", "msh", "mswmm", "mts", "mtv", "mvb", "mvc", "mvd", "mve", "mvp", "mxf", "mys", "ncor", "nsv", "nvc", "ogm", "ogv", "ogx", "osp", "par", "pds", "pgi", "piv", "playlist", "pmf", "prel", "pro", "prproj", "psh", "pva", "pvr", "pxv", "qt", "qtch", "qtl", "qtm", "qtz", "rcproject", "rdb", "rec", "rm", "rmd", "rmp", "rmvb", "roq", "rp", "rts", "rts", "rum", "rv", "sbk", "sbt", "scm", "scm", "scn", "sec", "seq", "sfvidcap", "smil", "smk", "sml", "smv", "spl", "ssm", "str", "stx", "svi", "swf", "swi", "swt", "tda3mt", "tivo", "tix", "tod", "tp", "tp0", "tpd", "tpr", "trp", "ts", "tvs", "vc1", "vcr", "vcv", "vdo", "vdr", "veg", "vem", "vf", "vfw", "vfz", "vgz", "vid", "viewlet", "viv", "vivo", "vlab", "vob", "vp3", "vp6", "vp7", "vpj", "vro", "vsp", "w32", "wcp", "webm", "wm", "wmd", "wmmp", "wmv", "wmx", "wp3", "wpl", "wtv", "wvx", "xfl", "xvid", "yuv", "zm1", "zm2", "zm3", "zmv" }; // http://www.fileinfo.com/filetypes/audio , "spx" , "mid" , "sf" public static final String[] AUDIO_EXTENSIONS = { "4mp", "669", "6cm", "8cm", "8med", "8svx", "a2m", "aa", "aa3", "aac", "aax", "abc", "abm", "ac3", "acd", "acd-bak", "acd-zip", "acm", "act", "adg", "afc", "agm", "ahx", "aif", "aifc", "aiff", "ais", "akp", "al", "alaw", "all", "amf", "amr", "ams", "ams", "aob", "ape", "apf", "apl", "ase", "at3", "atrac", "au", "aud", "aup", "avr", "awb", "band", "bap", "bdd", "box", "bun", "bwf", "c01", "caf", "cda", "cdda", "cdr", "cel", "cfa", "cidb", "cmf", "copy", "cpr", "cpt", "csh", "cwp", "d00", "d01", "dcf", "dcm", "dct", "ddt", "dewf", "df2", "dfc", "dig", "dig", "dls", "dm", "dmf", "dmsa", "dmse", "drg", "dsf", "dsm", "dsp", "dss", "dtm", "dts", "dtshd", "dvf", "dwd", "ear", "efa", "efe", "efk", "efq", "efs", "efv", "emd", "emp", "emx", "esps", "f2r", "f32", "f3r", "f4a", "f64", "far", "fff", "flac", "flp", "fls", "frg", "fsm", "fzb", "fzf", "fzv", "g721", "g723", "g726", "gig", "gp5", "gpk", "gsm", "gsm", "h0", "hdp", "hma", "hsb", "ics", "iff", "imf", "imp", "ins", "ins", "it", "iti", "its", "jam", "k25", "k26", "kar", "kin", "kit", "kmp", "koz", "koz", "kpl", "krz", "ksc", "ksf", "kt2", "kt3", "ktp", "l", "la", "lqt", "lso", "lvp", "lwv", "m1a", "m3u", "m4a", "m4b", "m4p", "m4r", "ma1", "mdl", "med", "mgv", "midi", "miniusf", "mka", "mlp", "mmf", "mmm", "mmp", "mo3", "mod", "mp1", "mp2", "mp3", "mpa", "mpc", "mpga", "mpu", "mp_", "mscx", "mscz", "msv", "mt2", "mt9", "mte", "mti", "mtm", "mtp", "mts", "mus", "mws", "mxl", "mzp", "nap", "nki", "nra", "nrt", "nsa", "nsf", "nst", "ntn", "nvf", "nwc", "odm", "oga", "ogg", "okt", "oma", "omf", "omg", "omx", "ots", "ove", "ovw", "pac", "pat", "pbf", "pca", "pcast", "pcg", "pcm", "peak", "phy", "pk", "pla", "pls", "pna", "ppc", "ppcx", "prg", "prg", "psf", "psm", "ptf", "ptm", "pts", "pvc", "qcp", "r", "r1m", "ra", "ram", "raw", "rax", "rbs", "rcy", "rex", "rfl", "rmf", "rmi", "rmj", "rmm", "rmx", "rng", "rns", "rol", "rsn", "rso", "rti", "rtm", "rts", "rvx", "rx2", "s3i", "s3m", "s3z", "saf", "sam", "sb", "sbg", "sbi", "sbk", "sc2", "sd", "sd", "sd2", "sd2f", "sdat", "sdii", "sds", "sdt", "sdx", "seg", "seq", "ses", "sf2", "sfk", "sfl", "shn", "sib", "sid", "sid", "smf", "smp", "snd", "snd", "snd", "sng", "sng", "sou", "sppack", "sprg", "sseq", "sseq", "ssnd", "stm", "stx", "sty", "svx", "sw", "swa", "syh", "syw", "syx", "td0", "tfmx", "thx", "toc", "tsp", "txw", "u", "ub", "ulaw", "ult", "ulw", "uni", "usf", "usflib", "uw", "uwf", "vag", "val", "vc3", "vmd", "vmf", "vmf", "voc", "voi", "vox", "vpm", "vqf", "vrf", "vyf", "w01", "wav", "wav", "wave", "wax", "wfb", "wfd", "wfp", "wma", "wow", "wpk", "wproj", "wrk", "wus", "wut", "wv", "wvc", "wve", "wwu", "xa", "xa", "xfs", "xi", "xm", "xmf", "xmi", "xmz", "xp", "xrns", "xsb", "xspf", "xt", "xwb", "ym", "zvd", "zvr" }; private static final HashSet<String> mHashVideo; private static final HashSet<String> mHashAudio; private static final double KB = 1024.0; private static final double MB = KB * KB; private static final double GB = KB * KB * KB; static { mHashVideo = new HashSet<String>(Arrays.asList(VIDEO_EXTENSIONS)); mHashAudio = new HashSet<String>(Arrays.asList(AUDIO_EXTENSIONS)); } /** 是否是音频或者视频 */ public static boolean isVideoOrAudio(File f) { final String ext = getFileExtension(f); return mHashVideo.contains(ext) || mHashAudio.contains(ext); } public static boolean isVideoOrAudio(String f) { final String ext = getUrlExtension(f); return mHashVideo.contains(ext) || mHashAudio.contains(ext); } public static boolean isVideo(File f) { final String ext = getFileExtension(f); return mHashVideo.contains(ext); } /** 获取文件后缀 */ public static String getFileExtension(File f) { if (f != null) { String filename = f.getName(); int i = filename.lastIndexOf('.'); if (i > 0 && i < filename.length() - 1) { return filename.substring(i + 1).toLowerCase(); } } return null; } public static String getUrlFileName(String url) { int slashIndex = url.lastIndexOf('/'); int dotIndex = url.lastIndexOf('.'); String filenameWithoutExtension; if (dotIndex == -1) { filenameWithoutExtension = url.substring(slashIndex + 1); } else { filenameWithoutExtension = url.substring(slashIndex + 1, dotIndex); } return filenameWithoutExtension; } public static String getUrlExtension(String url) { if (!StringUtils.isEmpty(url)) { int i = url.lastIndexOf('.'); if (i > 0 && i < url.length() - 1) { return url.substring(i + 1).toLowerCase(); } } return ""; } public static String getFileNameNoEx(String filename) { if ((filename != null) && (filename.length() > 0)) { int dot = filename.lastIndexOf('.'); if ((dot > -1) && (dot < (filename.length()))) { return filename.substring(0, dot); } } return filename; } public static String showFileSize(long size) { String fileSize; if (size < KB) fileSize = size + "B"; else if (size < MB) fileSize = String.format("%.1f", size / KB) + "KB"; else if (size < GB) fileSize = String.format("%.1f", size / MB) + "MB"; else fileSize = String.format("%.1f", size / GB) + "GB"; return fileSize; } /** 显示SD卡剩余空间 */ public static String showFileAvailable() { String result = ""; if (Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { StatFs sf = new StatFs(Environment.getExternalStorageDirectory() .getPath()); long blockSize = sf.getBlockSize(); long blockCount = sf.getBlockCount(); long availCount = sf.getAvailableBlocks(); return showFileSize(availCount * blockSize) + " / " + showFileSize(blockSize * blockCount); } return result; } /** 如果不存在就创建 */ public static boolean createIfNoExists(String path) { File file = new File(path); boolean mk = false; if (!file.exists()) { mk = file.mkdirs(); } return mk; } private static HashMap<String, String> mMimeType = new HashMap<String, String>(); static { mMimeType.put("M1V", "video/mpeg"); mMimeType.put("MP2", "video/mpeg"); mMimeType.put("MPE", "video/mpeg"); mMimeType.put("MPG", "video/mpeg"); mMimeType.put("MPEG", "video/mpeg"); mMimeType.put("MP4", "video/mp4"); mMimeType.put("M4V", "video/mp4"); mMimeType.put("3GP", "video/3gpp"); mMimeType.put("3GPP", "video/3gpp"); mMimeType.put("3G2", "video/3gpp2"); mMimeType.put("3GPP2", "video/3gpp2"); mMimeType.put("MKV", "video/x-matroska"); mMimeType.put("WEBM", "video/x-matroska"); mMimeType.put("MTS", "video/mp2ts"); mMimeType.put("TS", "video/mp2ts"); mMimeType.put("TP", "video/mp2ts"); mMimeType.put("WMV", "video/x-ms-wmv"); mMimeType.put("ASF", "video/x-ms-asf"); mMimeType.put("ASX", "video/x-ms-asf"); mMimeType.put("FLV", "video/x-flv"); mMimeType.put("MOV", "video/quicktime"); mMimeType.put("QT", "video/quicktime"); mMimeType.put("RM", "video/x-pn-realvideo"); mMimeType.put("RMVB", "video/x-pn-realvideo"); mMimeType.put("VOB", "video/dvd"); mMimeType.put("DAT", "video/dvd"); mMimeType.put("AVI", "video/x-divx"); mMimeType.put("OGV", "video/ogg"); mMimeType.put("OGG", "video/ogg"); mMimeType.put("VIV", "video/vnd.vivo"); mMimeType.put("VIVO", "video/vnd.vivo"); mMimeType.put("WTV", "video/wtv"); mMimeType.put("AVS", "video/avs-video"); mMimeType.put("SWF", "video/x-shockwave-flash"); mMimeType.put("YUV", "video/x-raw-yuv"); } /** 获取MIME */ public static String getMimeType(String path) { int lastDot = path.lastIndexOf("."); if (lastDot < 0) return null; return mMimeType.get(path.substring(lastDot + 1).toUpperCase()); } /** 多个SD卡时 取外置SD卡 */ public static String getExternalStorageDirectory() { // 参考文章 // http://blog.csdn.net/bbmiku/article/details/7937745 Map<String, String> map = System.getenv(); String[] values = new String[map.values().size()]; map.values().toArray(values); String path = values[values.length - 1]; Log.e("nmbb", "FileUtils.getExternalStorageDirectory : " + path); if (path.startsWith("/mnt/") && !Environment.getExternalStorageDirectory().getAbsolutePath() .equals(path)) return path; else return null; } public static String getCanonical(File f) { if (f == null) return null; try { return f.getCanonicalPath(); } catch (IOException e) { return f.getAbsolutePath(); } } public static boolean sdAvailable() { return Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment .getExternalStorageState()) || Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState()); } }
mit
catedrasaes-umu/NoSQLDataEngineering
projects/es.um.nosql.s13e.json2dbschema/src/es/um/nosql/s13e/json2dbschema/util/abstractjson/impl/jackson/JacksonNumber.java
351
/** * */ package es.um.nosql.s13e.json2dbschema.util.abstractjson.impl.jackson; import org.codehaus.jackson.JsonNode; import es.um.nosql.s13e.json2dbschema.util.abstractjson.IAJNumber; /** * @author dsevilla * */ public class JacksonNumber extends JacksonElement implements IAJNumber { public JacksonNumber(JsonNode val) { super(val); } }
mit
dk307/HSPI_RemoteHelper
IDeviceControlManager.cs
741
using Hspi.DeviceData; using System; using System.Threading; using System.Threading.Tasks; namespace Hspi.Connector { internal interface IDeviceCommandHandler { string Name { get; } TimeSpan DefaultCommandDelay { get; } TimeSpan PowerOnDelay { get; } DeviceType DeviceType { get; } Task HandleCommand(DeviceIdentifier deviceIdentifier, double value, CancellationToken token); Task HandleCommand(string commandId, CancellationToken token); Task HandleCommand(string feedbackName, object value, CancellationToken token); } internal interface IDeviceFeedbackProvider { string Name { get; } object GetFeedbackValue(string feedbackName); } }
mit
czim/file-handling
src/Variant/Strategies/VideoScreenshotStrategy.php
2515
<?php namespace Czim\FileHandling\Variant\Strategies; use FFMpeg\FFMpeg; use FFMpeg\Coordinate\TimeCode; use FFMpeg\FFProbe; class VideoScreenshotStrategy extends AbstractVideoStrategy { /** * Performs manipulation of the file. * * @return bool|null */ protected function perform(): ?bool { $path = $this->file->path(); $imageName = pathinfo($path, PATHINFO_FILENAME) . '.jpg'; $imagePath = pathinfo($path, PATHINFO_DIRNAME) . '/' . $imageName; $ffmpeg = FFMpeg::create([ 'ffmpeg.binaries' => $this->getFfpmegBinaryPath(), 'ffprobe.binaries' => $this->getFfprobeBinaryPath(), ]); $video = $ffmpeg->open($path); // Determine second at which to extract screenshot if (null !== ($percentage = $this->getPercentageConfigValue())) { // Percentage of full duration $ffprobe = FFProbe::create([ 'ffprobe.binaries' => $this->getFfprobeBinaryPath(), ]); $duration = (float) $ffprobe->format($path)->get('duration'); $seconds = $percentage / 100 * $duration; } elseif (null === ($seconds = $this->getSecondsConfigValue())) { $seconds = 0; } $frame = $video->frame(TimeCode::fromSeconds($seconds)); $frame->save($imagePath); $this->file->setName($imageName); $this->file->setMimeType('image/jpeg'); $this->file->setData($imagePath); return null; } protected function getSecondsConfigValue(): ?int { if (array_key_exists('seconds', $this->options)) { return $this->options['seconds']; } return null; } protected function getPercentageConfigValue(): ?int { if (array_key_exists('percentage', $this->options)) { return $this->options['percentage']; } return null; } protected function getFfpmegBinaryPath(): string { if (array_key_exists('ffmpeg', $this->options)) { return $this->options['ffmpeg']; } // @codeCoverageIgnoreStart return '/usr/bin/ffmpeg'; // @codeCoverageIgnoreEnd } protected function getFfprobeBinaryPath(): string { if (array_key_exists('ffprobe', $this->options)) { return $this->options['ffprobe']; } // @codeCoverageIgnoreStart return '/usr/bin/ffprobe'; // @codeCoverageIgnoreEnd } }
mit
forscience/cudgl
src/demos/fireball.cc
1762
#include <core/demo.hh> #include <gl/draw_geometry.hh> #include <gl/embedded_shaders.hh> #include <gl/program.hh> #include <shapes/screen_quad.hh> using namespace cudgl; auto initialize = [](gl &the_gl, args &a, program &p, draw_geometry &g) { return [&](demo &the_demo) { // initialize the draw geometry g.add_vertices(screen_quad_vertices, buffer_usage::static_draw); //add_vertices(g, screen_quad_vertices, buffer_usage::static_draw); g.add_indices(screen_quad_indices, buffer_usage::static_draw); // initialize the program p.attach_shader(shader_t::vertex, passthrough_330c_vertex); p.attach_shader(shader_t::fragment, fireball_330c_fragment, "fragment"); p.bind_attrib(0, "position"); p.link(); // initialize the gl rgba<double> clear_color{0.2, 0.2, 0.2, 0.2}; the_gl.print_info(); the_gl.set_clear_color(clear_color); the_gl.set_depth_test(false); the_gl.set_viewport(a.width, a.height); }; }; auto render = [](program &p, draw_geometry &g) { return [&](gl &the_gl) { static GLfloat global_time = 0; global_time += 0.01f; the_gl.clear_buffers(buffer_bits::color); the_gl.start_clock(); p.use(); p.set_uniform("iGlobalTime", global_time); p.set_uniform("iResolution", 640, 360); g.draw(); p.end_use(); the_gl.flush(); the_gl.end_clock(); the_gl.check_errors(0); }; }; int main(int argc, char *argv[]) { demo the_demo{}; program p{}; draw_geometry g{}; args a(argc, argv); the_demo.create_window(a); the_demo << initialize(the_demo.the_gl, a, p, g); the_demo.event_loop(render(p, g)); // needs to happen before the GL context disappears return 0; }
mit
enBask/Asgard
Samples/Mono game/Shared/MapData.cs
5951
using Asgard.Core.Network.Data; using MonoGame.Extended.Maps.Tiled; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Asgard.Core.System; using Artemis; using System.Reflection; using Farseer.Framework; using Asgard.Core.Physics; using FarseerPhysics.Factories; namespace Shared { public class MapData : DefinitionNetworkObject { public NetworkProperty<int> Width { get; set; } public NetworkProperty<int> Height { get; set; } public NetworkProperty<int> TileWidth { get; set; } public NetworkProperty<int> TileHeight { get; set; } public NetworkProperty<int> FirstId { get; set; } public NetworkProperty<LayerData> Layer1 { get; set; } public NetworkProperty<LayerData> Layer2 { get; set; } public NetworkProperty<LayerData> Layer3 { get; set; } public NetworkProperty<LayerData> Layer4 { get; set; } public NetworkProperty<LayerData> Layer5 { get; set; } float _worldfactor = 1f / 10f; public MapData() { } public void Load(AsgardBase Base, TiledMap map) { Width = map.Width; Height = map.Height; TileWidth = map.TileWidth; TileHeight = map.TileHeight; FirstId = 1; var layers = map.Layers.ToList(); if (layers.Count < 5) return; Layer1 = new LayerData(layers[0] as TiledTileLayer); Layer2 = new LayerData(layers[1] as TiledTileLayer); Layer3 = new LayerData(layers[2] as TiledTileLayer); Layer4 = new LayerData(layers[3] as TiledTileLayer); Layer5 = new LayerData(layers[4] as TiledTileLayer); LoadCollisions(Base, map); } private void LoadCollisions(AsgardBase Base, TiledMap map) { #region build collision world var viewMap = map; var midgard = Base.LookupSystem<Midgard>(); var world = midgard.GetWorld(); var layer = viewMap.Layers.Last() as TiledTileLayer; { var layerField = typeof(TiledMap).GetField("_layers", BindingFlags.NonPublic | BindingFlags.Instance); List<TiledLayer> layers = layerField.GetValue(viewMap) as List<TiledLayer>; layers.Remove(layer); } for (var y = 0; y < layer.Height; y++) { for (var x = 0; x < layer.Width; x++) { var tile = layer.GetTile(x, y); if (tile.Id == 1702)// hack { var xTile = tile.X; var yTile = tile.Y; Vector2 centerPoint = new Vector2((xTile * (viewMap.TileWidth - 1)) + ((viewMap.TileWidth - 1) / 2), (yTile * (viewMap.TileHeight - 1)) + ((viewMap.TileHeight - 1) / 2)); Vector2 upperLeftPos = new Vector2(xTile * (viewMap.TileWidth - 1), (yTile) * (viewMap.TileHeight - 1)); var body = BodyFactory.CreateRectangle(world, (viewMap.TileWidth * _worldfactor) - 0.01f, (viewMap.TileHeight * _worldfactor) - 0.01f, 1.0f); body.Restitution = 1f; body.Position = new Vector2( centerPoint.X * _worldfactor, centerPoint.Y * _worldfactor); body.CollisionCategories = FarseerPhysics.Dynamics.Category.Cat1; body.CollidesWith = FarseerPhysics.Dynamics.Category.Cat2; } } } #endregion } public override void OnCreated(AsgardBase instance, Entity entity) { var mapComponent = entity.GetComponent<MapComponent>(); mapComponent.Map = new TiledMap(mapComponent.Device, Width, Height, TileWidth, TileHeight); mapComponent.Map.CreateTileset(mapComponent.Texture, FirstId, TileWidth, TileHeight, 1, 1); mapComponent.Map.CreateTileLayer("1", Layer1.Value.Width, Layer1.Value.Height, Layer1.Value.TileData); mapComponent.Map.CreateTileLayer("2", Layer2.Value.Width, Layer2.Value.Height, Layer2.Value.TileData); mapComponent.Map.CreateTileLayer("3", Layer3.Value.Width, Layer3.Value.Height, Layer3.Value.TileData); mapComponent.Map.CreateTileLayer("4", Layer4.Value.Width, Layer4.Value.Height, Layer4.Value.TileData); mapComponent.Map.CreateTileLayer("5", Layer5.Value.Width, Layer5.Value.Height, Layer5.Value.TileData); LoadCollisions(instance, mapComponent.Map); } } public class LayerData : DefinitionNetworkObject { public NetworkProperty<string> StringData { get; set; } public NetworkProperty<int> Height { get; set; } public NetworkProperty<int> Width { get; set; } public int[] TileData { get; set; } public LayerData() { } public LayerData(TiledTileLayer layer) { Width = layer.Width; Height = layer.Height; List<int> ids = new List<int>(); for (int y = 0; y < layer.Height; ++y) { for (int x = 0; x < layer.Width; ++x) { var tile = layer.GetTile(x, y); ids.Add(tile.Id); } } StringData = String.Join(",", ids.ToArray()); } public override void OnCreated(AsgardBase instance, Entity entity) { var strData = StringData.Value.Split(','); TileData = strData.Select(s => Convert.ToInt32(s)).ToArray(); } } }
mit
mwaylabs/generator-m-ionic
generators/service/templates/_service.spec.js
1217
'use strict'; describe('module: <%= moduleName %>, service: <%= serviceName %>', function () { // load the service's module beforeEach(module('<%= moduleName %>')); // load all the templates to prevent unexpected $http requests from ui-router beforeEach(module('ngHtml2Js')); <% if (options.template !== 'debug') { -%> // instantiate service var <%= serviceName %>; beforeEach(inject(function (_<%= serviceName %>_) { <%= serviceName %> = _<%= serviceName %>_; })); it('should do something', function () { expect(!!<%= serviceName %>).toBe(true); }); <% } else { -%> // instantiate service var <%= serviceName %>; var $timeout; beforeEach(inject(function (_<%= serviceName %>_, _$timeout_) { <%= serviceName %> = _<%= serviceName %>_; $timeout = _$timeout_; })); describe('.changeBriefly()', function () { beforeEach(function () { <%= serviceName %>.changeBriefly(); }); it('should briefly change', function () { expect(<%= serviceName %>.someData.binding).toEqual('Yeah this was changed'); $timeout.flush(); expect(<%= serviceName %>.someData.binding).toEqual('Yes! Got that databinding working'); }); }); <% } -%> });
mit
DXNL/IoTArchitecture
sources/VetudaPoC/CollectorWorker/ServiceEventSource.cs
8655
using System; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Fabric; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.ServiceFabric.Services.Runtime; namespace CollectorWorker { [EventSource(Name = "MyCompany-VentudaPoC-CollectorWorker")] internal sealed class ServiceEventSource : EventSource { public static readonly ServiceEventSource Current = new ServiceEventSource(); static ServiceEventSource() { // A workaround for the problem where ETW activities do not get tracked until Tasks infrastructure is initialized. // This problem will be fixed in .NET Framework 4.6.2. Task.Run(() => { }); } // Instance constructor is private to enforce singleton semantics private ServiceEventSource() : base() { } #region Keywords // Event keywords can be used to categorize events. // Each keyword is a bit flag. A single event can be associated with multiple keywords (via EventAttribute.Keywords property). // Keywords must be defined as a public class named 'Keywords' inside EventSource that uses them. public static class Keywords { public const EventKeywords Requests = (EventKeywords)0x1L; public const EventKeywords ServiceInitialization = (EventKeywords)0x2L; } #endregion #region Events // Define an instance method for each event you want to record and apply an [Event] attribute to it. // The method name is the name of the event. // Pass any parameters you want to record with the event (only primitive integer types, DateTime, Guid & string are allowed). // Each event method implementation should check whether the event source is enabled, and if it is, call WriteEvent() method to raise the event. // The number and types of arguments passed to every event method must exactly match what is passed to WriteEvent(). // Put [NonEvent] attribute on all methods that do not define an event. // For more information see https://msdn.microsoft.com/en-us/library/system.diagnostics.tracing.eventsource.aspx [NonEvent] public void Message(string message, params object[] args) { if (this.IsEnabled()) { string finalMessage = string.Format(message, args); Message(finalMessage); } } private const int MessageEventId = 1; [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0}")] public void Message(string message) { if (this.IsEnabled()) { WriteEvent(MessageEventId, message); } } [NonEvent] public void ServiceMessage(StatelessService service, string message, params object[] args) { if (this.IsEnabled()) { string finalMessage = string.Format(message, args); ServiceMessage( service.Context.ServiceName.ToString(), service.Context.ServiceTypeName, service.Context.InstanceId, service.Context.PartitionId, service.Context.CodePackageActivationContext.ApplicationName, service.Context.CodePackageActivationContext.ApplicationTypeName, service.Context.NodeContext.NodeName, finalMessage); } } // For very high-frequency events it might be advantageous to raise events using WriteEventCore API. // This results in more efficient parameter handling, but requires explicit allocation of EventData structure and unsafe code. // To enable this code path, define UNSAFE conditional compilation symbol and turn on unsafe code support in project properties. private const int ServiceMessageEventId = 2; [Event(ServiceMessageEventId, Level = EventLevel.Informational, Message = "{7}")] private #if UNSAFE unsafe #endif void ServiceMessage( string serviceName, string serviceTypeName, long replicaOrInstanceId, Guid partitionId, string applicationName, string applicationTypeName, string nodeName, string message) { #if !UNSAFE WriteEvent(ServiceMessageEventId, serviceName, serviceTypeName, replicaOrInstanceId, partitionId, applicationName, applicationTypeName, nodeName, message); #else const int numArgs = 8; fixed (char* pServiceName = serviceName, pServiceTypeName = serviceTypeName, pApplicationName = applicationName, pApplicationTypeName = applicationTypeName, pNodeName = nodeName, pMessage = message) { EventData* eventData = stackalloc EventData[numArgs]; eventData[0] = new EventData { DataPointer = (IntPtr) pServiceName, Size = SizeInBytes(serviceName) }; eventData[1] = new EventData { DataPointer = (IntPtr) pServiceTypeName, Size = SizeInBytes(serviceTypeName) }; eventData[2] = new EventData { DataPointer = (IntPtr) (&replicaOrInstanceId), Size = sizeof(long) }; eventData[3] = new EventData { DataPointer = (IntPtr) (&partitionId), Size = sizeof(Guid) }; eventData[4] = new EventData { DataPointer = (IntPtr) pApplicationName, Size = SizeInBytes(applicationName) }; eventData[5] = new EventData { DataPointer = (IntPtr) pApplicationTypeName, Size = SizeInBytes(applicationTypeName) }; eventData[6] = new EventData { DataPointer = (IntPtr) pNodeName, Size = SizeInBytes(nodeName) }; eventData[7] = new EventData { DataPointer = (IntPtr) pMessage, Size = SizeInBytes(message) }; WriteEventCore(ServiceMessageEventId, numArgs, eventData); } #endif } private const int ServiceTypeRegisteredEventId = 3; [Event(ServiceTypeRegisteredEventId, Level = EventLevel.Informational, Message = "Service host process {0} registered service type {1}", Keywords = Keywords.ServiceInitialization)] public void ServiceTypeRegistered(int hostProcessId, string serviceType) { WriteEvent(ServiceTypeRegisteredEventId, hostProcessId, serviceType); } private const int ServiceHostInitializationFailedEventId = 4; [Event(ServiceHostInitializationFailedEventId, Level = EventLevel.Error, Message = "Service host initialization failed", Keywords = Keywords.ServiceInitialization)] public void ServiceHostInitializationFailed(string exception) { WriteEvent(ServiceHostInitializationFailedEventId, exception); } // A pair of events sharing the same name prefix with a "Start"/"Stop" suffix implicitly marks boundaries of an event tracing activity. // These activities can be automatically picked up by debugging and profiling tools, which can compute their execution time, child activities, // and other statistics. private const int ServiceRequestStartEventId = 5; [Event(ServiceRequestStartEventId, Level = EventLevel.Informational, Message = "Service request '{0}' started", Keywords = Keywords.Requests)] public void ServiceRequestStart(string requestTypeName) { WriteEvent(ServiceRequestStartEventId, requestTypeName); } private const int ServiceRequestStopEventId = 6; [Event(ServiceRequestStopEventId, Level = EventLevel.Informational, Message = "Service request '{0}' finished", Keywords = Keywords.Requests)] public void ServiceRequestStop(string requestTypeName) { WriteEvent(ServiceRequestStopEventId, requestTypeName); } private const int ServiceRequestFailedEventId = 7; [Event(ServiceRequestFailedEventId, Level = EventLevel.Error, Message = "Service request '{0}' failed", Keywords = Keywords.Requests)] public void ServiceRequestFailed(string requestTypeName, string exception) { WriteEvent(ServiceRequestFailedEventId, exception); } #endregion #region Private methods #if UNSAFE private int SizeInBytes(string s) { if (s == null) { return 0; } else { return (s.Length + 1) * sizeof(char); } } #endif #endregion } }
mit
joje6/three-cats-alt
lib/api/users.js
1764
var data = [ { email: 'user@threecats.io', name: 'Test User', password: '1111' } ]; function Users() {}; Users.prototype = { list: function(done) { done(null, data.slice()); return this; }, find: function(options, done) { if( !options ) return done(new Error('illegal arguments')); if( !options.email ) return done(new Error('missing email')); var found; data.forEach(function(user) { found = (user.email === options.email) ? user : found; }); if( !found ) return done(new Error('user not found:' + options.email)); done(null, found); return this; }, add: function(options, done) { if( !options ) return done(new Error('illegal arguments')); if( !options.email ) return done(new Error('missing email')); if( !options.name ) return done(new Error('missing name')); if( !options.password ) return done(new Error('missing password')); var found; data.forEach(function(user) { found = user.email === options.email ? user : found; }); if( found ) return done(new Error('already exists user:' + options.email)); var user = { email: options.email, name: options.name, password: options.password }; data.push(user); done(null, user); return this; }, auth: function(options, done) { if( !options ) return done(new Error('illegal arguments')); if( !options.email ) return done(new Error('missing email')); this.find({ email: options.email }, function(err, user) { if( err ) return done(err); if( user.password !== options.password ) return done(new Error('invalid password')); done(null, user); }); return this; } }; module.exports = Users;
mit
DevManiaCK/SharpBot
Core/Properties/AssemblyInfo.cs
1394
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Core")] [assembly: AssemblyCopyright("Copyright © DevManiack 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8d921db3-a542-4410-a2b5-3e5aaae2047e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
AmrARaouf/algorithm-detection
graph-source-code/508-D/9673904.cpp
2649
//Language: GNU C++ #include <bits/stdc++.h> #define MAXN 200000 #define BASE 62 using namespace std; int n; int acnt; int ANS[MAXN+10]; void init() { } inline int c2i(char c) { if(islower(c)) return c - 'a'; else if(isupper(c)) return c - 'A' + 26; else return c - '0' + 52; } inline char i2c(int c) { if(c < 26) return c + 'a'; else if(c < 52) return c + 'A' - 26; else return c + '0' - 52; } inline int encode(char c1, char c2) { return c2i(c1) * BASE + c2i(c2); } struct Graph { int inDeg[MAXN+10]; int outDeg[MAXN+10]; int s, t; int max_node; /* struct node { int v; bool vis; node* next; } Nodes[2*MAXN+10], *adj[2*MAXN+10], *ecnt; */ int G[3844 + 2][3844 + 2]; void init() { max_node = 0; } inline void addedge(int u, int v) { max_node = max(max(u,v), max_node); outDeg[u]++; inDeg[v]++; G[u][v]++; } bool is_euler() { s = t = -1; int pos = -1; for (int i=0; i <= max_node; i++) { if (inDeg[i] != outDeg[i]) { if (inDeg[i] - outDeg[i] == 1 && t < 0) t = i; else if (outDeg[i] - inDeg[i] == 1 && s < 0) s = i; else return false; } if (inDeg[i] || outDeg[i]) pos = i; } if (s < 0) s = pos; acnt = 0; dfs(s); return acnt + 1 >= n; } void dfs(int u) { for (int v = 0; v <= max_node; v++) { while (G[u][v]) { G[u][v]--; dfs(v); ANS[acnt++] = v; } } } void prt() { printf("%c%c", i2c(s / BASE), i2c(s % BASE)); while (acnt) { int v = ANS[--acnt]; printf("%c", i2c(v % BASE)); } } } G; char buff[100]; void read() { G.init(); scanf("%d", &n); for (int i=1; i<=n; i++) { scanf("%s", buff); int u = encode(buff[0], buff[1]); int v = encode(buff[1], buff[2]); G.addedge(u, v); } } int main() { //freopen("tanya.in", "r", stdin); init(); read(); if (G.is_euler()) { printf("YES\n"); G.prt(); } else { printf("NO"); } }
mit
dawncold/home-monitor
monitor.py
1687
#! /bin/env python # coding: utf8 import subprocess import sys import tempfile import time from datetime import datetime import RPi.GPIO as GPIO import local_ftp CAMERA_PROGRAM = 'raspistill' GPIO_SOCKET_NUMBER = 26 def get_image_bytes(): return subprocess.check_output([CAMERA_PROGRAM, '-o', '-']) def install(): GPIO.setmode(GPIO.BOARD) GPIO.setup(GPIO_SOCKET_NUMBER, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(GPIO_SOCKET_NUMBER, GPIO.RISING, bouncetime=1000) def uninstall(): GPIO.remove_event_detect(GPIO_SOCKET_NUMBER) GPIO.cleanup(GPIO_SOCKET_NUMBER) def detect_loop(): while 1: if GPIO.event_detected(GPIO_SOCKET_NUMBER): capture() time.sleep(1) def capture(): print('capture...') try: image_bytes = get_image_bytes() except Exception: print('get image bytes failed') else: print('generated image bytes') with tempfile.TemporaryFile(mode='wb+') as f: f.write(image_bytes) f.seek(0) while 1: try: local_ftp.upload('{}.jpg'.format(datetime.now().isoformat()), f) except Exception: print('upload failed, retry') else: print('uploaded image') break if __name__ == '__main__': try: install() except Exception: print('setup GPIO failed') try: uninstall() except Exception: print('uninstall GPIO failed') sys.exit(-1) else: try: detect_loop() except Exception: uninstall()
mit
sea-watch/sea-watch-app
admin/resources/views/auth/password.blade.php
1488
@extends('layouts.app') @section('content') <div class="container-fluid"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading">Reset Password</div> <div class="panel-body"> {!! Form::open(array('url' => URL::to('password/email'), 'method' => 'post', 'files'=> true)) !!} <div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}"> {!! Form::label('email', "E-Mail Address", array('class' => 'control-label')) !!} <div class="controls"> {!! Form::text('email', null, array('class' => 'form-control')) !!} <span class="help-block">{{ $errors->first('email', ':message') }}</span> </div> </div> <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <button type="submit" class="btn btn-primary"> Send Password Reset Link </button> </div> </div> {!! FOrm::close() !!} </div> </div> </div> </div> </div> @endsection
mit
s3k/snapstats
app/assets/javascripts/snapstats/application.js
796
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require ./lib/jquery.min //= require ./lib/d3.min //= require ./lib/metricsgraphics.min //= require ./main/main_controller //= require ./users/users_controller //= require ./performances/performances_controller
mit
el-davo/platmatic
app/instance/market/market.action-types.ts
1023
export const FETCH_MARKET_ASSETS = 'FETCH_MARKET_ASSETS'; export const ADD_MARKET_ASSETS = 'ADD_MARKET_ASSETS'; export const CLEAR_MARKET_ASSETS = 'CLEAR_MARKET_ASSETS'; // Purchase export const REQUEST_FETCH_PURCHASE_PLANS = 'REQUEST_FETCH_PURCHASE_PLANS'; export const ADD_PURCHASE_PLANS = 'ADD_PURCHASE_PLANS'; export const REQUEST_PURCHASE_PLANS_FAILED = 'REQUEST_PURCHASE_PLANS_FAILED'; export const CLOSE_PURCHASE_PLANS = 'CLOSE_PURCHASE_PLANS'; export const SELECT_PURCHASE_PLAN = 'SELECT_PURCHASE_PLAN'; export const SHOW_PURCHASE_SELECT_SPACE = 'SHOW_PURCHASE_SELECT_SPACE'; export const HIDE_PURCHASE_SELECT_SPACE = 'HIDE_PURCHASE_SELECT_SPACE'; export const REQUEST_FETCH_PURCHASE_SPACES = 'REQUEST_FETCH_PURCHASE_SPACES'; export const UPDATE_PURCHASE_SPACES = 'UPDATE_PURCHASE_SPACES'; export const REQUEST_PURCHASE_SERVICE = 'REQUEST_PURCHASE_SERVICE'; export const SHOW_PURCHASE_COMPLETE_SCREEN = 'SHOW_PURCHASE_COMPLETE_SCREEN'; export const HIDE_PURCHASE_COMPLETE_SCREEN = 'HIDE_PURCHASE_COMPLETE_SCREEN';
mit
BBGONE/jRIApp
FRAMEWORK/CLIENT/jriapp/jriapp/databindsvc.ts
9721
/** The MIT License (MIT) Copyright(c) 2016 Maxim V.Tsapov */ import { LocaleERRS, Utils, IIndexer, IErrorHandler, IPromise, IVoidPromise, DummyError, BaseObject } from "jriapp_shared"; import { DATA_ATTR } from "./const"; import { IElViewFactory, IElView, IViewType, IApplication, IExports, ILifeTimeScope, IBindableElement, IConverter, IBindingOptions, IBindingInfo, IDataBindingService, IModuleLoader } from "./int"; import { bootstrap } from "./bootstrap"; import { LifeTimeScope } from "./utils/lifetime"; import { DomUtils } from "./utils/dom"; import { create as createModulesLoader } from "./utils/mloader"; import { getBindingOptions, Binding } from "./binding"; import { ViewChecks } from "./utils/viewchecks"; import { Parser } from "./utils/parser"; import { $ } from "./utils/jquery"; const utils = Utils, viewChecks = ViewChecks, dom = DomUtils, doc = dom.document, strUtils = utils.str, sys = utils.sys, checks = utils.check, boot = bootstrap, ERRS = LocaleERRS, parser = Parser; export function createDataBindSvc(root: Document | HTMLElement, elViewFactory: IElViewFactory): IDataBindingService { return new DataBindingService(root, elViewFactory); } class DataBindingService extends BaseObject implements IDataBindingService, IErrorHandler { private _root: Document | HTMLElement; private _elViewFactory: IElViewFactory; private _objLifeTime: ILifeTimeScope; private _mloader: IModuleLoader; constructor(root: Document | HTMLElement, elViewFactory: IElViewFactory) { super(); this._root = root; this._elViewFactory = elViewFactory; this._objLifeTime = null; this._mloader = createModulesLoader(); } private _toBindableElement(el: HTMLElement): IBindableElement { let val: string, allAttrs = el.attributes, attr: Attr, res: IBindableElement = { el: el, dataView: null, dataForm: null, expressions: [] }; for (let i = 0, n = allAttrs.length; i < n; i++) { attr = allAttrs[i]; if (strUtils.startsWith(attr.name, DATA_ATTR.DATA_BIND)) { val = attr.value.trim(); if (!val) { throw new Error(strUtils.format(ERRS.ERR_PARAM_INVALID, attr.name, "empty")); } if (val[0] !== "{" && val[val.length - 1] !== "}") val = "{" + val + "}"; res.expressions.push(val); } if (strUtils.startsWith(attr.name, DATA_ATTR.DATA_FORM)) { res.dataForm = attr.value.trim(); } if (strUtils.startsWith(attr.name, DATA_ATTR.DATA_VIEW)) { res.dataView = attr.value.trim(); } } if (!!res.dataView || res.expressions.length > 0) return res; else return null; } private _getBindableElements(scope: Document | HTMLElement): IBindableElement[] { let self = this, result: IBindableElement[] = [], allElems = dom.queryAll<HTMLElement>(scope, "*"); allElems.forEach(function (el) { let res = self._toBindableElement(el); if (!!res) result.push(res); }); return result; } private _cleanUp() { if (!!this._objLifeTime) { this._objLifeTime.destroy(); this._objLifeTime = null; } } private _getRequiredModuleNames(el: HTMLElement): string[] { let attr = el.getAttribute(DATA_ATTR.DATA_REQUIRE); if (!attr) return <string[]>[]; let reqArr = attr.split(","); let hashMap: IIndexer<any> = {}; reqArr.forEach(function (name) { if (!name) return; name = strUtils.fastTrim(name); if (!!name) hashMap[name] = name; }); return Object.keys(hashMap); } private _getOnlyDataFormElems(bindElems: IBindableElement[]): HTMLElement[] { return bindElems.filter((bindElem, index, arr) => { return !!bindElem.dataForm; }).map((bindElem, index, arr) => { return bindElem.el; }); } private _updDataFormAttr(bindElems: IBindableElement[]): void { //mark all dataforms for easier checking that the element is a dataform bindElems.forEach(function (bindElem) { if (!bindElem.dataForm && viewChecks.isDataForm(bindElem.el)) { bindElem.el.setAttribute(DATA_ATTR.DATA_FORM, "yes"); bindElem.dataForm = "yes"; } }); } private _bindElView(elView: IElView, bindElem: IBindableElement, lftm: ILifeTimeScope, isInsideTemplate: boolean, defSource: any) { let self = this, op: IBindingOptions, bind_attr: string, temp_opts: IBindingInfo[], info: IBindingInfo; lftm.addObj(elView); if (isInsideTemplate) viewChecks.setIsInsideTemplate(elView); //then create databinding if element has data-bind attribute bind_attr = bindElem.expressions.join(""); if (!!bind_attr) { temp_opts = parser.parseOptions(bind_attr); for (let j = 0, len = temp_opts.length; j < len; j += 1) { info = temp_opts[j]; op = getBindingOptions(info, elView, defSource); let binding = self.bind(op); lftm.addObj(binding); } } } private _bindTemplateElements(templateEl: HTMLElement): IPromise<ILifeTimeScope> { const self = this, defer = utils.defer.createDeferred<ILifeTimeScope>(true); try { let rootBindEl = self._toBindableElement(templateEl), bindElems: IBindableElement[], lftm = new LifeTimeScope(); if (!!rootBindEl && !!rootBindEl.dataForm) { //in this case process only this element bindElems = [rootBindEl]; } else { bindElems = self._getBindableElements(templateEl); if (!!rootBindEl) { bindElems.push(rootBindEl); } } //mark all dataforms for easier checking that the element is a dataform self._updDataFormAttr(bindElems); //select all dataforms inside the scope let forms = self._getOnlyDataFormElems(bindElems); let needBinding = bindElems.filter((bindElem) => { return !viewChecks.isInNestedForm(templateEl, forms, bindElem.el); }); needBinding.forEach(function (bindElem) { let elView = self._elViewFactory.getOrCreateElView(bindElem.el); self._bindElView(elView, bindElem, lftm, true, null); }); defer.resolve(lftm); } catch (err) { self.handleError(err, self); setTimeout(() => { defer.reject(new DummyError(err)); }, 0); } return defer.promise(); } bindTemplateElements(templateEl: HTMLElement): IPromise<ILifeTimeScope> { const self = this, requiredModules = self._getRequiredModuleNames(templateEl); let res: IPromise<ILifeTimeScope>; if (requiredModules.length > 0) { res = self._mloader.load(requiredModules).then(() => { return self._bindTemplateElements(templateEl); }); } else { res = self._bindTemplateElements(templateEl); } res.catch((err) => { utils.queue.enque(() => { self.handleError(err, self); }); }); return res; } bindElements(scope: Document | HTMLElement, defaultDataContext: any, isDataFormBind: boolean, isInsideTemplate: boolean): IPromise<ILifeTimeScope> { const self = this, defer = utils.defer.createDeferred<ILifeTimeScope>(true); scope = scope || doc; try { const bindElems = self._getBindableElements(scope), lftm = new LifeTimeScope(); if (!isDataFormBind) { //mark all dataforms for easier checking that the element is a dataform self._updDataFormAttr(bindElems); } //select all dataforms inside the scope const forms = self._getOnlyDataFormElems(bindElems); const needBinding = bindElems.filter((bindElem) => { return !viewChecks.isInNestedForm(scope, forms, bindElem.el); }); needBinding.forEach(function (bindElem) { let elView = self._elViewFactory.getOrCreateElView(bindElem.el); self._bindElView(elView, bindElem, lftm, isInsideTemplate, defaultDataContext); }); defer.resolve(lftm); } catch (err) { self.handleError(err, self); setTimeout(() => { defer.reject(new DummyError(err)); }, 0); } return defer.promise(); } setUpBindings(): IVoidPromise { const defScope = this._root, defaultDataContext = boot.getApp(), self = this; this._cleanUp(); let promise = this.bindElements(defScope, defaultDataContext, false, false); return promise.then((lftm) => { if (self.getIsDestroyCalled()) { lftm.destroy(); return; } self._objLifeTime = lftm; }); } bind(opts: IBindingOptions): Binding { return new Binding(opts); } destroy() { this._cleanUp(); this._elViewFactory = null; this._mloader = null; super.destroy(); } }
mit
cmmarslender/shortcode-cleaner
tasks/default.js
85
module.exports = function (grunt) { grunt.registerTask('default', ['js', 'css']); };
mit
mongodb/mongoid
lib/mongoid/cacheable.rb
971
# frozen_string_literal: true module Mongoid # Encapsulates behavior around caching. module Cacheable extend ActiveSupport::Concern included do cattr_accessor :cache_timestamp_format, instance_writer: false self.cache_timestamp_format = :nsec end # Print out the cache key. This will append different values on the # plural model name. # # If new_record? - will append /new # If not - will append /id-updated_at.to_s(cache_timestamp_format) # Without updated_at - will append /id # # This is usually called inside a cache() block # # @example Returns the cache key # document.cache_key # # @return [ String ] the string with or without updated_at def cache_key return "#{model_key}/new" if new_record? return "#{model_key}/#{_id}-#{updated_at.utc.to_s(cache_timestamp_format)}" if do_or_do_not(:updated_at) "#{model_key}/#{_id}" end end end
mit
TeskeVirtualSystem/jpak
tools/JPAK Explorer Win/JPAKTool/jpaktool.cs
7506
/********************************************** * _ ____ _ _ __ _ ___ * * | | _ \ / \ | |/ / __ _/ | / _ \ * * _ | | |_) / _ \ | ' / \ \ / / || | | | * *| |_| | __/ ___ \| . \ \ V /| || |_| | * * \___/|_| /_/ \_\_|\_\ \_/ |_(_)___/ * * * *Multiuse Javascript Package * *By: Lucas Teske * *https://github.com/TeskeVirtualSystem/jpak * **********************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Web.Script.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Windows.Forms; using System.IO; using System.Reflection; using System.Drawing; namespace JPAK { public class JPAKTool { // The File Types Image list static ImageList FileTypes; // The File Extensions Map. {extension, imagefile} static Dictionary<string, string> FileExts = new Dictionary<string, string>() { {"all","binary"}, {"a","applix"}, {"c","source_c"}, {"cpp","source_cpp"}, {"js","source"}, {"f","source_f"}, {"h","source_h"}, {"j","source_j"}, {"java","source_java"}, {"l","source_l"}, {"o","source_o"}, {"p","source_p"}, {"php","source_php"}, {"pl","source_pl"}, {"py","source_py"}, {"s","source_s"}, {"sh","shellscript"}, {"doc","document"}, {"xls","spreadsheet"}, {"odt","document"}, {"ods","spreadsheet"}, {"tar","tar"}, {"gz","tar"}, {"zip","tar"}, {"jpak","tar"}, {"jpg","image"}, {"jpeg","image"}, {"png","image"}, {"gif","image"}, {"mp3","sound"}, {"ogg","sound"}, {"wav","sound"}, {"avi","video"}, {"mp4","video"}, {"ogv","video"}, {"mpg","video"}, {"mkv","video"}, {"txt","txt2"}, {"iso","cdtrack"}, {"ttf","font_type1"}, {"html","html"}, {"htm","html"}, {"mid","midi"}, {"midi","midi"}, {"tpl","templates"}, {"coord","templates"}, {"folder","folder"} }; // This function builds the image list static void BuildFileTypeImageList() { FileTypes = new ImageList(); FileTypes.ImageSize = new Size(32, 32); System.Resources.ResourceManager myManager = new System.Resources.ResourceManager("JPAK.FileImages", Assembly.GetExecutingAssembly()); foreach (KeyValuePair<String, String> entry in FileExts) FileTypes.Images.Add(entry.Key, (Image)myManager.GetObject(entry.Value)); } //Builds the image list if its necessary, and returns it public static ImageList GetFileTypeImageList() { if (FileTypes == null) BuildFileTypeImageList(); return FileTypes; } //Returns the compatible file extension to use with imagelist public static String GetFileExt(String filename) { String[] extarray = filename.Split('.'); String ext = extarray[extarray.Length - 1]; if (extarray.Length == 1) return "all"; foreach (KeyValuePair<String, String> entry in FileExts) if (entry.Key.Equals(ext)) return ext; return "all"; } //Exports a file from JPAK Volume public static void ExportFile(FileStream volume, String filepath, int offset, int size) { FileStream fs = File.Create(filepath, 2048, FileOptions.None); volume.Seek(offset, SeekOrigin.Begin); byte[] buffer = new byte[2048]; int readsize = 0; int chunksize = 2048; while (readsize < size) { chunksize = size - readsize > 2048 ? 2048 : size - readsize; volume.Read(buffer, 0, chunksize); fs.Write(buffer, 0, chunksize); readsize += chunksize; } fs.Close(); } //Checks the magic number of JPAK public static bool CheckJPAK(FileStream volume) { volume.Seek(0, SeekOrigin.Begin); byte[] MagicNumber = new byte[5]; volume.Read(MagicNumber, 0, 5); volume.Seek(0, SeekOrigin.Begin); String magic = Encoding.UTF8.GetString(MagicNumber); return (magic.Equals("JPAK1")); } //Gets the filetable tree from JPAK File public static DirectoryEntry GetFileTable(FileStream volume) { volume.Seek(-4, SeekOrigin.End); byte[] bOffset = new byte[4]; volume.Read(bOffset, 0, 4); int Offset = BitConverter.ToInt32(bOffset, 0); volume.Seek(0, SeekOrigin.End); long VolumeSize = volume.Position; volume.Seek(Offset, SeekOrigin.Begin); byte[] filetable = new byte[VolumeSize - Offset - 4]; volume.Read(filetable, 0, (int)(VolumeSize - Offset - 4)); String jsonstr = Encoding.UTF8.GetString(filetable); return ParseJSONDirectory(jsonstr); } //Gets the filetable jsonstring from JPAK File public static String GetFileTableS(FileStream volume) { volume.Seek(-4, SeekOrigin.End); byte[] bOffset = new byte[4]; volume.Read(bOffset, 0, 4); int Offset = BitConverter.ToInt32(bOffset, 0); volume.Seek(0, SeekOrigin.End); long VolumeSize = volume.Position; volume.Seek(Offset, SeekOrigin.Begin); byte[] filetable = new byte[VolumeSize - Offset - 4]; volume.Read(filetable, 0, (int)(VolumeSize - Offset - 4)); String jsonstr = Encoding.UTF8.GetString(filetable); return jsonstr; } //Parses a JSON String representing a directory entry public static DirectoryEntry ParseJSONDirectory(String dirjson) { JObject jdec = JsonConvert.DeserializeObject<JObject>(dirjson); return GetFileTree(jdec, jdec["name"].ToString(), jdec["path"].ToString()); } //Returns the Directory Tree public static DirectoryEntry GetFileTree(JObject FileTable) { return GetFileTree(FileTable, "root", "/"); } public static DirectoryEntry GetFileTree(JObject FileTable, String name, String path) { DirectoryEntry root = new DirectoryEntry(name, path); foreach (JProperty file in FileTable["files"]) { FileEntry f = file.Value.ToObject<FileEntry>(); root.AddFile(f); } foreach (JProperty dir in FileTable["directories"]) { String jdir = dir.Value.ToString(); DirectoryEntry d = ParseJSONDirectory(jdir); root.AddDirectory(d); } return root; } } }
mit
ssleptsov/ng2-select
components/select/select.d.ts
2116
import { EventEmitter, ElementRef } from '@angular/core'; import { SelectItem } from './select-item'; import { IOptionsBehavior } from './select-interfaces'; export declare class Select { element: ElementRef; allowClear: boolean; placeholder: string; initData: Array<any>; multiple: boolean; items: Array<any>; disabled: boolean; data: EventEmitter<any>; selected: EventEmitter<any>; removed: EventEmitter<any>; typed: EventEmitter<any>; options: Array<SelectItem>; itemObjects: Array<SelectItem>; active: Array<SelectItem>; activeOption: SelectItem; private offSideClickHandler; private inputMode; private optionsOpened; private inputValue; private _items; private _disabled; private childrenBehavior; private genericBehavior; private behavior; constructor(element: ElementRef); private focusToInput(value?); private matchClick(e); private mainClick(e); private open(); ngOnInit(): void; ngOnDestroy(): void; private getOffSideClickHandler(context); remove(item: SelectItem): void; doEvent(type: string, value: any): void; private hideOptions(); inputEvent(e: any, isUpMode?: boolean): void; private selectActiveMatch(); private selectMatch(value, e?); private selectActive(value); private isActive(value); } export declare class Behavior { actor: Select; optionsMap: Map<string, number>; constructor(actor: Select); private getActiveIndex(optionsMap?); fillOptionsMap(): void; ensureHighlightVisible(optionsMap?: Map<string, number>): void; } export declare class GenericBehavior extends Behavior implements IOptionsBehavior { actor: Select; constructor(actor: Select); first(): void; last(): void; prev(): void; next(): void; filter(query: RegExp): void; } export declare class ChildrenBehavior extends Behavior implements IOptionsBehavior { actor: Select; constructor(actor: Select); first(): void; last(): void; prev(): void; next(): void; filter(query: RegExp): void; }
mit
wonghoifung/tips
leetcode/easy_reverse_string.cpp
698
#include <string> #include <vector> #include <iostream> #include <map> #include <unordered_map> #include <unordered_set> #include <set> #include <queue> #include <deque> #include <stack> #include <array> #include <memory> #include <sstream> #include <functional> #include <algorithm> #include <bitset> #include <tuple> #include <numeric> #include <initializer_list> #include <math.h> #include <assert.h> #include <time.h> #include <stdint.h> #include <stdarg.h> using namespace std; class Solution { public: string reverseString(string s) { reverse(s.begin(), s.end()); return s; } }; int main() { Solution s; cout << s.reverseString("hello") << endl; std::cin.get(); return 0; }
mit
GustavHager/pig-latinizer
include/TranslatorGUI.hpp
460
#ifndef TRANSLATOR_GUI_HPP #define TRANSLATOR_GUI_HPP #include <SFML/Graphics.hpp> #include <TGUI/TGUI.hpp> #include "Translator.hpp" #include "InformativeAssert.hpp" class TranslatorGUI { public: TranslatorGUI(); void setTranslator(Translator * translator); void run(); private: Translator * activeTranslator; tgui::EditBox::Ptr editBox; tgui::ChatBox::Ptr chatbox; bool isEvenColor; void translateInput(); }; #endif
mit
Rodinia/php-UitzendingGemist4DuneHD
uitzendinggemist/lib/lib_ugemist.php
15922
<?php require_once dirname(__FILE__).'/util.php'; // -------------------- Functions ---------------------- # Suppress DOM warnings libxml_use_internal_errors(true); function wgetEpisodesWeekarchief($ug_search_url, $max_pages, $page_offset = 1) { $episodes = array(); // result $itemQueries = array(); // result $itemQueries['program'] = "h2/a"; $itemQueries['episode'] = "h3/a"; $itemQueries['href'] = "h3/a/@href"; $itemQueries['data-images'] = "../div[@class='image']/a/img/@data-images"; $result = privWgetEpisodes($ug_search_url, "//li[@class='broadcast active']/div[@class='info']", $itemQueries, $max_pages, $page_offset); foreach($result as $item) { $episodes[] = array( 'refid' => substr($item['href'], 14), 'title' => $item['program'].' - '.$item['episode'], 'img' => getImgSrcFromDataImages($item['data-images']) ); } return $episodes; } function wgetEpisodesByProgram($ug_search_url, $max_pages, $page_offset = 1) { $episodes = array(); // result $itemQueries = array( 'episode' => 'h3/a', 'href' => 'h3/a/@href', 'data-images' => "../div[@class='image']/a/img/@data-images", 'description' => "."); $result = privWgetEpisodes($ug_search_url, "//ul/li[@class='episode active']/div[@class='description']", $itemQueries, $max_pages, $page_offset); foreach($result as $item) { $description = false; foreach(preg_split("/((\r?\n)|(\r\n?))/", trim($item['description'])) as $line) { $description = trim($line); } $episodes[] = array( 'refid' => substr($item['href'], 14), 'img' => getImgSrcFromDataImages($item['data-images']), 'title' => $item['episode'], 'description' => $description); } return $episodes; } function getImgSrcFromDataImages($data_images) { $images = explode(',', trim($data_images, '[]')); $img = trim($images[0], '"'); return str_replace('140x79', '280x148', $img); } function wgetProgramsAZ($suffix, $max_pages, $page_offset) { return wgetPrograms('http://www.uitzendinggemist.nl/programmas/'.$suffix.'?display_mode=detail', $max_pages, $page_offset); } function wgetPrograms($ug_search_url, $max_pages = 1, $page_offset = 1) { $itemQueries = array(); // result $itemQueries['name'] = "h2/a"; $itemQueries['href'] = "h2/a/@href"; $itemQueries['data-images'] = "../div[@class='image']/a/img/@data-images"; $query="/html//li[@class='series']/div[@class='info']"; return privWgetEpisodes($ug_search_url, $query, $itemQueries, $max_pages, $page_offset); } function wgetSearchPrograms($ug_search_url, $max_pages = 1, $page_offset = 1) { $itemQueries = array(); // result $itemQueries['name'] = "h3/a"; $itemQueries['href'] = "h3/a/@href"; $itemQueries['data-images'] = "div[@class='img']/a/img/@data-images"; $query="//ul[@id='series-result']/li[@class='series knav']/div[@class='wrapper']"; return privWgetEpisodes($ug_search_url, $query, $itemQueries, $max_pages, $page_offset); } function privWgetEpisodes($ug_search_url, $query, $itemQueries, $max_pages, $page_offset = 1) { $episodes = array(); // result $pagefound = false; $page = $page_offset; $num = 0; do { $url = $ug_search_url.(strpos($ug_search_url, '?') ? '&':'?').'page='.$page++; //echo "<p>Read from url = $url</p>\n"; $dom = loadHtmlAsDom($url); $xpath = new DOMXpath($dom); $pagefound = false; foreach($xpath->query($query) as $episode) { $pagefound = true; $items = array(); // result foreach($itemQueries as $itemKey => $itemQuery) { $items[$itemKey] = $xpath->query( $itemQuery, $episode)->item(0)->nodeValue; //echo "<p>$itemKey => $itemQuery = ".$items[$itemKey]."</p>\n"; } $episodes[] = $items; } } while($pagefound && $page<($page_offset + $max_pages)); return $episodes; } // Resolve remote-episode-ID base on local-episode-ID function wgetEpisodeData($localepiid) { //echo "# wgetEpisodeId($localepiid)\n"; //echo '# url = http://www.uitzendinggemist.nl/afleveringen/'.$localepiid."\n"; $dom = loadHtmlAsDom('http://www.uitzendinggemist.nl/afleveringen/'.$localepiid); $xpath = new DOMXpath($dom); $ed = $xpath->query("//span[@id='episode-data']")->item(0); $eda = array(); foreach ($ed->attributes as $name => $value) $eda[$name] = $value->value; //print_r($eda); return $eda; } function wgetEpisodeId($localepiid) { $epData = wgetEpisodeData($localepiid); return $epData['data-episode-id']; } // compressie_formaat should be one of: wmv|mov|wvc1 // compressie_kwaliteit should be one of: sb|bb|std (low to high) function getStreamUrl($epiid, $secret, $compressie_formaat = 'mov', $compressie_kwaliteit = 'bb') { foreach(getStreams($epiid, $secret) as $stream) { if( $stream->getAttribute('compressie_formaat') == $compressie_formaat && $stream->getAttribute('compressie_kwaliteit') == $compressie_kwaliteit) { foreach($stream->getElementsByTagName('streamurl') as $streamurl) return trim($streamurl->nodeValue); //.'start=0'; } } return NULL; } function getStreams($ed) { //print_r($ed); if( $ed['data-player-id'] != null ) { return getStreamsByPlayerId($ed['data-player-id']); } else { $secret = getSessionKey(); return getStreamsByEpisodeId($ed['data-episode-id'], $secret); } } // http://ida.omroep.nl/odi/?prid=VPWON_1219719&puboptions=adaptive,h264_bb,h264_sb,h264_std&adaptive=yes&part=1&token=gbq5f6ov0jqv05u5lj5t98p5j3&callback=jQuery18207517273030243814_1395569608767&_=1395569609791 function makePlayerStreamInfoUrl($playerid, $token = null, $adaptive = false) { $time = time(); if($token === null) $token = getPlayerToken(); return 'http://ida.omroep.nl/odi/?prid='.$playerid. '&puboptions=adaptive,h264_bb,h264_sb,h264_std,wmv_bb,wmv_sb,wvc1_std'. '&adaptive='.($adaptive ? 'yes' : 'no'). '&part=1'. '&token='.$token. '&_='.$time; } function get_M3U8_url($playerid, $token = null) { $url = makePlayerStreamInfoUrl($playerid, null, true); $json = getJson($url); if($json['success'] == 1) { $streamInfoUrl = $json['streams'][0]; $streamInfoUrl = str_replace('type=jsonp&callback=?', 'json', $streamInfoUrl); // enforce pure JSON $json = getJson($streamInfoUrl); if($json['errorcode'] == 0) { return $json['url']; } } return null; } function getStreamsByPlayerId($playerid, $token = null) { $url = makePlayerStreamInfoUrl($playerid, $token); //echo "# url = $url\n"; return getJson($url); } function getJson($url) { $contents = curlGet($url); $contents = utf8_encode($contents); return json_decode($contents, true); } function getPlayerToken() { $js = file_get_contents('http://ida.omroep.nl/npoplayer/i.js'); // Is there a way to get the token directly in JSON? return jsToJson(utf8_encode($js)); } // Strips wrapping function to only the JSON content function jsToJson($js) { preg_match('/"([^"]*)"/', $js, $matches); return $matches[1]; } function getStreamsByEpisodeId($epiid, $secret) { //echo "# getStreams($epiid, $secret)\n"; $infoUrl = makeStreamInfoUrl($epiid, $secret); //echo "# infoUrl=$infoUrl\n"; $dom = new DOMDocument(); //echo "# wget Stream Info: $infoUrl\n"; //$html = $dom->loadHTMLFile($infoUrl); if( !$dom->loadXML(curlGet($infoUrl)) ) die('Failed to load XML stream info from: '.$infoUrl); $xpath = new DOMXpath($dom); $domnodelist = $xpath->query("//stream"); // Convert to array $streams = array(); foreach($domnodelist as $stream) { $streams[] = $stream; } // Sort array return sortStreams($streams); } // Sort streams on quality, and most suitable for Dune HD function sortStreams($streams) { usort($streams, "stream_cmp"); return $streams; } // lowest number, first in stream list function stream_cmp($stra, $strb) { // first sort on Quality (bandwith) $result = stream_cmp_quality($stra, $strb); // if and only if quality is equel, sort on format return $result == 0 ? stream_cmp_format($stra, $strb) : $result; } function stream_cmp_quality($stra, $strb) { // Compare stream quality (bandwith) $cka = $stra->getAttribute('compressie_kwaliteit'); $ckb = $strb->getAttribute('compressie_kwaliteit'); return compressieKwaliteitToNum($cka) - compressieKwaliteitToNum($ckb); } function stream_cmp_format($stra, $strb) { // Compare format $cfa = $stra->getAttribute('compressie_formaat'); $cfb = $strb->getAttribute('compressie_formaat'); return compressieFormaatToNum($cfa) - compressieFormaatToNum($cfb); } function compressieFormaatToNum($compressieFormaat) { switch($compressieFormaat) { case 'mov' : return 0; // MP4/H.264 case 'wvc1': return 1; // WMV/MMS (Windows Media Video 9 Advanced Profile) case 'wmv' : return 2; // WMV } trigger_error('Unsupported compressie-formaat: '.$compressieFormaat); } function compressieKwaliteitToNum($compressieKwaliteit) { switch($compressieKwaliteit) { case 'std': return 0; // ?? best quality 640x360, 1 Mbit/sec case 'bb' : return 1; // broadband 320x180 = (WMA 9.1 / 500 kbit/s) case 'sb' : return 2; // slowband 160 x 90 = (WMA 9.1 / 100 kbit/s) } trigger_error('Unsupported compressie-kwaliteit: '.$compressieKwaliteit); } function makeStreamInfoUrl($epiid, $secret) { //echo "# makeStreamUrl(epiid=$epiid, secret=$secret)\n"; return 'http://pi.omroep.nl/info/stream/aflevering/'. $epiid .'/'. episodeHash($epiid, $secret); } function makeAfleveringMetaDataUrl($epiid, $secret) { return 'http://pi.omroep.nl/info/metadata/aflevering/'. $epiid .'/'. episodeHash($epiid, $secret); } function getAfleveringMetaDataUrl($epiid, $secret) { $url = makeAfleveringMetaDataUrl($epiid, $secret); //$dom = new DOMDocument(); //$html = $dom->loadHTMLFile($url); $dom = loadHtmlAsDom($url); $result = array(); foreach($dom->getElementsByTagName('aflevering') as $aflevering) { foreach($aflevering->getElementsByTagName('serie') as $serie) { $result['serie_id'] = $serie->getAttribute('id'); foreach($serie->getElementsByTagName('serie') as $serie_titel) { $result['serie_titel'] = $serie_titel->nodeValue; } } $result['prid'] = $aflevering->getAttribute('prid'); $streamSense = $aflevering->getElementsByTagName('streamsense')->item(0); $result['sko_dt'] = $streamSense->getElementsByTagName('sko_dt')->item(0)->nodeValue; } return $result; } function makePlaylistSerieMetaDataUrl($serie_id, $secret) { return 'http://pi.omroep.nl/info/playlist/serie/'. $serie_id .'/'. episodeHash($serie_id, $secret); } function makeStreamUrl($epiid, $secret) { //echo "# makeStreamUrl(epiid=$epiid, secret=$secret)\n"; return 'http://pi.omroep.nl/info/stream/aflevering/'. $epiid .'/'. episodeHash($epiid, $secret); } // Berekent episode hash voor uitzending gemist function episodeHash($episode, $secret) { $hashInput = $episode.'|'.$secret[1]; //echo "hash-input: ".$hashInput; $md5 = md5($hashInput); return strtoupper($md5); } function getSessionKey() { $sessionUrl = 'http://pi.omroep.nl/info/security/'; $rawKey = wgetSessionKey($sessionUrl); $decodedKey = base64_decode($rawKey); return explode('|', $decodedKey); } // Extraxts stream URL from SMIL (Content-Type: application/smil) function wgetVideoSrcFromSmil($urlToSmil) { $dom = new DOMDocument(); $dom->loadHTMLFile($urlToSmil); $xpath = new DOMXpath($dom); $videos = $xpath->query("//video"); foreach($videos as $video) { return $video->getAttribute('src'); } } // Download session key /* ToDo function wgetSessionKey($sessionUrl) { $doc = new DOMDocument(); $html = $doc->loadHTMLFile($sessionUrl); $xpath = new DOMXpath($doc); return $xpath->query("/session/key")->nodeValue; }*/ // Download session key function wgetSessionKey($sessionUrl) { echo "# wgetSessionKey $sessionUrl\n"; $dom = loadXmlAsDom($sessionUrl); $xpath = new DOMXpath($dom); return $xpath->query("/session/key")->item(0)->nodeValue; return $result->item(0)->nodeValue; /*$dom = loadHtmlAsDom($sessionUrl); // ToDo: use XML method foreach($dom->getElementsByTagName('session') as $session) { foreach($session->getElementsByTagName('key') as $key) { return $key->nodeValue; } } return 0;*/ } function wgetProgramPrefixLinks() { $result = array(); $doc = loadHtmlAsDom('http://www.uitzendinggemist.nl/programmas/'); $xpath = new DOMXpath($doc); $elements = $xpath->query("/html/body/div[@id='content']/div[@id='series-index']/div[1]/div[@id='series-index-letters']/ol/li/a"); foreach($elements as $element) { $href = $element->getAttribute('href'); $programId=substr($href, 12); $result[] = $programId; } return $result; } function getLastPage($xpath, $divid) { $elements = $xpath->query("/html/body//div[@id='".$divid."']/div[@class='pagination']/a"); $maxPage = 1; foreach ($elements as $element) { $value = $element->nodeValue; if(is_numeric($value)) $maxPage = $value; } return $maxPage; } function getProgamHtmlXpath($url, $page) { $ug_url = $url.(strpos($url, '?') === false ? '?' : '&').'page='.$page; //echo "# Loading url: $ug_url\n"; //$doc = new DOMDocument(); //$doc->loadHTMLFile($ug_url); $dom = loadHtmlAsDom($ug_url); $dom->strictErrorChecking = false; return new DOMXpath($dom); } function wgetBroadcasters() { $query="/html/body//div[@id='broadcasters-page']/ol[@class='broadcasters']/li/a"; $xpath = getProgamHtmlXpath('http://www.uitzendinggemist.nl/omroepen', 1); $result = array(); $nodeList = $xpath->query($query); foreach ($nodeList as $href) $result[] = $href; return $result; } function wgetGenres() { $query="/html/body//div[@id='genres-page']/ol[@class='genres']/li/a"; $xpath = getProgamHtmlXpath('http://www.uitzendinggemist.nl/genres', 1); $result = array(); $nodeList = $xpath->query($query); foreach ($nodeList as $href) $result[] = $href; return $result; } function wgetRegios() { $query="/html/body//div[@id='broadcasters-page']/ol[@class='broadcasters']/li/a"; $xpath = getProgamHtmlXpath('http://www.uitzendinggemist.nl/omroepen/regio', 1); $result = array(); $nodeList = $xpath->query($query); foreach ($nodeList as $href) $result[] = $href; return $result; } ?>
mit
abhacid/cAlgoBot
Sources/Robots/News Robot/News Robot/Properties/AssemblyInfo.cs
457
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("News Robot")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("News Robot")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("35f19c43-c7cc-4f53-b8e0-61caaf9cd8e8")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
lighthorseinnovation/TableauAPI
TableauAPI/RESTHelpers/TableauServerWebClient.cs
1186
using System; using System.Net; namespace TableauAPI.RESTHelpers { /// <summary> /// Subclass of the WebClient object that allows use to set a larger/custom timout value so that longer downloads succeed /// </summary> internal class TableauServerWebClient : WebClient { public readonly int WebRequestTimeout; public const int DefaultLongRequestTimeOutMs = 15 * 60 * 1000; //15 minutes * 60 sec/minute * 1000 ms/sec /// <summary> /// Constructor /// </summary> /// <param name="timeoutMs"></param> public TableauServerWebClient(int timeoutMs = DefaultLongRequestTimeOutMs) { this.WebRequestTimeout = timeoutMs; } /// <summary> /// Returns a Web Request object (used for download operations) with /// our specifically set timeout /// </summary> /// <param name="address"></param> /// <returns></returns> protected override WebRequest GetWebRequest(Uri address) { var request = base.GetWebRequest(address); request.Timeout = WebRequestTimeout; return request; } } }
mit
nvazquez/Turtlebots
pysamples/set_rgb.py
663
# Copyright (c) 2009-11, Walter Bender # This procedure is invoked when the user-definable block on the # "extras" palette is selected and expanded to 3 arguments. # Usage: Import this code into a Python (user-definable) block. # First, expand the Python block to reveal three numerics arguments. # Set these values to the desired red, green, and blue. When the code # is run, the red, green, and blue values are used to set the pen # color. def myblock(tw, rgb_array): ''' Set rgb color from values ''' tw.canvas.fgrgb = [(int(rgb_array[0]) % 256), (int(rgb_array[1]) % 256), (int(rgb_array[2]) % 256)]
mit
juusokorhonen/solartools
backend/__init__.py
1143
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from flask import Flask, url_for, abort, flash, redirect, session, request, g, current_app from flask_appconfig import AppConfig, HerokuConfig from flask.ext.cors import CORS from .errorhandler import register_errorhandlers from .rest import restapi, restapi_bp def create_app(config=None, configfile=None): """ Creates a Flask app using the provided configuration. Keyword arguments: :param config: Config object or None (default: None) :param configfile: - Name and path to configfile (default: None) :returns: Flask application """ app = Flask(__name__) # Configure app HerokuConfig(app, default_settings=config, configfile=configfile) # Set up CORS CORS(app) # Development-specific functions if (app.debug): pass # Testing-specifig functions if (app.config.get('TESTING')): pass # Production-specific functions if (app.config.get('PRODUCTION')): pass # Add REST api app.register_blueprint(restapi_bp) return app
mit