code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php // Load DB include "ConfigDb.php"; // Load core classes include "core/Model.php"; include "core/Controller.php"; // Load model classes - they extend Model.php include "model/AddressesModel.php"; include "model/EmployeesModel.php"; // Load Controller class - it extends Controller.php include 'controller/FilterInput.php'; include "controller/MainController.php"; include 'controller/EmployeeController.php'; include 'controller/AddressController.php'; include 'controller/RouteController.php'; $route = new RouteController(); $route->route();
stoyantodorovbg/PHP-Web-Development-Basics
Homework Working with Forms in PHP/employee2/index.php
PHP
mit
559
package action import ( "os" "path/filepath" "github.com/gopasspw/gopass/internal/tree" "github.com/gopasspw/gopass/internal/config" "github.com/gopasspw/gopass/internal/out" "github.com/gopasspw/gopass/internal/store/leaf" "github.com/gopasspw/gopass/pkg/ctxutil" "github.com/gopasspw/gopass/pkg/fsutil" "github.com/gopasspw/gopass/pkg/termio" "github.com/urfave/cli/v2" ) // Fsck checks the store integrity func (s *Action) Fsck(c *cli.Context) error { s.rem.Reset("fsck") ctx := ctxutil.WithGlobalFlags(c) if c.IsSet("decrypt") { ctx = leaf.WithFsckDecrypt(ctx, c.Bool("decrypt")) } out.Printf(ctx, "Checking store integrity ...") // make sure config is in the right place // we may have loaded it from one of the fallback locations if err := s.cfg.Save(); err != nil { return ExitError(ExitConfig, err, "failed to save config: %s", err) } // clean up any previous config locations oldCfg := filepath.Join(config.Homedir(), ".gopass.yml") if fsutil.IsFile(oldCfg) { if err := os.Remove(oldCfg); err != nil { out.Errorf(ctx, "Failed to remove old gopass config %s: %s", oldCfg, err) } } // display progress bar t, err := s.Store.Tree(ctx) if err != nil { return ExitError(ExitUnknown, err, "failed to list stores: %s", err) } pwList := t.List(tree.INF) bar := termio.NewProgressBar(int64(len(pwList)*2), ctxutil.IsHidden(ctx)) ctx = ctxutil.WithProgressCallback(ctx, func() { bar.Inc() }) ctx = out.AddPrefix(ctx, "\n") // the main work in done by the sub stores if err := s.Store.Fsck(ctx, c.Args().Get(0)); err != nil { return ExitError(ExitFsck, err, "fsck found errors: %s", err) } bar.Done() return nil }
franciscocpg/gopass
internal/action/fsck.go
GO
mit
1,676
require "codeclimate-test-reporter" CodeClimate::TestReporter.start # This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # Require this file using `require "spec_helper"` to ensure that it is only # loaded once. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| config.run_all_when_everything_filtered = true config.filter_run :focus # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = "random" config.expect_with :rspec do |c| # Disable old "should" syntax for expressions c.syntax = :expect end end
mutiny/attributable
spec/spec_helper.rb
Ruby
mit
854
// Copyright (c) Simple Injector Contributors. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for license information. namespace SimpleInjector.Diagnostics { using System; using System.Diagnostics; using SimpleInjector.Advanced; /// <summary> /// Diagnostic result for a warning about a /// component that depends on a service with a lifestyle that is shorter than that of the component. /// For more information, see: https://simpleinjector.org/dialm. /// </summary> [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ", nq}")] public class LifestyleMismatchDiagnosticResult : DiagnosticResult { internal LifestyleMismatchDiagnosticResult( Type serviceType, string description, KnownRelationship relationship) : base( serviceType, description, DiagnosticType.LifestyleMismatch, DiagnosticSeverity.Warning, relationship) { this.Relationship = relationship; } /// <summary>Gets the object that describes the relationship between the component and its dependency.</summary> /// <value>A <see cref="KnownRelationship"/> instance.</value> public KnownRelationship Relationship { get; } } }
simpleinjector/SimpleInjector
src/SimpleInjector/Diagnostics/LifestyleMismatchDiagnosticResult.cs
C#
mit
1,347
import Helper, { helper as buildHelper } from '@ember/component/helper'; import { inlineSvg } from 'ember-inline-svg/helpers/inline-svg'; import SVGs from '../svgs'; import Ember from 'ember'; let helper; if (Helper && buildHelper) { helper = buildHelper(function ([path], options) { return inlineSvg(SVGs, path, options); }); } else { helper = Ember.Handlebars.makeBoundHelper(function (path, options) { return inlineSvg(SVGs, path, options.hash || {}); }); } export default helper;
minutebase/ember-inline-svg
app/helpers/inline-svg.js
JavaScript
mit
502
'use strict'; var path = require('path'); var Stream = require('readable-stream'); var BufferStreams = require('bufferstreams'); var ttf2woff2 = require('ttf2woff2'); var PluginError = require('plugin-error'); var replaceExtension = require('replace-ext'); var PLUGIN_NAME = 'gulp-ttf2woff2'; // File level transform function function ttf2woff2Transform() { // Return a callback function handling the buffered content return function ttf2woff2TransformCb(err, buf, cb) { // Handle any error if(err) { return cb(new PluginError(PLUGIN_NAME, err, { showStack: true })); } // Use the buffered content try { buf = ttf2woff2(buf); return cb(null, buf); } catch(err2) { return cb(new PluginError(PLUGIN_NAME, err2, { showStack: true })); } }; } // Plugin function function ttf2woff2Gulp(options) { var stream = new Stream.Transform({ objectMode: true }); options = options || {}; options.ignoreExt = options.ignoreExt || false; options.clone = options.clone || false; stream._transform = function ttf2woff2GulpTransform(file, unused, done) { var cntStream; var newFile; // When null just pass through if(file.isNull()) { stream.push(file); done(); return; } // If the ext doesn't match, pass it through if((!options.ignoreExt) && '.ttf' !== path.extname(file.path)) { stream.push(file); done(); return; } // Fix for the vinyl clone method... // https://github.com/wearefractal/vinyl/pull/9 if(options.clone) { if(file.isBuffer()) { stream.push(file.clone()); } else { cntStream = file.contents; file.contents = null; newFile = file.clone(); file.contents = cntStream.pipe(new Stream.PassThrough()); newFile.contents = cntStream.pipe(new Stream.PassThrough()); stream.push(newFile); } } file.path = replaceExtension(file.path, '.woff2'); // Buffers if(file.isBuffer()) { try { file.contents = ttf2woff2(file.contents); } catch(err) { stream.emit('error', new PluginError(PLUGIN_NAME, err, { showStack: true, })); } // Streams } else { file.contents = file.contents.pipe(new BufferStreams(ttf2woff2Transform())); } stream.push(file); done(); }; return stream; } // Export the file level transform function for other plugins usage ttf2woff2Gulp.fileTransform = ttf2woff2Transform; // Export the plugin main function module.exports = ttf2woff2Gulp;
nfroidure/gulp-ttf2woff2
src/index.js
JavaScript
mit
2,569
public class Solution { public int lengthOfLongestSubstringTwoDistinct(String s) { int[] map = new int[128]; int count = 0, start = 0, end = 0, d = 0; while (end < s.length()) { if (map[s.charAt(end++)]++ == 0) count++; while (count > 2) if(map[s.charAt(start++)]-- == 1) count--; d = Math.max(d, end - start); } return d; } }
zhugejunwei/Algorithms-in-Java-Swift-CPP
String/159. Longest Substring with At Most Two Distinct Characters.java
Java
mit
411
<?php /** * This class defines the structure of the 'category' table. * * * * This map class is used by Propel to do runtime db structure discovery. * For example, the createSelectSql() method checks the type of a given column used in an * ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive * (i.e. if it's a text column type). * * @package propel.generator.kreader.map */ class CategoryTableMap extends TableMap { /** * The (dot-path) name of this class */ const CLASS_NAME = 'kreader.map.CategoryTableMap'; /** * Initialize the table attributes, columns and validators * Relations are not initialized by this method since they are lazy loaded * * @return void * @throws PropelException */ public function initialize() { // attributes $this->setName('category'); $this->setPhpName('Category'); $this->setClassname('Category'); $this->setPackage('kreader'); $this->setUseIdGenerator(true); // columns $this->addPrimaryKey('id', 'Id', 'INTEGER', true, null, null); $this->addColumn('name', 'Name', 'VARCHAR', true, 255, null); // validators } // initialize() /** * Build the RelationMap objects for this table relationships */ public function buildRelations() { $this->addRelation('Site', 'Site', RelationMap::ONE_TO_MANY, array('id' => 'category_id', ), null, null, 'Sites'); } // buildRelations() } // CategoryTableMap
Kehet/KReader
build/classes/kreader/map/CategoryTableMap.php
PHP
mit
1,560
require "spec_helper" describe ZMQP1 do it "is awesome" do ZMQP1::Awesome.new.describe.should be_awesome end end
skippy/zmq_p1
spec/awesome_spec.rb
Ruby
mit
122
namespace TheDmi.CouchDesignDocuments { public interface IShowsSection { } }
thedmi/CouchDesignDocuments
Sources/CouchDesignDocuments/IShowsSection.cs
C#
mit
91
//# sourceMappingURL=WeatherData.js.map
MatthewNichols/WeatherDemo
Scripts/WeatherApp/Model/WeatherData.js
JavaScript
mit
43
<?php /* Safe sample input : get the field userData from the variable $_GET via an object sanitize : use of floatval construction : interpretation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ class Input{ private $input; public function getInput(){ return $this->input; } public function __construct(){ $this->input = $_GET['UserData'] ; } } $temp = new Input(); $tainted = $temp->getInput(); $tainted = floatval($tainted); $query = "$temp = ' $tainted ';"; $res = eval($query); ?>
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_95/safe/CWE_95__object-classicGet__func_floatval__variable-interpretation_simple_quote.php
PHP
mit
1,394
/* * The MIT License (MIT) * * Copyright (c) 2016 MrInformatic. * * 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 game.saver.remote.gamemaps; import game.saver.GameData; import game.saver.Quarry; import game.saver.gamemaps.GameDoubleMap; import game.saver.gamemaps.GameFloatMap; import game.saver.remote.RemoteClassMap; import game.saver.remote.Remoteable; import java.util.LinkedList; import java.util.Map; /** * * @author MrInformatic */ public class RemoteGameDoubleMap<T extends GameData> extends GameDoubleMap<T> implements Remoteable{ private int id; private Quarry quarry; private RemoteClassMap remoteClassMap; public RemoteGameDoubleMap(Quarry quarry,RemoteClassMap remoteClassMap){ this.quarry = quarry; this.remoteClassMap = remoteClassMap; } @Override public T put(Double key, T value) { LinkedList<GameData> gameDatas = getUnaddedGameData(value); T type = super.put(key,value); sendPut(key, value, gameDatas); return type; } @Override public T remove(Object key) { quarry.writeByte((byte)1); quarry.writeDouble((Double)key); return super.remove(key); } @Override public void putAll(Map<? extends Double, ? extends T> m) { LinkedList<GameData>[] gameDatases = new LinkedList[m.size()]; int i=0; for(T ms : m.values()){ gameDatases[i] = getUnaddedGameData(ms); i++; } super.putAll(m); i=0; for(Map.Entry<? extends Double, ? extends T> ms : m.entrySet()){ sendPut(ms.getKey(),ms.getValue(),gameDatases[i]); i++; } } @Override public void clear() { quarry.writeByte((byte)2); super.clear(); } private void sendPut(Double key,T value,LinkedList<GameData> unaddedGameData){ for(GameData gameData : unaddedGameData){ remoteClassMap.addClass(gameData.getClass()); } quarry.writeInt(id); quarry.writeByte((byte)0); quarry.writeDouble(key); quarry.writeInt(unaddedGameData.size()); for(GameData gameData : unaddedGameData){ quarry.writeInt(gameData.getId()); quarry.writeInt(remoteClassMap.getClassId(gameData.getClass())); quarry.write(gameData); } for(GameData gameData : unaddedGameData){ gameData.writeChilds(quarry); } quarry.writeInt(-1); } private LinkedList<GameData> getUnaddedGameData(GameData gameData){ LinkedList<GameData> result = new LinkedList<>(); getUnaddedGameData(result,gameData); return result; } private LinkedList<GameData> getUnaddedGameData(LinkedList<GameData> list,GameData gameData){ if(gameData.getId()==-1){ list.add(gameData); } for(GameData gameData1 : gameData.getChilds()){ getUnaddedGameData(list,gameData1); } return list; } @Override public void update() { try { switch(quarry.readByte()){ case 0: double key = quarry.readDouble(); LinkedList<GameData> gameDatas = new LinkedList<>(); int length = quarry.readInt(); for(int i=0;i<length;i++){ int id = quarry.readInt(); T value = (T)quarry.read(remoteClassMap.getClassbyId(quarry.readInt())); gameDatas.add(value); graph.set(id,value); } for(GameData gameData : gameDatas){ gameData.readChilds(quarry,graph); } break; case 1: remove(quarry.readDouble()); break; case 2: clear(); break; } } catch (Exception ex) { ex.printStackTrace(); } } public void setId(int id){ this.id = id; } }
MrInformatic/GameSaver
src/main/java/game/saver/remote/gamemaps/RemoteGameDoubleMap.java
Java
mit
5,186
function commentPage() { // Open popup $("#comment-popup").dialog({ width : 800, height : 400, modal : true, appendTo: "#mainForm", open : function(event, ui) { $('input[id$="comment-comment"]').focus(); }, close : function(event, ui) { cancelComment(); } }); } /** * Clean comment form */ function cancelComment() { $('textarea[id$="comment-comment"]').val(''); } function saveComment(event) { if (event.status == 'complete') { cancelComment(); $('#comment-popup').dialog('close'); } }
Micht69/shoplist
WebContent/static/scripts/comment.js
JavaScript
mit
556
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using TwitterAPI; using System.Net; using Core; using System.Security.Cryptography; using System.IO; namespace TwitterAPI { [DataContract] public class TwitterDirectMessage { /// <summary> /// ダイレクトメッセージのID /// </summary> [DataMember(Name = "id")] public decimal Id { get; set; } [DataMember(Name = "created_at")] private string created_at { get; set; } public DateTime CreateDate { get { return DateTime.ParseExact(created_at, "ddd MMM dd HH':'mm':'ss zz'00' yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.None); } } /// <summary> /// ダイレクトメッセージのID(文字列) /// </summary> [DataMember(Name = "id_str")] public string StringId { get; set; } /// <summary> /// ダイレクトメッセージの受信者 /// </summary> [DataMember(Name = "recipient")] public TwitterUser Recipient { get; set; } /// <summary> /// ダイレクトメッセージの送信者 /// </summary> [DataMember(Name = "sender")] public TwitterUser Sender { get; set; } /// <summary> /// ダイレクトメッセージの内容 /// </summary> [DataMember(Name = "text")] public string Text { get; set; } [DataMember(Name = "sender_id")] public decimal SenderId { get; set; } [DataMember(Name = "sender_id_str")] public string SenderStringId { get; set; } [DataMember(Name = "sender_screen_name")] public string SenderScreenName { get; set; } [DataMember(Name = "recipient_id")] public decimal RecipientId { get; set; } [DataMember(Name = "recipient_id_str")] public string RecipientStringId { get; set; } [DataMember(Name = "recipient_screen_name")] public string RecipientScreenName { get; set; } [DataMember(Name = "entities")] public TwitterStatus.TweetEntities Entities { get; set; } public static TwitterResponse<TwitterDirectMessageCollection> DirectMessage(OAuthTokens tokens, DirectMessageOptions options) { return new TwitterResponse<TwitterDirectMessageCollection>(Method.Get(UrlBank.DirectMessages, tokens, options)); } public static TwitterResponse<TwitterDirectMessageCollection> DirectMessageSent(OAuthTokens tokens, DirectMessageOptions options) { return new TwitterResponse<TwitterDirectMessageCollection>(Method.Get(UrlBank.DirectMessagesSent, tokens, options)); } public static TwitterResponse<TwitterDirectMessage> Show(OAuthTokens tokens, decimal id) { return new TwitterResponse<TwitterDirectMessage>(Method.Get(string.Format(UrlBank.DirectMessageShow, id), tokens, null)); } public static TwitterResponse<TwitterDirectMessage> Destroy(OAuthTokens tokens, decimal id, bool IncludeEntities = false) { return new TwitterResponse<TwitterDirectMessage>(Method.GenerateResponseResult(Method.GenerateWebRequest(string.Format("{0}?id={1}", UrlBank.DirectMessagesDestroy, id), WebMethod.POST, tokens, null, "application/x-www-form-urlencoded", null, null))); } public static TwitterResponse<TwitterDirectMessage> New(OAuthTokens tokens, string ScreenName, string Text) { string data = string.Format("text={0}&screen_name={1}", Uri.EscapeDataString(Text), Uri.EscapeDataString(ScreenName)); return new TwitterResponse<TwitterDirectMessage>(Method.GenerateResponseResult(Method.GenerateWebRequest("https://api.twitter.com/1.1/direct_messages/new.json?" + data, WebMethod.POST, tokens, null, "application/x-www-form-urlencoded", null, null))); } public static TwitterResponse<TwitterDirectMessage> New(OAuthTokens tokens, decimal UserId, string Text) { string data = string.Format("text={0}&screen_name={1}", Uri.EscapeDataString(Text), UserId); return new TwitterResponse<TwitterDirectMessage>(Method.GenerateResponseResult(Method.GenerateWebRequest("https://api.twitter.com/1.1/direct_messages/new.json?" + data, WebMethod.POST, tokens, null, "application/x-www-form-urlencoded", null, null))); } private class DMDestroyOption : ParameterClass { [Parameters("id", ParameterMethodType.POSTData)] public decimal Id { get; set; } [Parameters("include_entities")] public bool? IncludeEntities { get; set; } } } public class TwitterDirectMessageCollection : List<TwitterDirectMessage> { } }
atst1996/TwitterAPI
TwitterAPI/Method/DirectMessages/DirectMessage.cs
C#
mit
4,411
document.addEventListener("DOMContentLoaded", function() { "use_strict"; // Store game in global variable const CASUDOKU = {}; CASUDOKU.game = (function() { // Controls the state of the game // Game UI let uiStats = document.getElementById("gameStats"), uiComplete = document.getElementById("gameComplete"), uiNewGame = document.getElementById("gameNew"), gamePadKeys = document.querySelectorAll("#gameKeypad li a"); // GameKeypad Events for (let i = gamePadKeys.length - 1; i >= 0; i--) { let key = gamePadKeys[i]; key.onclick = function(e) { e.preventDefault(); // Parse keycode value let number = parseInt(e.currentTarget.innerText, 10); if (!number) { CASUDOKU.board.update_cell(0); } else { CASUDOKU.board.update_cell(number); } } } uiNewGame.onclick = function(e) { e.preventDefault(); CASUDOKU.game.start(); } start = function() { CASUDOKU.timer.start(); CASUDOKU.board.new_puzzle(); uiComplete.style.display = "none"; uiStats.style.display = "block"; }; over = function() { CASUDOKU.timer.stop(); uiComplete.style.display = "block"; uiStats.style.display = "none"; }; // Public api return { start: start, over: over }; }()); CASUDOKU.timer = (function() { let timeout, seconds = 0, minutes = 0, secCounter = document.querySelectorAll(".secCounter"), minCounter = document.querySelectorAll(".minCounter"); start = function() { if (seconds === 0 && minutes === 0) { timer(); } else { stop(); seconds = 0; minutes = 0; setText(minCounter, 0); timer(); } }; stop = function() { clearTimeout(timeout); }; setText = function(element, time) { element.forEach(function(val) { val.innerText = time; }); }; timer = function() { timeout = setTimeout(timer, 1000); if (seconds === 59) { setText(minCounter, ++minutes); seconds = 0; } setText(secCounter, seconds++); }; // Public api return { start: start, stop: stop }; }()); CASUDOKU.board = (function() { // Stores the cells that make up the Sudoku board let grid = [], // Canvas settings canvas = document.getElementById("gameCanvas"), context = canvas.getContext("2d"), canvasWidth = canvas.offsetWidth, canvasHeight = canvas.offsetHeight, // Board Settings numRows = 9, numCols = 9, regionWidth = canvasWidth / 3, regionHeight = canvasHeight / 3, // Cell Settings cellWidth = canvasWidth / numCols, cellHeight = canvasHeight / numRows, numCells = numRows * numCols, selectedCellIndex = 0, //Key Codes keycode = { arrowLeft: 37, arrowUp: 38, arrowRight: 39, arrowDown: 40, zero: 48, nine: 57 }; // End let // Keyboard & Mouse Events canvas.addEventListener("click", function (e) { // Calculate position of mouse click and update selected cell let xAxis, yAxis, canvasOffset = getOffset(), cellIndex, resultsX = [], resultsY = []; function getOffset() { return { left: canvas.getBoundingClientRect().left + window.scrollX, top: canvas.getBoundingClientRect().top + window.scrollY }; } if (e.pageX !== undefined && e.pageY !== undefined) { xAxis = e.pageX; yAxis = e.pageY; } else { xAxis = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; yAxis = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } xAxis -= canvasOffset.left; yAxis -= canvasOffset.top; xAxis = Math.min(xAxis, canvasWidth); yAxis = Math.min(yAxis, canvasHeight); xAxis = Math.floor(xAxis/cellWidth); yAxis = Math.floor(yAxis/cellHeight); // Matches clicked coordinates to a cell for (let i = 0; i < numCells; i+= 1) { if (grid[i].col === xAxis && grid[i].row === yAxis) { selectedCellIndex = i; refresh_board(); } } }); window.addEventListener("keypress", function (e) { if (e.which >= keycode.zero && e.which <= keycode.nine) { // Subtract 48 to get actual number update_cell(e.which - 48); } }); window.addEventListener("keydown", function (e) { // Arrow Key events for changing the selected cell let pressed = e.which, col = grid[selectedCellIndex].col, row = grid[selectedCellIndex].row; if (pressed >= keycode.arrowLeft && pressed <= keycode.arrowDown) { if (col < (numCols - 1) && pressed == keycode.arrowRight) { selectedCellIndex++; refresh_board(); } if (col > 0 && pressed == keycode.arrowLeft) { selectedCellIndex--; refresh_board(); } if (row < (numRows - 1) && pressed == keycode.arrowDown) { selectedCellIndex += numCols; refresh_board(); } if (row > 0 && pressed == keycode.arrowUp) { selectedCellIndex -= numCols; refresh_board(); } } }); new_puzzle = function() { let workerSudokuSolver = new Worker("js/sudoku-solver.js"), clues = 24, puzzle; workerSudokuSolver.postMessage(clues); workerSudokuSolver.onmessage = function(e) { puzzle = e.data; make_grid(puzzle); }; }; make_grid = function(puzzle) { // Makes a grid array filled with cell instances. Each cell stores // one puzzle value let colCounter = 0, rowCounter = 0; class Cell { constructor() { // set fixed puzzle values this.isDefault = true; this.value = 0; // Store position on the canvas this.x = 0; this.y = 0; this.col = 0; this.row = 0; } }; for (let i = 0; i < puzzle.length; i++) { grid[i] = new Cell(); grid[i].value = puzzle[i]; if (puzzle[i] === 0) { grid[i].isDefault = false; } // Set cell column and row grid[i].col = colCounter; grid[i].row = rowCounter; colCounter++; // change row if ((i + 1) % 9 === 0) { rowCounter++; colCounter = 0; } } refresh_board(); }; refresh_board = function () { let workerSudokuValidator = new Worker("js/sudoku-validator.js"); workerSudokuValidator.postMessage(grid); workerSudokuValidator.onmessage = function(e) { let correct = e.data; if (correct) { CASUDOKU.game.over(); } draw(); }; }; draw = function () { // renders the canvas let regionPosX = 0, regionPosY = 0, cellPosX = 0, cellPosY = 0, textPosX = cellWidth * 0.4, textPosY = cellHeight * 0.65; // board outline context.clearRect(0, 0, canvasWidth, canvasHeight); context.strokeRect(0 , 0, canvasWidth, canvasHeight); context.globalCompositeOperation = "destination-over"; context.lineWidth = 10; // regions for (let x = 0; x < numRows; x++) { context.strokeRect(regionPosX, regionPosY, regionWidth, regionHeight); regionPosX += regionWidth; if (regionPosX == canvasWidth){ regionPosY += regionHeight; regionPosX = 0; } } // Start to draw the Grid context.beginPath(); // vertical lines for (let z = 0; z <= canvasWidth; z += cellWidth) { context.moveTo(0.5 + z, 0); context.lineTo(0.5 + z, canvasWidth); } // horizontal lines for (let y = 0; y <= canvasHeight; y += cellHeight) { context.moveTo(0, 0.5 + y); context.lineTo(canvasHeight, 0.5 + y); } // cell outline context.lineWidth = 2; context.strokeStyle = "black"; context.stroke(); for (let i = 0; i < numCells; i++) { grid[i].x = cellPosX; grid[i].y = cellPosY; // Cell values if (grid[i].isDefault) { context.font = "bold 1.6em Droid Sans, sans-serif"; context.fillStyle = "black"; context.fillText(grid[i].value, textPosX, textPosY); } if (grid[i].value !== 0 && !grid[i].isDefault) { context.font = "1.4em Droid Sans, sans-serif"; context.fillStyle = "grey"; context.fillText(grid[i].value, textPosX, textPosY); } // Cell background colour if (i == selectedCellIndex) { context.fillStyle = "#00B4FF"; } else { context.fillStyle = "#EEEEEE"; } // Cell background context.fillRect(cellPosX, cellPosY, cellWidth, cellHeight); cellPosX += cellWidth; textPosX += cellWidth; // Change row if ((i + 1) % numRows === 0) { cellPosX = 0; cellPosY += cellHeight; textPosY += cellHeight; textPosX = cellWidth * 0.4; } } }; update_cell = function (value) { if (!grid[selectedCellIndex].isDefault) { grid[selectedCellIndex].value = value; refresh_board(); } }; // Public api return { new_puzzle: new_puzzle, update_cell: update_cell }; }()); CASUDOKU.game.start(); });
davidhenry/CaSudoku
js/game.js
JavaScript
mit
8,726
package rest import ( restful "github.com/emicklei/go-restful" swagger "github.com/emicklei/go-restful-swagger12" ) // ConfigureSwagger configures the swagger documentation for all endpoints in the container func ConfigureSwagger(apiDocPath string, container *restful.Container) { if apiDocPath == "" { return } config := swagger.Config{ WebServices: container.RegisteredWebServices(), WebServicesUrl: ``, ApiPath: apiDocPath, } swagger.RegisterSwaggerService(config, container) }
spring1843/chat-server
src/shared/rest/swagger.go
GO
mit
508
webpackJsonp([2],{ /***/ 16: /***/ function(module, exports, __webpack_require__) { /// <reference path="../../typings/tsd.d.ts" /> var ListController = __webpack_require__(17); // webpack will load the html. Nifty, eh? __webpack_require__(9); // webpack will load this scss too! __webpack_require__(18); module.exports = angular.module('List', []) .controller('ListController', ['$scope', ListController]); //# sourceMappingURL=index.js.map /***/ }, /***/ 17: /***/ function(module, exports) { var ListController = (function () { function ListController() { this.apps = [ { name: 'Gmail' }, { name: 'Facebook' }, { name: 'Twitter' }, { name: 'LinkedIn' } ]; this.title = 'Applications'; } return ListController; })(); module.exports = ListController; //# sourceMappingURL=list.controller.js.map /***/ }, /***/ 18: /***/ function(module, exports, __webpack_require__) { // style-loader: Adds some css to the DOM by adding a <style> tag // load the styles var content = __webpack_require__(19); if(typeof content === 'string') content = [[module.id, content, '']]; // add the styles to the DOM var update = __webpack_require__(15)(content, {}); if(content.locals) module.exports = content.locals; // Hot Module Replacement if(false) { // When the styles change, update the <style> tags if(!content.locals) { module.hot.accept("!!./../../../../node_modules/css-loader/index.js!./../../../../node_modules/autoprefixer-loader/index.js!./../../../../node_modules/sass-loader/index.js!./list.scss", function() { var newContent = require("!!./../../../../node_modules/css-loader/index.js!./../../../../node_modules/autoprefixer-loader/index.js!./../../../../node_modules/sass-loader/index.js!./list.scss"); if(typeof newContent === 'string') newContent = [[module.id, newContent, '']]; update(newContent); }); } // When the module is disposed, remove the <style> tags module.hot.dispose(function() { update(); }); } /***/ }, /***/ 19: /***/ function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(14)(); // imports // module exports.push([module.id, ".list-item {\n color: blue; }\n", ""]); // exports /***/ } });
jaganathanb/Typescript-Angular-Gulp-Webpack-Dynamic-module-loading-
dist/2.module.js
JavaScript
mit
2,324
<?php namespace App\Models; use Fwartner\Katching\Cacheable; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Comment extends Model { use Cacheable, SoftDeletes; protected $table = 'comments'; protected $fillable = [ 'content', 'is_spam', 'user_id', 'thread_id' ]; protected $casts = [ 'is_spam' => 'boolean' ]; public function owner() { return $this->belongsTo(User::class, 'user_id'); } public function forum() { return $this->belongsTo(Forum::class, 'forum_id'); } public function thread() { return $this->belongsTo(Thread::class, 'thread_id'); } }
LaravelHamburg/laravel-hamburg.com
app/Models/Comment.php
PHP
mit
729
require File.expand_path('../core_response', __FILE__) module Korwe module TheCore class InitiateSessionResponse < CoreResponse def initialize(session_id, guid, successful) super(session_id, :InitiateSessionResponse, guid, successful) end end end end
korwe/core-client-ruby
lib/messages/initiate_session_response.rb
Ruby
mit
282
djsex.css = { /* * http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript */ create: function(stylesheet) { var head = document.getElementsByTagName('head')[0], style = document.createElement('style'), rules = document.createTextNode(stylesheet); style.type = 'text/css'; if(style.styleSheet) style.styleSheet.cssText = rules.nodeValue; else style.appendChild(rules); head.appendChild(style); }, appendClass: function (el, classname) { if(el.className) { var classes = el.className.split(" "); var alreadyclassed = false; classes.forEach(function(thisclassname) { if(classname == thisclassname) alreadyclassed=true; }); if(!alreadyclassed) classes.push(classname); el.className = classes.join(" ") } else { el.className=classname; } }, deleteClass: function (el, classname) { if(el.className) { var classes = el.className.split(" "); for(i=0; i<=classes.length; i++) { if((classes[i]) && (classes[i]==classname)) classes.splice(i,1); } el.className = classes.join(" "); } }, };
WatersideDevelopment/Fullscreen-Ajax-Image-Loader
js/djsex/CSS.js
JavaScript
mit
1,396
<?php namespace Mapbender\ActivityIndicatorBundle\Element; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; /** * */ class ActivityIndicatorAdminType extends AbstractType { /** * @inheritdoc */ public function getName() { return 'activityindicator'; } /** * @inheritdoc */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'application' => null )); } /** * @inheritdoc */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('tooltip', 'text', array('required' => false)) ->add('activityClass', 'text', array('required' => false)) ->add('ajaxActivityClass', 'text', array('required' => false)) ->add('tileActivityClass', 'text', array('required' => false)); } }
mapbender/mapbender-activityindicator
src/Mapbender/ActivityIndicatorBundle/Element/ActivityIndicatorAdminType.php
PHP
mit
1,022
/** * The Furnace namespace * * @module furnace * @class Furnace * @static */ import Validation from 'furnace/packages/furnace-validation'; import I18n from 'furnace/packages/furnace-i18n'; import Forms from 'furnace/packages/furnace-forms'; export default { /** * * @property Forms * @type Furnace.Forms */ Forms : Forms, /** * @property I18n * @type Furnace.I18n */ I18n : I18n, /** * @property Validation * @type Furnace.Validation */ Validation: Validation };
ember-furnace/ember-cli-furnace
addon/index.js
JavaScript
mit
503
import cx from 'clsx' import PropTypes from 'prop-types' import React from 'react' import { customPropTypes, getElementType, getUnhandledProps, useKeyOnly } from '../../lib' /** * A placeholder can contain an image. */ function PlaceholderImage(props) { const { className, square, rectangular } = props const classes = cx( useKeyOnly(square, 'square'), useKeyOnly(rectangular, 'rectangular'), 'image', className, ) const rest = getUnhandledProps(PlaceholderImage, props) const ElementType = getElementType(PlaceholderImage, props) return <ElementType {...rest} className={classes} /> } PlaceholderImage.propTypes = { /** An element type to render as (string or function). */ as: PropTypes.elementType, /** Additional classes. */ className: PropTypes.string, /** An image can modify size correctly with responsive styles. */ square: customPropTypes.every([customPropTypes.disallow(['rectangular']), PropTypes.bool]), /** An image can modify size correctly with responsive styles. */ rectangular: customPropTypes.every([customPropTypes.disallow(['square']), PropTypes.bool]), } export default PlaceholderImage
Semantic-Org/Semantic-UI-React
src/elements/Placeholder/PlaceholderImage.js
JavaScript
mit
1,162
(function (angular) { "use strict"; var appFooter = angular.module('myApp.footer', []); appFooter.controller("footerCtrl", ['$scope', function ($scope) { }]); myApp.directive("siteFooter",function(){ return { restrict: 'A', templateUrl:'app/components/footer/footer.html' }; }); } (angular));
kevinczhang/kevinczhang.github.io
src/app/components/footer/footer.js
JavaScript
mit
376
<?php namespace App\Http\Controllers\API\V2; use App\Beacon; use App\Http\Requests\BeaconRequest; use Illuminate\Http\Request; class BeaconController extends Controller { /** * Return a list of items. * * @param Request $request * * @return json */ public function index(Request $request) { return $this->filteredAndOrdered($request, new Beacon())->paginate($this->pageSize); } /** * Save a new item. * * @param Request $request * * @return json */ public function store(BeaconRequest $request) { return response(Beacon::create($request->all()), 201); } /** * Return a single item. * * @param Request $request * @param Beacon $beacon * * @return json */ public function show(Request $request, Beacon $beacon) { return $this->attachResources($request, $beacon); } /** * Update a single item. * * @param BeaconRequest $request * @param Beacon $beacon * * @return json */ public function update(BeaconRequest $request, Beacon $beacon) { $beacon->update($request->all()); return $beacon; } /** * Delete a single item. * * @param Beacon $beacon * * @return empty */ public function destroy(Beacon $beacon) { $beacon->delete(); return response('', 204); } /** * Return a list of deleted items. * * @return json */ public function deleted() { return Beacon::onlyTrashed()->get(); } }
nosuchagency/beacon-bacon
app/Http/Controllers/API/V2/BeaconController.php
PHP
mit
1,627
import {IDetailsService} from '../services/details.service'; class DetailsController implements ng.IComponentController { private detailsService: IDetailsService; private detailsData: any; private previousState: any; constructor($stateParams: any, detailsService: IDetailsService) { console.log('details controller'); console.log("$stateParams.id=", $stateParams.id); console.log("this.previousState=", this.previousState); let id = $stateParams.id; detailsService.searchByIMDbID(id, 'full').then((result) => { console.log("detailsData = ", result.data); this.detailsData = result.data; }); } } export default DetailsController; DetailsController.$inject = ['$stateParams', 'detailsService'];
andyyusydney/open-movie
src/details/details.controller.ts
TypeScript
mit
788
package main import ( "bufio" "fmt" "os" "os/exec" "strings" "sync" ) func checkError(err error, prefix string) { if err != nil { panic(fmt.Sprintf("%s %s", prefix, err.Error())) } } func cleanFeedbackLine(s string) (out string) { out = s out = strings.TrimSpace(out) out = strings.Replace(out, "\r", "", -1) out = strings.Replace(out, "\n", "\\n", -1) return } func runCommand(wg *sync.WaitGroup, resultCollector *ResultCollector, commandIndex int, phase *nodeData, cmd *exec.Cmd) { if wg != nil { defer wg.Done() } defer func() { if r := recover(); r != nil { errMsg := fmt.Sprintf("%s", r) if !phase.ContinueOnFailure { logger.Fatallnf(errMsg) } else { logger.Errorlnf(errMsg) } resultCollector.AppendResult(&result{Cmd: cmd, Successful: false}) } else { resultCollector.AppendResult(&result{Cmd: cmd, Successful: true}) } }() stdout, err := cmd.StdoutPipe() checkError(err, "cmd.StdoutPipe") stderr, err := cmd.StderrPipe() checkError(err, "cmd.StderrPipe") outLines := []string{} stdoutScanner := bufio.NewScanner(stdout) go func() { for stdoutScanner.Scan() { txt := cleanFeedbackLine(stdoutScanner.Text()) outLines = append(outLines, txt) logger.Tracelnf("COMMAND %d STDOUT: %s", commandIndex, txt) } }() errLines := []string{} stderrScanner := bufio.NewScanner(stderr) go func() { for stderrScanner.Scan() { txt := cleanFeedbackLine(stderrScanner.Text()) errLines = append(errLines, txt) logger.Warninglnf("COMMAND %d STDERR: %s", commandIndex, txt) } }() err = cmd.Start() checkError(err, "cmd.Start") err = cmd.Wait() if err != nil { newErr := fmt.Errorf("%s - lines: %s", err.Error(), strings.Join(errLines, "\\n")) outCombined := cleanFeedbackLine(strings.Join(outLines, "\n")) errMsg := fmt.Sprintf("FAILED COMMAND %d. Continue: %t. ERROR: %s. OUT: %s", commandIndex, phase.ContinueOnFailure, newErr.Error(), outCombined) panic(errMsg) } } func runPhase(setup *setup, phaseName string, phase *nodeData) { var wg sync.WaitGroup resultCollector := &ResultCollector{} cmds, err := phase.GetExecCommandsFromSteps(setup.StringVariablesOnly(), setup.Variables) if err != nil { logger.Fatallnf(err.Error()) } if phase.RunParallel { wg.Add(len(cmds)) } logger.Infolnf("Running step %s", phaseName) for ind, c := range cmds { logger.Tracelnf(strings.TrimSpace(fmt.Sprintf(`INDEX %d = %s`, ind, execCommandToDisplayString(c)))) var wgToUse *sync.WaitGroup = nil if phase.RunParallel { wgToUse = &wg go runCommand(wgToUse, resultCollector, ind, phase, c) } else { runCommand(wgToUse, resultCollector, ind, phase, c) } } if phase.RunParallel { wg.Wait() } if resultCollector.FailedCount() == 0 { logger.Infolnf("There were no failures - %d/%d successful", resultCollector.SuccessCount(), resultCollector.TotalCount()) } else { logger.Errorlnf("There were %d/%d failures: ", resultCollector.FailedCount(), resultCollector.TotalCount()) for _, failure := range resultCollector.FailedDisplayList() { logger.Errorlnf("- %s", failure) } } } func main() { logger.Infolnf("Running version '%s'", Version) if len(os.Args) < 2 { logger.Fatallnf("The first command-line argument must be the YAML file path.") } yamlFilePath := os.Args[1] setup, err := ParseYamlFile(yamlFilePath) if err != nil { logger.Fatallnf(err.Error()) } for _, phase := range setup.Phases { runPhase(setup, phase.Name, phase.Data) } }
golang-devops/yaml-script-runner
main.go
GO
mit
3,494
<html> <head> <title>Progmia | Game | Level Selection</title> <link href="<?php echo base_url(); ?>assets/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/levels.css"> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/stars.css"> <script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="<?php echo base_url();?>assets/js/bootstrap.min.js""></script> <script type="text/javascript" src="<?php echo base_url();?>assets/js/bootstrap.min.js"></script> <link rel="icon" href="<?php echo base_url(); ?>assets/images/icon_jFd_icon.ico"> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/fonts/font-awesome-4.7.0/css/font-awesome.min.css"> <script type="text/javascript" src="<?php echo base_url();?>assets/js/drag-on.js"></script> </head> <body> <nav id="primary-nav" class="primary-nav"> <div class="container-fluid"> <div class="row" style="display: flex;align-items: center;"> <div class="col-md-3 col-lg-3 col-xs-4 col-sm-4" style="text-align: center;"> <a class="back" href="<?php echo base_url(); ?>Game/MainMenu"><i class="fa fa-arrow-left"></i></a> </div> <div class="col-md-6 col-lg-6 col-xs-4 col-sm-4"> </div> <div class="col-md-3 col-lg-3 col-xs-4 col-sm-4"> <ul class="nav-left"> <li class="music-control"> <button id="playpausebtn" class="playpausebtn"><i class="fa fa-music"></i></button> <input id="volumeslider" class="volumeslider" type="range" min="0" max="100" value="100" step="1"> </li> </ul> </div> </div> </div> </nav> <script> $(document).ready(function(){ $("button.playpausebtn").click(function() { if(jQuery('#playpausebtn').hasClass('paused')){ $("button").removeClass("paused"); } else { $(this).addClass("paused"); } }); $("button#back").click(function() { }); }); var audio, playbtn, mutebtn, seekslider, volumeslider, seeking=false, seekto; function initAudioPlayer(){ audio = new Audio(); audio.src = "<?php echo base_url();?>/assets/sounds/bgm/03 Civil (Explore).mp3"; audio.loop = true; audio.play(); // Set object references playbtn = document.getElementById("playpausebtn"); volumeslider = document.getElementById("volumeslider"); // Add Event Handling playbtn.addEventListener("click",playPause); volumeslider.addEventListener("mousemove", setvolume); // Functions function playPause(){ if(audio.paused){ audio.play(); } else { audio.pause(); } } function setvolume(){ audio.volume = volumeslider.value / 100; } } window.addEventListener("load", initAudioPlayer); </script>
timpquerubin/Progmia
application/views/templates/menu_levels_header.php
PHP
mit
2,910
import base64 try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.3, 2.4 fallback. from django import http, template from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import render_to_response from django.utils.translation import ugettext_lazy, ugettext as _ ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.") LOGIN_FORM_KEY = 'this_is_the_login_form' def _display_login_form(request, error_message=''): request.session.set_test_cookie() return render_to_response('admin/login.html', { 'title': _('Log in'), 'app_path': request.get_full_path(), 'error_message': error_message }, context_instance=template.RequestContext(request)) def staff_member_required(view_func): """ Decorator for views that checks that the user is logged in and is a staff member, displaying the login page if necessary. """ def _checklogin(request, *args, **kwargs): if request.user.is_authenticated() and request.user.is_staff: # The user is valid. Continue to the admin page. return view_func(request, *args, **kwargs) assert hasattr(request, 'session'), "The Django admin requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'." # If this isn't already the login page, display it. if LOGIN_FORM_KEY not in request.POST: if request.POST: message = _("Please log in again, because your session has expired.") else: message = "" return _display_login_form(request, message) # Check that the user accepts cookies. if not request.session.test_cookie_worked(): message = _("Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.") return _display_login_form(request, message) else: request.session.delete_test_cookie() # Check the password. username = request.POST.get('username', None) password = request.POST.get('password', None) user = authenticate(username=username, password=password) if user is None: message = ERROR_MESSAGE if '@' in username: # Mistakenly entered e-mail address instead of username? Look it up. users = list(User.all().filter('email =', username)) if len(users) == 1 and users[0].check_password(password): message = _("Your e-mail address is not your username. Try '%s' instead.") % users[0].username else: # Either we cannot find the user, or if more than 1 # we cannot guess which user is the correct one. message = _("Usernames cannot contain the '@' character.") return _display_login_form(request, message) # The user data is correct; log in the user in and continue. else: if user.is_active and user.is_staff: login(request, user) return http.HttpResponseRedirect(request.get_full_path()) else: return _display_login_form(request, ERROR_MESSAGE) return wraps(view_func)(_checklogin)
isaac-philip/loolu
common/django/contrib/admin/views/decorators.py
Python
mit
3,535
// BEGIN CUT HERE // END CUT HERE #include <sstream> #include <cstdio> #include <cstdlib> #include <iostream> #include <cstring> #include <algorithm> #include <cmath> #include <vector> #include <map> #include <string> #include <set> #include <algorithm> using namespace std; const int V = 64; const int E = V * V * 2; const int INF = 1 << 29; int d[V], how[V], eCapacity[E], eU[E], eV[E], eCost[E]; int eIndex = 0; void addEdge(int u, int v, int capacity, int cost) { eU[eIndex] = u, eV[eIndex] = v, eCapacity[eIndex] = capacity, eCost[eIndex++] = cost; eU[eIndex] = v, eV[eIndex] = u, eCapacity[eIndex] = 0, eCost[eIndex++] = -cost; } pair <int, int> minCostMaxFlow(int n, int s, int t) { int flow = 0, cost = 0; for (;;) { for (int i = 0; i < n; i++) { d[i] = INF; } d[s] = 0; for(;;) { bool done = true; for (int e = 0; e < eIndex; e++) { if (eCapacity[e] > 0) { int u = eU[e], v = eV[e], cost = eCost[e]; if (d[v] > d[u] + cost) { d[v] = d[u] + cost; how[v] = e; done = false; } } } if (done) { break; } } if (d[t] >= INF / 2) { break; } int augment = INF; for (int v = t; v != s; v = eU[how[v]]) { augment = min(augment, eCapacity[how[v]]); } for (int v = t; v != s; v = eU[how[v]]) { int e = how[v]; eCapacity[e] -= augment; eCapacity[e ^ 1] += augment; } flow += augment; cost += d[t] * augment; } pair <int, int> ret = make_pair(cost, flow); return ret; } class SpecialCells { public: int guess(vector <int> x, vector <int> y) { eIndex = 0; map <int, int> xMap, yMap; set <pair <int, int> > pairSet; int n = x.size(); for (int i = 0; i < n; i++) { xMap[x[i]]++; yMap[y[i]]++; pairSet.insert(make_pair(x[i], y[i])); } int grpahVertexNumber = xMap.size() + yMap.size() + 2; int s = grpahVertexNumber - 2, t = grpahVertexNumber - 1, xIndex = 0, yIndex = xMap.size(); for (map <int, int> :: iterator it = xMap.begin(); it != xMap.end(); it++, xIndex++) { addEdge(s, xIndex, it->second, 0); } for (map <int, int> :: iterator it = yMap.begin(); it != yMap.end(); it++, yIndex++) { addEdge(yIndex, t, it->second, 0); } xIndex = 0; for (map <int, int> :: iterator it = xMap.begin(); it != xMap.end(); it++, xIndex++) { yIndex = xMap.size(); for (map <int, int> :: iterator jt = yMap.begin(); jt != yMap.end(); jt++, yIndex++) { int cost = pairSet.find(make_pair(it->first, jt->first)) == pairSet.end() ? 0 : 1; addEdge(xIndex, yIndex, 1, cost); } } pair <int, int> mcmf = minCostMaxFlow(grpahVertexNumber, s, t); int ret = mcmf.first; return ret; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {1,2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,2}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 0; verify_case(0, Arg2, guess(Arg0, Arg1)); } void test_case_1() { int Arr0[] = {1,1,2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,2,1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; verify_case(1, Arg2, guess(Arg0, Arg1)); } void test_case_2() { int Arr0[] = {1,2,1,2,1,2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,2,3,1,2,3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 6; verify_case(2, Arg2, guess(Arg0, Arg1)); } void test_case_3() { int Arr0[] = {1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 9; verify_case(3, Arg2, guess(Arg0, Arg1)); } void test_case_4() { int Arr0[] = {1,100000}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,100000}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 0; verify_case(4, Arg2, guess(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main(){ SpecialCells ___test; ___test.run_test(-1); return 0; } // END CUT HERE
CanoeFZH/SRM
SRM612/SpecialCells.cpp
C++
mit
5,627
<?php /** * wCMF - wemove Content Management Framework * Copyright (C) 2005-2020 wemove digital solutions GmbH * * Licensed under the terms of the MIT License. * * See the LICENSE file distributed with this work for * additional information. */ namespace wcmf\lib\core; /** * A session that requires clients to send a token for authentication. * * @author ingo herwig <ingo@wemove.com> */ interface TokenBasedSession extends Session { /** * Get the name of the auth token header. * @return String */ public function getHeaderName(); /** * Get the name of the auth token cookie. * @return String */ public function getCookieName(); }
iherwig/wcmf
src/wcmf/lib/core/TokenBasedSession.php
PHP
mit
673
export default function formatList(xs, { ifEmpty = 'нет', joint = ', ' } = {}) { return (!xs || xs.length === 0) ? ifEmpty : xs.join(joint) }
whitescape/react-admin-components
src/ui/format/list.js
JavaScript
mit
147
<?php namespace Tests\Builders; class SaveCardBuilder extends AbstractModelBuilder { public function __construct() { $this->attributeValues = array( 'yourConsumerReference' => '12345', 'cardNumber' => '4976000000003436', 'expiryDate' => '12/20', 'cv2' => 452, ); } }
JudoPay/PhpSdk
tests/Builders/SaveCardBuilder.php
PHP
mit
385
// $Author: benine $ // $Date$ // $Log$ // Contains the mismatch class for afin #ifndef MISMATCH_H #define MISMATCH_H //////////////////////////////////////////////\ // Mismatch Class: ////////////////////////////> ////////////////////////////////////////////// // // Mismatch object, contains all classes, methods, data, and data references necessary for processing mismatches for contig fusion // There will be only one Process object needed per iteration of this program class Mismatch{ private: double score; int length; int index_i; int index_j; int end_i; int end_j; public: Mismatch(); Mismatch( double score, int length, int index_i, int index_j, int end_i, int end_j ); // set mismatch score void set_score( double score ); // set length void set_length( int length ); // set index_i void set_index_i( int index ); // set index_j void set_index_j( int index ); // set index void set_indices( int index_i, int index_j ); // set end_i void set_end_i( int end_i ); // set end_j void set_end_j( int end_j ); // return mismatch score double get_score(); // return length int get_length(); // return index i int get_index_i(); // return index j int get_index_j(); // return end_i int get_end_i(); // return end_j int get_end_j(); }; #endif
mrmckain/Fast-Plast
afin/mismatch.hpp
C++
mit
1,405
<?php /* * 注意:此文件由itpl_engine编译型模板引擎编译生成。 * 如果您的模板要进行修改,请修改 templates/default/shop/map.html * 如果您的模型要进行修改,请修改 models/shop/map.php * * 修改完成之后需要您进入后台重新编译,才会重新生成。 * 如果您开启了debug模式运行,那么您可以省去上面这一步,但是debug模式每次都会判断程序是否更新,debug模式只适合开发调试。 * 如果您正式运行此程序时,请切换到service模式运行! * * 如您有问题请到官方论坛()提问,谢谢您的支持。 */ ?><?php /* * 此段代码由debug模式下生成运行,请勿改动! * 如果debug模式下出错不能再次自动编译时,请进入后台手动编译! */ /* debug模式运行生成代码 开始 */ if (!function_exists("tpl_engine")) { require("foundation/ftpl_compile.php"); } if(filemtime("templates/default/shop/map.html") > filemtime(__file__) || (file_exists("models/shop/map.php") && filemtime("models/shop/map.php") > filemtime(__file__)) ) { tpl_engine("default", "shop/map.html", 1); include(__file__); } else { /* debug模式运行生成代码 结束 */ ?><?php if (!$IWEB_SHOP_IN) { trigger_error('Hacking attempt'); } /* 公共信息处理 header, left, footer */ require("foundation/module_shop.php"); require("foundation/module_users.php"); require("foundation/module_shop_category.php"); //引入语言包 $s_langpackage = new shoplp; $i_langpackage = new indexlp; /* 数据库操作 */ dbtarget('r', $dbServs); $dbo = new dbex(); /* 定义文件表 */ $t_shop_info = $tablePreStr . "shop_info"; $t_users = $tablePreStr . "users"; $t_shop_category = $tablePreStr . "shop_category"; $t_shop_categories = $tablePreStr . "shop_categories"; /* 商铺信息处理 */ $SHOP = get_shop_info($dbo, $t_shop_info, $shop_id); //商铺分类 $shop_rank = $SHOP['shop_categories']; $shop_rank_arr = get_categories_rank($shop_rank, $dbo, $t_shop_categories); if ($shop_rank_arr) { $num = count($shop_rank_arr) - 1; } if (!$SHOP) { trigger_error($s_langpackage->s_shop_error); }//无此商铺 if ($SHOP['lock_flg']) { trigger_error($s_langpackage->s_shop_locked); }//锁定 if ($SHOP['open_flg']) { trigger_error($s_langpackage->s_shop_close); }//关闭 $sql = "select rank_id,user_name,last_login_time from $t_users where user_id='" . $SHOP['user_id'] . "'"; $ranks = $dbo->getRow($sql); $SHOP['rank_id'] = $ranks[0]; /* 文章头部信息 */ $header = get_shop_header($s_langpackage->s_shop_index, $SHOP); //$nav_selected=3; ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title><?php echo $header['title']; ?></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/> <meta name="keywords" content="<?php echo $header['keywords']; ?>"/> <meta name="description" content="<?php echo $header['description']; ?>"/> <base href="<?php echo $baseUrl; ?>"/> <link href="skin/<?php echo $SYSINFO['templates']; ?>/css/shop.css" rel="stylesheet" type="text/css"/> <link href="skin/<?php echo $SYSINFO['templates']; ?>/css/import.css" type="text/css" rel="stylesheet"/> <link href="skin/<?php echo $SYSINFO['templates']; ?>/css/article.css" type="text/css" rel="stylesheet"/> <link href="skin/<?php echo $SYSINFO['templates']; ?>/css/shop_<?php echo $SHOP['shop_template']; ?>.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="skin/<?php echo $SYSINFO['templates']; ?>/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="skin/<?php echo $SYSINFO['templates']; ?>/js/changeStyle.js"></script> <style> <?php if($SHOP['shop_template_img']){?> #shopHeader { background: transparent url(<?php echo $SHOP['shop_template_img'];?>) no-repeat scroll 0 0 #4A9DA5; } <?php }?> </style> </head> <body onload="initialize()" onunload="GUnload()"> <!-- wrapper --> <div id="wrapper"> <?php require("shop/index_header.php"); ?> <!-- contents --> <div id="contents" class="clearfix"> <div id="pkz"> <?php echo $s_langpackage->s_this_location; ?><a href="index.php"><?php echo $SYSINFO['sys_name']; ?></a> &gt; <a href="shop_list.php"><?php echo $s_langpackage->s_shop_category; ?></a> &gt; <?php foreach ($shop_rank_arr as $k => $value) { ?> <?php if ($num == $k) { ?> <a href=""><?php echo $value['cat_name']; ?></a> <?php } else { ?> <a href=""><?php echo $value['cat_name']; ?></a> &gt; <?php } ?> <?php } ?> </div> <div id="shopHeader" class=" mg12b clearfix"> <p class="shopName"><?php echo $SHOP['shop_name']; ?></p> <div class="shop_nav"> <?php require("shop/menu.php"); ?> </div> </div> <?php require("shop/left.php"); ?> <div id="rightCloumn"> <div class="bigpart"> <div class="shop_notice top10"> <div class="c_t"> <div class="c_t_l left"></div> <div class="c_t_r right"></div> <h2><a href="javascript:;"><?php echo $s_langpackage->s_shop_seat; ?></a><span></span></h2> </div> <div class="c_m"> <div id="map_canvas" style="width: 688px; height: 500px"></div> </div> <div class="c_bt"> <div class="c_bt_l left"></div> <div class="c_bt_r right"></div> </div> </div> </div> </div> </div> <?php require("shop/index_footer.php"); ?> <script src="http://maps.google.com/maps?file=api&v=2.x&key=<?php echo $SYSINFO['map_key']; ?>" type="text/javascript"></script> <script type="text/javascript"> var now_x = <?php echo $SHOP['map_x'];?>; var now_y = <?php echo $SHOP['map_y'];?>; var now_zoom = <?php echo $SHOP['map_zoom'];?>; function initialize() { if (GBrowserIsCompatible()) { var map = new GMap2(document.getElementById("map_canvas")); var center = new GLatLng(now_y, now_x); map.setCenter(center, now_zoom); var point = new GLatLng(now_y, now_x); var marker = new GMarker(point); map.addOverlay(marker); map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl()); } } </script> </body> </html><?php } ?>
hisuley/gds
trunk/shop/map.php
PHP
mit
7,143
package com.example; import java.util.Set; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class ServletContainerInitializerImpl implements ServletContainerInitializer { @Override public void onStartup(final Set<Class<?>> c, final ServletContext ctx) throws ServletException { final AnnotationConfigWebApplicationContext wac = new AnnotationConfigWebApplicationContext(); wac.register(MvcConfig.class); wac.refresh(); final DispatcherServlet servlet = new DispatcherServlet(wac); final ServletRegistration.Dynamic reg = ctx.addServlet("dispatcher", servlet); reg.addMapping("/*"); } }
backpaper0/sandbox
springmvc-study-no-xml/src/main/java/com/example/ServletContainerInitializerImpl.java
Java
mit
923
import React from 'react'; const EditHero = props => { if (props.selectedHero) { return ( <div> <div className="editfields"> <div> <label>id: </label> {props.addingHero ? <input type="number" name="id" placeholder="id" value={props.selectedHero.id} onChange={props.onChange} /> : <label className="value"> {props.selectedHero.id} </label>} </div> <div> <label>name: </label> <input name="name" value={props.selectedHero.name} placeholder="name" onChange={props.onChange} /> </div> <div> <label>saying: </label> <input name="saying" value={props.selectedHero.saying} placeholder="saying" onChange={props.onChange} /> </div> </div> <button onClick={props.onCancel}>Cancel</button> <button onClick={props.onSave}>Save</button> </div> ); } else { return <div />; } }; export default EditHero;
Ryan-ZL-Lin/react-cosmosdb
src/components/EditHero.js
JavaScript
mit
1,289
/** * Module dependencies. */ var express = require('express') var MemoryStore = express.session.MemoryStore var mongoStore = require('connect-mongo')(express) var path = require('path') var fs = require('fs') var _ = require('underscore') var mongoose = require('mongoose') var passport = require('passport') var http = require('http') var socketio = require('socket.io') var passportSocketIo = require('passport.socketio') // Load configurations var env = process.env.NODE_ENV || 'development' var config = require('./config/config')[env] // Bootstrap db connection mongoose.connect(config.db) // Bootstrap models var modelsDir = path.join(__dirname, '/app/models') fs.readdirSync(modelsDir).forEach(function (file) { if (~file.indexOf('.js')) require(modelsDir + '/' + file) }) // Bootstrap passport config require('./config/passport')(passport, config) var app = express() var store = new mongoStore({ url : config.db, collection : 'sessions' }); //var store = new MemoryStore() // express settings require('./config/express')(app, config, passport, store) // Bootstrap routes require('./config/routes')(app, passport) var server = http.createServer(app) var sio = socketio.listen(server) var clients = {} var socketsOfClients = {} sio.configure(function () { sio.set('authorization', passportSocketIo.authorize({ cookieParser: express.cookieParser, //or connect.cookieParser key: 'express.sid', //the cookie where express (or connect) stores the session id. secret: 'dirty', //the session secret to parse the cookie store: store, //the session store that express uses fail: function (data, accept) { // *optional* callbacks on success or fail accept(null, false) // second parameter takes boolean on whether or not to allow handshake }, success: function (data, accept) { accept(null, true) } })) }) // upon connection, start a periodic task that emits (every 1s) the current timestamp sio.sockets.on('connection', function (socket) { var username = socket.handshake.user.username; clients[username] = socket.id socketsOfClients[socket.id] = username userNameAvailable(socket.id, username) userJoined(username) socket.on('data', function (data) { socket.broadcast.emit('data', { 'drawing' : data }) }) socket.on('message', function (data) { var now = new Date(); sio.sockets.emit('message', { 'source': socketsOfClients[socket.id], 'time': now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds(), 'message': data.message }) }) socket.on('disconnect', function() { var username = socketsOfClients[socket.id] delete socketsOfClients[socket.id] delete clients[username]; // relay this message to all the clients userLeft(username) }) }) // Start the application by listening on port <> var port = process.env.PORT || 3000 server.listen(port, function(){ console.log('Express server listening on port ' + port) }); function userNameAvailable(socketId, username) { setTimeout(function(){ sio.sockets.sockets[socketId].emit('user welcome', { "currentUsers": JSON.stringify(Object.keys(clients)) }); }, 500); } function userJoined(username) { Object.keys(socketsOfClients).forEach(function(socketId) { sio.sockets.sockets[socketId].emit('user joined', { "username": username }); }); } function userLeft(username) { sio.sockets.emit('user left', { "username": username }); } // expose app exports = module.exports = app;
rtorino/shiny-octo-ironman
app.js
JavaScript
mit
3,595
#guimporter.py import sys from PySide import QtGui, QtCore, QtWebKit Signal = QtCore.Signal
lazunin/stclient
guimporter.py
Python
mit
92
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("SearchForANumber")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SearchForANumber")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("fe6220fa-63b8-4168-9867-f466b571c2a5")] // 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")]
davidvaleff/ProgrammingFundamentals-Sept2017
06.Lists/Exercises/SearchForANumber/Properties/AssemblyInfo.cs
C#
mit
1,403
'use strict'; var redis = require('redis') , xtend = require('xtend') , hyperquest = require('hyperquest') ; module.exports = FetchAndCache; /** * Creates a fetchncache instance. * * #### redis opts * * - **opts.redis.host** *{number=}* host at which redis is listening, defaults to `127.0.0.1` * - **opts.redis.port** *{string=}* port at which redis is listening, defaults to `6379` * * #### service opts * * - **opts.service.url** *{string=}* url at which to reach the service * * @name fetchncache * @function * @param {Object=} opts * @param {Object=} opts.redis redis options passed straight to [redis](https://github.com/mranney/node_redis) (@see above) * @param {Object=} opts.service options specifying how to reach the service that provides the data (@see above) * @param {number=} opts.expire the default number of seconds after which to expire a resource from the redis cache (defaults to 15mins) * @return {Object} fetchncache instance */ function FetchAndCache(opts) { if (!(this instanceof FetchAndCache)) return new FetchAndCache(opts); opts = opts || {}; var redisOpts = xtend({ port: 6379, host: '127.0.0.1' }, opts.redis) , serviceOpts = xtend({ url: 'http://127.0.0.1' }, opts.service) this._defaultExpire = opts.expire || 15 * 60 // 15min this._serviceOpts = serviceOpts; this._markCached = opts.markCached !== false; this._client = redis.createClient(redisOpts.port, redisOpts.host, redisOpts) } var proto = FetchAndCache.prototype; /** * Fetches the resource, probing the redis cache first and falling back to the service. * If a transform function is provided (@see opts), that is applied to the result before returning or caching it. * When fetched from the service it is added to the redis cached according to the provided options. * * @name fetcncache::fetch * @function * @param {string} uri path to the resource, i.e. `/reource1?q=1234` * @param {Object=} opts configure caching and transformation behavior for this particular resource * @param {number=} opts.expire overrides default expire for this particular resource * @param {function=} opts.transform specify the transform function to be applied, default: `function (res} { return res }` * @param {function} cb called back with an error or the transformed resource */ proto.fetch = function (uri, opts, cb) { var self = this; if (!self._client) return cb(new Error('fetchncache was stopped and can no longer be used to fetch data')); if (typeof opts === 'function') { cb = opts; opts = null; } opts = xtend({ expire: self._defaultExpire, transform: function (x) { return x } }, opts); self._client.get(uri, function (err, res) { if (err) return cb(err); if (res) return cb(null, res, true); self._get(uri, function (err, res) { if (err) return cb(err); self._cache(uri, res, opts, cb); }) }); } /** * Stops the redis client in order to allow exiting the application. * At this point this fetchncache instance becomes unusable and throws errors on any attempts to use it. * * @name fetchncache::stop * @function * @param {boolean=} force will make it more aggressive about ending the underlying redis client (default: false) */ proto.stop = function (force) { if (!this._client) throw new Error('fetchncache was stopped previously and cannot be stopped again'); if (force) this._client.end(); else this._client.unref(); this._client = null; } /** * Clears the entire redis cache, so use with care. * Mainly useful for testing or to ensure that all resources get refreshed. * * @name fetchncache::clearCache * @function * @return {Object} fetchncache instance */ proto.clearCache = function () { if (!this._client) throw new Error('fetchncache was stopped previously and cannot be cleared'); this._client.flushdb(); return this; } proto._get = function (uri, cb) { var body = ''; var url = this._serviceOpts.url + uri; console.log('url', url); hyperquest .get(url) .on('error', cb) .on('data', function (d) { body += d.toString() }) .on('end', function () { cb(null, body) }) } proto._cache = function (uri, res, opts, cb) { var self = this; var val; try { val = opts.transform(res); } catch (e) { return cb(e); } // assuming that value is now a string we use set to add it self._client.set(uri, val, function (err) { if (err) return cb(err); self._client.expire(uri, opts.expire, function (err) { if (err) return cb(err); cb(null, val); }) }); }
thlorenz/fetchncache
index.js
JavaScript
mit
4,638
package org.blendee.jdbc; /** * プレースホルダを持つ SQL 文と、プレースホルダにセットする値を持つものを表すインターフェイスです。 * @author 千葉 哲嗣 */ public interface ComposedSQL extends ChainPreparedStatementComplementer { /** * このインスタンスが持つ SQL 文を返します。 * @return SQL 文 */ String sql(); /** * {@link PreparedStatementComplementer} を入れ替えた新しい {@link ComposedSQL} を生成します。 * @param complementer 入れ替える {@link PreparedStatementComplementer} * @return 同じ SQL を持つ、別のインスタンス */ default ComposedSQL reproduce(PreparedStatementComplementer complementer) { var sql = sql(); return new ComposedSQL() { @Override public String sql() { return sql; } @Override public int complement(int done, BPreparedStatement statement) { complementer.complement(statement); return Integer.MIN_VALUE; } }; } /** * {@link ChainPreparedStatementComplementer} を入れ替えた新しい {@link ComposedSQL} を生成します。 * @param complementer 入れ替える {@link ChainPreparedStatementComplementer} * @return 同じ SQL を持つ、別のインスタンス */ default ComposedSQL reproduce(ChainPreparedStatementComplementer complementer) { var sql = sql(); return new ComposedSQL() { @Override public String sql() { return sql; } @Override public int complement(int done, BPreparedStatement statement) { return complementer.complement(done, statement); } }; } }
blendee/blendee
src/main/java/org/blendee/jdbc/ComposedSQL.java
Java
mit
1,611
<TS language="es_419" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Haga clic para editar la dirección o etiqueta</translation> </message> <message> <source>Create a new address</source> <translation>Crear una nueva dirección</translation> </message> <message> <source>&amp;New</source> <translation>&amp;New</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Copia la dirección seleccionada al portapapeles del sistema</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Borrar la dirección que esta seleccionada en la lista</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportar los datos de la actual tabla hacia un archivo</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Seleccione la dirección a la que enviará las monedas</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>Seleccione la dirección con la que recibirá las monedas</translation> </message> <message> <source>Sending addresses</source> <translation>Enviando direcciones</translation> </message> <message> <source>Receiving addresses</source> <translation>Recibiendo direcciones</translation> </message> <message> <source>These are your Pandacoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Estas son sus direcciones de Pandacoin para enviar sus pagos. Siempre revise el monto y la dirección recibida antes de enviar monedas.</translation> </message> </context> <context> <name>AddressTableModel</name> </context> <context> <name>AskPassphraseDialog</name> </context> <context> <name>BanTableModel</name> </context> <context> <name>BitcoinGUI</name> </context> <context> <name>CoinControlDialog</name> </context> <context> <name>EditAddressDialog</name> </context> <context> <name>FreespaceChecker</name> </context> <context> <name>HelpMessageDialog</name> </context> <context> <name>Intro</name> </context> <context> <name>ModalOverlay</name> </context> <context> <name>OpenURIDialog</name> </context> <context> <name>OptionsDialog</name> </context> <context> <name>OverviewPage</name> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> </context> <context> <name>QObject::QObject</name> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> </context> <context> <name>ReceiveCoinsDialog</name> </context> <context> <name>ReceiveRequestDialog</name> </context> <context> <name>RecentRequestsTableModel</name> </context> <context> <name>SendCoinsDialog</name> </context> <context> <name>SendCoinsEntry</name> </context> <context> <name>SendConfirmationDialog</name> </context> <context> <name>ShutdownWindow</name> </context> <context> <name>SignVerifyMessageDialog</name> </context> <context> <name>SplashScreen</name> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> </context> <context> <name>TransactionDescDialog</name> </context> <context> <name>TransactionTableModel</name> </context> <context> <name>TransactionView</name> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> </context> <context> <name>WalletView</name> <message> <source>Export the data in the current tab to a file</source> <translation>Exportar los datos de la actual tabla hacia un archivo</translation> </message> </context> <context> <name>bitcoin-core</name> </context> </TS>
DigitalPandacoin/pandacoin
src/qt/locale/bitcoin_es_419.ts
TypeScript
mit
4,495
package com.github.sixro.minihabits.core.infrastructure.domain; import java.util.*; import com.badlogic.gdx.Preferences; import com.github.sixro.minihabits.core.domain.*; public class PreferencesBasedRepository implements Repository { private final Preferences prefs; public PreferencesBasedRepository(Preferences prefs) { super(); this.prefs = prefs; } @Override public Set<MiniHabit> findAll() { String text = prefs.getString("mini_habits"); if (text == null || text.trim().isEmpty()) return new LinkedHashSet<MiniHabit>(); return newMiniHabits(text); } @Override public void add(MiniHabit miniHabit) { Set<MiniHabit> list = findAll(); list.add(miniHabit); prefs.putString("mini_habits", asString(list)); prefs.flush(); } @Override public void update(Collection<MiniHabit> list) { Set<MiniHabit> currentList = findAll(); currentList.removeAll(list); currentList.addAll(list); prefs.putString("mini_habits", asString(currentList)); prefs.flush(); } @Override public void updateProgressDate(DateAtMidnight aDate) { prefs.putLong("last_feedback_timestamp", aDate.getTime()); prefs.flush(); } @Override public DateAtMidnight lastFeedbackDate() { long timestamp = prefs.getLong("last_feedback_timestamp"); if (timestamp == 0L) return null; return DateAtMidnight.from(timestamp); } private Set<MiniHabit> newMiniHabits(String text) { String[] parts = text.split(","); Set<MiniHabit> ret = new LinkedHashSet<MiniHabit>(); for (String part: parts) ret.add(newMiniHabit(part)); return ret; } private MiniHabit newMiniHabit(String part) { int indexOfColon = part.indexOf(':'); String label = part.substring(0, indexOfColon); Integer daysInProgress = Integer.parseInt(part.substring(indexOfColon +1)); MiniHabit habit = new MiniHabit(label, daysInProgress); return habit; } private String asString(Collection<MiniHabit> list) { StringBuilder b = new StringBuilder(); int i = 0; for (MiniHabit each: list) { b.append(each.label() + ":" + each.daysInProgress()); if (i < list.size()-1) b.append(','); i++; } return b.toString(); } }
sixro/minihabits
core/src/main/java/com/github/sixro/minihabits/core/infrastructure/domain/PreferencesBasedRepository.java
Java
mit
2,241
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); let _ = require('lodash'); let async = require('async'); const pip_services3_commons_node_1 = require("pip-services3-commons-node"); const pip_services3_facade_node_1 = require("pip-services3-facade-node"); class RolesOperationsV1 extends pip_services3_facade_node_1.FacadeOperations { constructor() { super(); this._dependencyResolver.put('roles', new pip_services3_commons_node_1.Descriptor('pip-services-roles', 'client', '*', '*', '1.0')); } setReferences(references) { super.setReferences(references); this._rolesClient = this._dependencyResolver.getOneRequired('roles'); } getUserRolesOperation() { return (req, res) => { this.getUserRoles(req, res); }; } grantUserRolesOperation() { return (req, res) => { this.grantUserRoles(req, res); }; } revokeUserRolesOperation() { return (req, res) => { this.revokeUserRoles(req, res); }; } getUserRoles(req, res) { let userId = req.route.params.user_id; this._rolesClient.getRolesById(null, userId, this.sendResult(req, res)); } grantUserRoles(req, res) { let userId = req.route.params.user_id; let roles = req.body; this._rolesClient.grantRoles(null, userId, roles, this.sendResult(req, res)); } revokeUserRoles(req, res) { let userId = req.route.params.user_id; let roles = req.body; this._rolesClient.revokeRoles(null, userId, roles, this.sendResult(req, res)); } } exports.RolesOperationsV1 = RolesOperationsV1; //# sourceMappingURL=RolesOperationsV1.js.map
pip-services-users/pip-facade-users-node
obj/src/operations/version1/RolesOperationsV1.js
JavaScript
mit
1,730
require_relative 'rules_factory_common' FactoryBot.define do factory :priority_bills, parent: :answers do factory :S6_H1_missed_payment_low, traits: [:country, :S6_H1_missed_payment_low_answers] factory :S6_H2_council_tax_severe, traits: [:country, :S6_H2_tax_severe_answers] factory :S6_H2_domestic_rates_severe, traits: [:country, :S6_H2_tax_severe_answers] factory :S6_H2_council_tax_temp_worried, traits: [:country, :S6_H2_tax_temp_worried_answers] factory :S6_H2_domestic_rates_temp_worried, traits: [:country, :S6_H2_tax_temp_worried_answers] factory :S6_H2_council_tax_temp_normal, traits: [:country, :S6_H2_tax_temp_normal_answers] factory :S6_H2_domestic_rates_temp_normal, traits: [:country, :S6_H2_tax_temp_normal_answers] factory :S6_H2_council_tax_no_change, traits: [:country, :S6_H2_tax_no_change_answers] factory :S6_H2_domestic_rates_no_change, traits: [:country, :S6_H2_tax_no_change_answers] factory :S6_H3_gas_electricity_severe, traits: [:country, :S6_H3_gas_electricity_severe_answers] factory :S6_H3_gas_electricity_temp_worried, traits: [:country, :S6_H3_gas_electricity_temp_worried_answers] factory :S6_H3_gas_electricity_temp_normal, traits: [:country, :S6_H3_gas_electricity_temp_normal_answers] factory :S6_H3_gas_electricity_no_change, traits: [:country, :S6_H3_gas_electricity_no_change_answers] factory :S6_H4_dmp_hmrc_severe, traits: [:country, :S6_H4_dmp_hmrc_severe_answers] factory :S6_H4_dmp_hmrc_temp_worried, traits: [:country, :S6_H4_dmp_hmrc_temp_worried_answers] factory :S6_H4_dmp_hmrc_temp_normal, traits: [:country, :S6_H4_dmp_hmrc_temp_normal_answers] factory :S6_H4_dmp_hmrc_no_change, traits: [:country, :S6_H4_dmp_hmrc_no_change_answers] factory :S6_H5_tv_licence_severe, traits: [:country, :S6_H5_tv_licence_severe_answers] factory :S6_H5_tv_licence_temp_worried, traits: [:country, :S6_H5_tv_licence_temp_worried_answers] factory :S6_H5_tv_licence_temp_normal, traits: [:country, :S6_H5_tv_licence_temp_normal_answers] factory :S6_H5_tv_licence_no_change, traits: [:country, :S6_H5_tv_licence_no_change_answers] factory :S6_H6_income_tax_severe, traits: [:country, :S6_H6_income_tax_severe_answers] factory :S6_H6_income_tax_temp_worried, traits: [:country, :S6_H6_income_tax_temp_worried_answers] factory :S6_H6_income_tax_temp_normal, traits: [:country, :S6_H6_income_tax_temp_normal_answers] factory :S6_H6_income_tax_no_change, traits: [:country, :S6_H6_income_tax_no_change_answers] factory :S6_H7_child_maintenance_severe, traits: [:country, :S6_H7_child_maintenance_severe_answers] factory :S6_H7_child_maintenance_temp_worried, traits: [:country, :S6_H7_child_maintenance_temp_worried_answers] factory :S6_H7_child_maintenance_temp_normal, traits: [:country, :S6_H7_child_maintenance_temp_normal_answers] factory :S6_H7_child_maintenance_no_change, traits: [:country, :S6_H7_child_maintenance_no_change_answers] factory :S6_H8_court_fines_severe, traits: [:country, :S6_H8_court_fines_severe_answers] factory :S6_H8_court_fines_temp_worried, traits: [:country, :S6_H8_court_fines_temp_worried_answers] factory :S6_H8_court_fines_temp_normal, traits: [:country, :S6_H8_court_fines_temp_normal_answers] factory :S6_H8_court_fines_temp_normal_ni, traits: [:country, :S6_H8_court_fines_temp_normal_ni_answers] factory :S6_H8_court_fines_temp_normal_scotland, traits: [:country, :S6_H8_court_fines_temp_normal_scotland_answers] factory :S6_H8_court_fines_no_change, traits: [:country, :S6_H8_court_fines_no_change_answers] factory :S6_H9_hire_purchase_severe, traits: [:country, :S6_H9_hire_purchase_severe_answers] factory :S6_H9_hire_purchase_temp_worried, traits: [:country, :S6_H9_hire_purchase_temp_worried_answers] factory :S6_H9_hire_purchase_temp_normal, traits: [:country, :S6_H9_hire_purchase_temp_normal_answers] factory :S6_H9_hire_purchase_no_change, traits: [:country, :S6_H9_hire_purchase_no_change_answers] factory :S6_H10_car_park_severe, traits: [:country, :S6_H10_car_park_severe_answers] factory :S6_H10_car_park_temp_worried, traits: [:country, :S6_H10_car_park_temp_worried_answers] factory :S6_H10_car_park_temp_normal, traits: [:country, :S6_H10_car_park_temp_normal_answers] factory :S6_H10_car_park_temp_normal_ni, traits: [:country, :S6_H10_car_park_temp_normal_ni_answers] factory :S6_H10_car_park_temp_normal_scotland, traits: [:country, :S6_H10_car_park_temp_normal_scotland_answers] factory :S6_H10_car_park_no_change, traits: [:country, :S6_H10_car_park_no_change_answers] trait :S6_H1_missed_payment_low_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', [], nil) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H2_tax_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a1'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H2_tax_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a1'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H2_tax_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a1'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H2_tax_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a1'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H3_gas_electricity_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a2'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H3_gas_electricity_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a2'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H3_gas_electricity_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a2'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H3_gas_electricity_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a2'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H4_dmp_hmrc_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a3'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H4_dmp_hmrc_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a3'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H4_dmp_hmrc_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a3'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H4_dmp_hmrc_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a3'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H5_tv_licence_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a4'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H5_tv_licence_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a4'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H5_tv_licence_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a4'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H5_tv_licence_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a4'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H6_income_tax_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a5'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H6_income_tax_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a5'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H6_income_tax_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a5'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H6_income_tax_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a5'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H7_child_maintenance_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a6'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H7_child_maintenance_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a6'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H7_child_maintenance_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a6'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H7_child_maintenance_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a6'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_temp_normal_ni_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_temp_normal_scotland_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H9_hire_purchase_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a8'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H9_hire_purchase_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a8'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H9_hire_purchase_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a8'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H9_hire_purchase_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a8'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_temp_normal_ni_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_temp_normal_scotland_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'],[] ) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end end end
moneyadviceservice/frontend
features/factories/money_navigator/priority_bills_rules.rb
Ruby
mit
33,882
var config = require('../lib/config')(); var Changeset = require('./Changeset'); var queries = require('./queries'); var helpers = require('../helpers'); require('../validators'); var validate = require('validate.js'); var errors = require('../errors'); var pgPromise = helpers.pgPromise; var promisifyQuery = helpers.promisifyQuery; var changesets = {}; module.exports = changesets; var pgURL = config.PostgresURL; changesets.search = function(params) { var parseError = validateParams(params); if (parseError) { return Promise.reject(new errors.ParseError(parseError)); } var searchQuery = queries.getSearchQuery(params); var countQuery = queries.getCountQuery(params); console.log('searchQ', searchQuery); console.log('countQ', countQuery); return pgPromise(pgURL) .then(function (pg) { var query = promisifyQuery(pg.client); var searchProm = query(searchQuery.text, searchQuery.values); var countProm = query(countQuery.text, countQuery.values); return Promise.all([searchProm, countProm]) .then(function (r) { pg.done(); return r; }) .catch(function (e) { pg.done(); return Promise.reject(e); }); }) .then(processSearchResults); }; changesets.get = function(id) { if (!validate.isNumber(parseInt(id, 10))) { return Promise.reject(new errors.ParseError('Changeset id must be a number')); } var changesetQuery = queries.getChangesetQuery(id); var changesetCommentsQuery = queries.getChangesetCommentsQuery(id); return pgPromise(pgURL) .then(function (pg) { var query = promisifyQuery(pg.client); var changesetProm = query(changesetQuery.text, changesetQuery.values); var changesetCommentsProm = query(changesetCommentsQuery.text, changesetCommentsQuery.values); return Promise.all([changesetProm, changesetCommentsProm]) .then(function (results) { pg.done(); return results; }) .catch(function (e) { pg.done(); return Promise.reject(e); }); }) .then(function (results) { var changesetResult = results[0]; if (changesetResult.rows.length === 0) { return Promise.reject(new errors.NotFoundError('Changeset not found')); } var changeset = new Changeset(results[0].rows[0], results[1].rows); return changeset.getGeoJSON(); }); }; function processSearchResults(results) { var searchResult = results[0]; var countResult = results[1]; var changesetsArray = searchResult.rows.map(function (row) { var changeset = new Changeset(row); return changeset.getGeoJSON(); }); var count; if (countResult.rows.length > 0) { count = countResult.rows[0].count; } else { count = 0; } var featureCollection = { 'type': 'FeatureCollection', 'features': changesetsArray, 'total': count }; return featureCollection; } function validateParams(params) { var constraints = { 'from': { 'presence': false, 'datetime': true }, 'to': { 'presence': false, 'datetime': true }, 'bbox': { 'presence': false, 'bbox': true } }; var errs = validate(params, constraints); if (errs) { var errMsg = Object.keys(errs).map(function(key) { return errs[key][0]; }).join(', '); return errMsg; } return null; }
mapbox/osm-comments-api
changesets/index.js
JavaScript
mit
3,841
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.Windows.Automation.Peers; using System.Windows.Media; using System.Windows.Threading; using MS.Internal.KnownBoxes; namespace System.Windows.Controls.Primitives { /// <summary> /// StatusBar is a visual indicator of the operational status of an application and/or /// its components running in a window. StatusBar control consists of a series of zones /// on a band that can display text, graphics, or other rich content. The control can /// group items within these zones to emphasize relational similarities or functional /// connections. The StatusBar can accommodate multiple sets of UI or functionality that /// can be chosen even within the same application. /// </summary> [StyleTypedProperty(Property = "ItemContainerStyle", StyleTargetType = typeof(StatusBarItem))] public class StatusBar : ItemsControl { //------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Constructors static StatusBar() { DefaultStyleKeyProperty.OverrideMetadata(typeof(StatusBar), new FrameworkPropertyMetadata(typeof(StatusBar))); _dType = DependencyObjectType.FromSystemTypeInternal(typeof(StatusBar)); IsTabStopProperty.OverrideMetadata(typeof(StatusBar), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox)); ItemsPanelTemplate template = new ItemsPanelTemplate(new FrameworkElementFactory(typeof(DockPanel))); template.Seal(); ItemsPanelProperty.OverrideMetadata(typeof(StatusBar), new FrameworkPropertyMetadata(template)); } #endregion #region Public Properties /// <summary> /// DependencyProperty for ItemContainerTemplateSelector property. /// </summary> public static readonly DependencyProperty ItemContainerTemplateSelectorProperty = MenuBase.ItemContainerTemplateSelectorProperty.AddOwner( typeof(StatusBar), new FrameworkPropertyMetadata(new DefaultItemContainerTemplateSelector())); /// <summary> /// DataTemplateSelector property which provides the DataTemplate to be used to create an instance of the ItemContainer. /// </summary> public ItemContainerTemplateSelector ItemContainerTemplateSelector { get { return (ItemContainerTemplateSelector)GetValue(ItemContainerTemplateSelectorProperty); } set { SetValue(ItemContainerTemplateSelectorProperty, value); } } /// <summary> /// DependencyProperty for UsesItemContainerTemplate property. /// </summary> public static readonly DependencyProperty UsesItemContainerTemplateProperty = MenuBase.UsesItemContainerTemplateProperty.AddOwner(typeof(StatusBar)); /// <summary> /// UsesItemContainerTemplate property which says whether the ItemContainerTemplateSelector property is to be used. /// </summary> public bool UsesItemContainerTemplate { get { return (bool)GetValue(UsesItemContainerTemplateProperty); } set { SetValue(UsesItemContainerTemplateProperty, value); } } #endregion //------------------------------------------------------------------- // // Protected Methods // //------------------------------------------------------------------- #region Protected Methods private object _currentItem; /// <summary> /// Return true if the item is (or is eligible to be) its own ItemUI /// </summary> protected override bool IsItemItsOwnContainerOverride(object item) { bool ret = (item is StatusBarItem) || (item is Separator); if (!ret) { _currentItem = item; } return ret; } protected override DependencyObject GetContainerForItemOverride() { object currentItem = _currentItem; _currentItem = null; if (UsesItemContainerTemplate) { DataTemplate itemContainerTemplate = ItemContainerTemplateSelector.SelectTemplate(currentItem, this); if (itemContainerTemplate != null) { object itemContainer = itemContainerTemplate.LoadContent(); if (itemContainer is StatusBarItem || itemContainer is Separator) { return itemContainer as DependencyObject; } else { throw new InvalidOperationException(SR.Get(SRID.InvalidItemContainer, this.GetType().Name, typeof(StatusBarItem).Name, typeof(Separator).Name, itemContainer)); } } } return new StatusBarItem(); } /// <summary> /// Prepare the element to display the item. This may involve /// applying styles, setting bindings, etc. /// </summary> protected override void PrepareContainerForItemOverride(DependencyObject element, object item) { base.PrepareContainerForItemOverride(element, item); Separator separator = element as Separator; if (separator != null) { bool hasModifiers; BaseValueSourceInternal vs = separator.GetValueSource(StyleProperty, null, out hasModifiers); if (vs <= BaseValueSourceInternal.ImplicitReference) separator.SetResourceReference(StyleProperty, SeparatorStyleKey); separator.DefaultStyleKey = SeparatorStyleKey; } } /// <summary> /// Determine whether the ItemContainerStyle/StyleSelector should apply to the container /// </summary> /// <returns>false if item is a Separator, otherwise return true</returns> protected override bool ShouldApplyItemContainerStyle(DependencyObject container, object item) { if (item is Separator) { return false; } else { return base.ShouldApplyItemContainerStyle(container, item); } } #endregion #region Accessibility /// <summary> /// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>) /// </summary> protected override AutomationPeer OnCreateAutomationPeer() { return new StatusBarAutomationPeer(this); } #endregion #region DTypeThemeStyleKey // Returns the DependencyObjectType for the registered ThemeStyleKey's default // value. Controls will override this method to return approriate types. internal override DependencyObjectType DTypeThemeStyleKey { get { return _dType; } } private static DependencyObjectType _dType; #endregion DTypeThemeStyleKey #region ItemsStyleKey /// <summary> /// Resource Key for the SeparatorStyle /// </summary> public static ResourceKey SeparatorStyleKey { get { return SystemResourceKey.StatusBarSeparatorStyleKey; } } #endregion } }
mind0n/hive
Cache/Libs/net46/wpf/src/Framework/System/Windows/Controls/Primitives/StatusBar.cs
C#
mit
7,812
// John Meyer // CSE 271 F // Dr. Angel Bravo import java.util.Scanner; import java.io.*; /** * Copies a file with line numbers prefixed to every line */ public class Lab2InputOutput { public static void main(String[] args) throws Exception { // Define variables Scanner keyboardReader = new Scanner(System.in); String inputFileName; String outputFileName; // Check arguments if (args.length == 0) { System.out.println("Usage: java Lab2InputOutput /path/to/file"); return; } inputFileName = args[0]; // Find input file File inputFile = new File(inputFileName); Scanner fileInput = new Scanner(inputFile); // Get output file name System.out.print("Output File Name: "); outputFileName = keyboardReader.next(); File outputFile = new File(outputFileName); // Start copying PrintWriter fileOutput = new PrintWriter(outputFile); String lineContent; for (int lineNumber = 1; fileInput.hasNext(); lineNumber++) { lineContent = fileInput.nextLine(); fileOutput.printf("/* %d */ %s%n", lineNumber, lineContent); } fileInput.close(); fileOutput.close(); } // end method main } // end class Lab2InputOutput
0x326/academic-code-portfolio
2016-2021 Miami University/CSE 271 Introduction to Object-Oriented Programming/Lab02/src/main/java/Lab2InputOutput.java
Java
mit
1,334
/* ' Copyright (c) 2013 Christoc.com Software Solutions ' All rights reserved. ' ' 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. ' */ using System; using DotNetNuke.Common.Utilities; using DotNetNuke.Framework.Providers; namespace Christoc.Modules.DNNSignalR.Data { /// ----------------------------------------------------------------------------- /// <summary> /// SQL Server implementation of the abstract DataProvider class /// /// This concreted data provider class provides the implementation of the abstract methods /// from data dataprovider.cs /// /// In most cases you will only modify the Public methods region below. /// </summary> /// ----------------------------------------------------------------------------- public class SqlDataProvider : DataProvider { #region Private Members private const string ProviderType = "data"; private const string ModuleQualifier = "DNNSignalR_"; private readonly ProviderConfiguration _providerConfiguration = ProviderConfiguration.GetProviderConfiguration(ProviderType); private readonly string _connectionString; private readonly string _providerPath; private readonly string _objectQualifier; private readonly string _databaseOwner; #endregion #region Constructors public SqlDataProvider() { // Read the configuration specific information for this provider Provider objProvider = (Provider)(_providerConfiguration.Providers[_providerConfiguration.DefaultProvider]); // Read the attributes for this provider //Get Connection string from web.config _connectionString = Config.GetConnectionString(); if (string.IsNullOrEmpty(_connectionString)) { // Use connection string specified in provider _connectionString = objProvider.Attributes["connectionString"]; } _providerPath = objProvider.Attributes["providerPath"]; _objectQualifier = objProvider.Attributes["objectQualifier"]; if (!string.IsNullOrEmpty(_objectQualifier) && _objectQualifier.EndsWith("_", StringComparison.Ordinal) == false) { _objectQualifier += "_"; } _databaseOwner = objProvider.Attributes["databaseOwner"]; if (!string.IsNullOrEmpty(_databaseOwner) && _databaseOwner.EndsWith(".", StringComparison.Ordinal) == false) { _databaseOwner += "."; } } #endregion #region Properties public string ConnectionString { get { return _connectionString; } } public string ProviderPath { get { return _providerPath; } } public string ObjectQualifier { get { return _objectQualifier; } } public string DatabaseOwner { get { return _databaseOwner; } } // used to prefect your database objects (stored procedures, tables, views, etc) private string NamePrefix { get { return DatabaseOwner + ObjectQualifier + ModuleQualifier; } } #endregion #region Private Methods private static object GetNull(object field) { return Null.GetNull(field, DBNull.Value); } #endregion #region Public Methods //public override IDataReader GetItem(int itemId) //{ // return SqlHelper.ExecuteReader(ConnectionString, NamePrefix + "spGetItem", itemId); //} //public override IDataReader GetItems(int userId, int portalId) //{ // return SqlHelper.ExecuteReader(ConnectionString, NamePrefix + "spGetItemsForUser", userId, portalId); //} #endregion } }
ChrisHammond/DNN-SignalR
Providers/DataProviders/SqlDataProvider/SqlDataProvider.cs
C#
mit
4,526
module ClassifyCluster VERSION = "0.4.17" end
socialcast/classify_cluster
lib/classify_cluster/version.rb
Ruby
mit
48
// Copyright 2013 The Changkong Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package dmt const VersionNo = "20131207" /* 图片分类 */ type PictureCategory struct { Created string `json:"created"` Modified string `json:"modified"` ParentId int `json:"parent_id"` PictureCategoryId int `json:"picture_category_id"` PictureCategoryName string `json:"picture_category_name"` Position int `json:"position"` Type string `json:"type"` } /* 图片 */ type Picture struct { ClientType string `json:"client_type"` Created string `json:"created"` Deleted string `json:"deleted"` Md5 string `json:"md5"` Modified string `json:"modified"` PictureCategoryId int `json:"picture_category_id"` PictureId int `json:"picture_id"` PicturePath string `json:"picture_path"` Pixel string `json:"pixel"` Referenced bool `json:"referenced"` Sizes int `json:"sizes"` Status string `json:"status"` Title string `json:"title"` Uid int `json:"uid"` } /* 图片空间的用户信息获取,包括订购容量等 */ type UserInfo struct { AvailableSpace string `json:"available_space"` FreeSpace string `json:"free_space"` OrderExpiryDate string `json:"order_expiry_date"` OrderSpace string `json:"order_space"` RemainingSpace string `json:"remaining_space"` UsedSpace string `json:"used_space"` WaterMark string `json:"water_mark"` } /* 搜索返回的结果类 */ type TOPSearchResult struct { Paginator *TOPPaginator `json:"paginator"` VideoItems struct { VideoItem []*VideoItem `json:"video_item"` } `json:"video_items"` } /* 分页信息 */ type TOPPaginator struct { CurrentPage int `json:"current_page"` IsLastPage bool `json:"is_last_page"` PageSize int `json:"page_size"` TotalResults int `json:"total_results"` } /* 视频 */ type VideoItem struct { CoverUrl string `json:"cover_url"` Description string `json:"description"` Duration int `json:"duration"` IsOpenToOther bool `json:"is_open_to_other"` State int `json:"state"` Tags []string `json:"tags"` Title string `json:"title"` UploadTime string `json:"upload_time"` UploaderId int `json:"uploader_id"` VideoId int `json:"video_id"` VideoPlayInfo *VideoPlayInfo `json:"video_play_info"` } /* 视频播放信息 */ type VideoPlayInfo struct { AndroidpadUrl string `json:"androidpad_url"` AndroidpadV23Url *AndroidVlowUrl `json:"androidpad_v23_url"` AndroidphoneUrl string `json:"androidphone_url"` AndroidphoneV23Url *AndroidVlowUrl `json:"androidphone_v23_url"` FlashUrl string `json:"flash_url"` IpadUrl string `json:"ipad_url"` IphoneUrl string `json:"iphone_url"` WebUrl string `json:"web_url"` } /* android phone和pad播放的mp4文件类。适用2.3版本的Android。 */ type AndroidVlowUrl struct { Hd string `json:"hd"` Ld string `json:"ld"` Sd string `json:"sd"` Ud string `json:"ud"` }
yaofangou/open_taobao
api/dmt/dmt_structs.go
GO
mit
3,394
'use strict'; const assert = require('assert'); const HttpResponse = require('./http-response'); describe('HttpResponse', () => { const mockResponse = { version: '1.0', status: '200 OK' }; it('should create an instance', () => { const httpResponse = new HttpResponse(mockResponse); assert.ok(httpResponse instanceof HttpResponse); }); describe('isProtocolVersion()', () => { it('should determine if protocol version matches', () => { const httpResponse = new HttpResponse(mockResponse); assert.ok(httpResponse.isProtocolVersion('1.0')); }); it('should return false if versions do not match', () => { const httpResponse = new HttpResponse(mockResponse); assert.equal(httpResponse.isProtocolVersion('2.0'), false); }); it('should throw an error if no version specified', () => { const httpResponse = new HttpResponse(mockResponse); assert.throws(httpResponse.isProtocolVersion, /Specify a protocol `version`/); }); it('should throw an error if no version specified', () => { const httpResponse = new HttpResponse(mockResponse); assert.throws(() => httpResponse.isProtocolVersion(false), /The protocol `version` must be a string/); }); }); describe('getProtocolVersion()', () => { it('should get the protocol version', () => { const httpResponse = new HttpResponse(mockResponse); assert.equal(httpResponse.getProtocolVersion(), '1.0'); }); }); describe('setProtocolVersion()', () => { it('should set the protocol version', () => { const httpResponse = new HttpResponse(mockResponse); assert.equal(httpResponse.getProtocolVersion(), '1.0'); httpResponse.setProtocolVersion('2.0'); assert.equal(httpResponse.getProtocolVersion(), '2.0'); }); it('should throw an error if no version specified', () => { const httpResponse = new HttpResponse(mockResponse); assert.throws(httpResponse.setProtocolVersion, /Specify a protocol `version`/); }); it('should throw an error if no version specified', () => { const httpResponse = new HttpResponse(mockResponse); assert.throws(() => httpResponse.setProtocolVersion(Boolean), /The protocol `version` must be a string/); }); }); describe('isStatus()', () => { it('should determine if status matches', () => { const httpResponse = new HttpResponse(mockResponse); assert.ok(httpResponse.isStatus('200 OK')); }); it('should return false if status do not match', () => { const httpResponse = new HttpResponse(mockResponse); assert.equal(httpResponse.isStatus('400 Bad Request'), false); }); it('should throw an error if no status specified', () => { const httpResponse = new HttpResponse(mockResponse); assert.throws(httpResponse.isStatus, /Specify a `status`/); }); it('should throw an error if specified status is not a string', () => { const httpResponse = new HttpResponse(mockResponse); assert.throws(() => httpResponse.isStatus({}), /The `status` must be a string/); }); }); describe('getStatus()', () => { it('should return the status', () => { const httpResponse = new HttpResponse(mockResponse); assert.equal(httpResponse.getStatus(), '200 OK'); }); }); describe('getStatusCode()', () => { it('should return status code', () => { const httpResponse = new HttpResponse(mockResponse); assert.equal(httpResponse.getStatusCode(), '200'); }); }); describe('getStatusText()', () => { it('should return status text', () => { const httpResponse = new HttpResponse(mockResponse); assert.equal(httpResponse.getStatusText(), 'OK'); }); }); describe('setStatus()', () => { it('should set the status', () => { const httpResponse = new HttpResponse(mockResponse); assert.equal(httpResponse.getStatus(), '200 OK'); httpResponse.setStatus(400, 'Bad Request'); assert.equal(httpResponse.getStatus(), '400 Bad Request'); }); it('should throw an error if no code specified', () => { const httpResponse = new HttpResponse(mockResponse); assert.equal(httpResponse.getStatus(), '200 OK'); assert.throws(() => httpResponse.setStatus(void 0, 'Bad Request'), /Specify a status `code`/); }); it('should throw an error if the code is not an integer', () => { const httpResponse = new HttpResponse(mockResponse); assert.equal(httpResponse.getStatus(), '200 OK'); assert.throws(() => httpResponse.setStatus('200', 'Bad Request'), /The status `code` must be an integer/); }); it('should throw an error if no text specified', () => { const httpResponse = new HttpResponse(mockResponse); assert.equal(httpResponse.getStatus(), '200 OK'); assert.throws(() => httpResponse.setStatus(400, void 0), /Specify a status `text`/); }); it('should throw an error if specified text is not a string', () => { const httpResponse = new HttpResponse(mockResponse); assert.equal(httpResponse.getStatus(), '200 OK'); assert.throws(() => httpResponse.setStatus(400, true), /The status `text` must be a string/); }); }); describe('hasHeader()', () => { it('should determine if header has been set', () => { const _mockResponse = Object.assign({headers: {'Content-Type': 'test'}}, mockResponse); const httpResponse = new HttpResponse(_mockResponse); assert.ok(httpResponse.hasHeader('Content-Type')); }); it('should return false if header has not been set', () => { const httpResponse = new HttpResponse(mockResponse); assert.equal(httpResponse.hasHeader('Content-Type'), false); }); it('should throw an error if no header `name` specified', () => { const httpResponse = new HttpResponse(mockResponse); assert.throws(httpResponse.hasHeader, /Specify a header `name`/); }); it('should throw an error if specified header `name` is not a string', () => { const httpResponse = new HttpResponse(mockResponse); assert.throws(() => httpResponse.hasHeader({}), /The header `name` must be a string/); }); }); describe('getHeader()', () => { it('should return the header with the specified `name`', () => { const _mockResponse = Object.assign({headers: {'Content-Type': ['test']}}, mockResponse); const httpResponse = new HttpResponse(_mockResponse); assert.equal(httpResponse.getHeader('Content-Type'), 'test'); }); it('should return the default value if specified header does not exist', () => { const _mockResponse = Object.assign({headers: {}}, mockResponse); const httpResponse = new HttpResponse(_mockResponse); const defaultValue = 'text/plain'; assert.equal(httpResponse.getHeader('Content-Type', defaultValue), defaultValue); }); it('should throw an error if no header `name` specified', () => { const httpResponse = new HttpResponse(mockResponse); assert.throws(httpResponse.getHeader, /Specify a header `name`/); }); it('should throw an error if specified header `name` is not a string', () => { const httpResponse = new HttpResponse(mockResponse); assert.throws(() => httpResponse.getHeader({}), /The header `name` must be a string/); }); }); describe('getHeaders()', () => { it('should return all headers', () => { const headers = {'Content-Type': ['test']}; const _mockResponse = Object.assign({headers}, mockResponse); const httpResponse = new HttpResponse(_mockResponse); assert.deepEqual(httpResponse.getHeaders(), {'Content-Type': 'test'}); }); it('should return an empty set of headers when none are set', () => { const httpResponse = new HttpResponse(mockResponse); assert.deepEqual(httpResponse.getHeaders(), {}); }); }); describe('setHeader()', () => { it('should set a header in the httpResponse', () => { const httpResponse = new HttpResponse(mockResponse); httpResponse.setHeader('Content-Type', 'test'); assert.ok(httpResponse.hasHeader('Content-Type')); assert.equal(httpResponse.getHeader('Content-Type'), 'test'); }); it('should throw an error if a header `name` is not defined', () => { const httpResponse = new HttpResponse(mockResponse); assert.throws(() => httpResponse.setHeader(void 0, 'test'), /Specify a header `name`/); }); it('should throw an error if a header `name` is not a string', () => { const httpResponse = new HttpResponse(mockResponse); assert.throws(() => httpResponse.setHeader(false, 'test'), /The header `name` must be a string/); }); it('should throw an error if a header `value` is not defined', () => { const httpResponse = new HttpResponse(mockResponse); assert.throws(() => httpResponse.setHeader('Content-Type', void 0), /Specify a header `value`/); }); it('should throw an error if a header `name` is not a string', () => { const httpResponse = new HttpResponse(mockResponse); assert.throws(() => httpResponse.setHeader('Content-Type', []), /The header `value` must be a string/); }); it('should register a new header as an array with 1 value', () => { const httpResponse = new HttpResponse(mockResponse); httpResponse.setHeader('X-Test', 'test'); assert.ok(httpResponse.hasHeader('X-Test')); assert.deepEqual(httpResponse.getHeaderArray('X-Test'), ['test']); }); }); describe('hasBody()', () => { it('should determine if the httpResponse has a `body`', () => { const _mockResponse = Object.assign({body: ' '}, mockResponse); const httpResponse = new HttpResponse(_mockResponse); assert.ok(httpResponse.hasBody()); }); it('should return false if the esponse do not have a `body`', () => { const httpResponse = new HttpResponse(mockResponse); assert.equal(httpResponse.hasBody(), false); }); }); describe('getBody()', () => { it('should return the content of the httpResponse `body`', () => { const body = ' '; const _mockResponse = Object.assign({body}, mockResponse); const httpResponse = new HttpResponse(_mockResponse); assert.equal(httpResponse.getBody(), body); }); }); describe('setBody()', () => { it('should set the content of the httpResponse `body`', () => { const body = ' '; const httpResponse = new HttpResponse(mockResponse); httpResponse.setBody(body); assert.equal(httpResponse.getBody(), body); }); }); });
orestes/katana-sdk-node
sdk/http-response.test.js
JavaScript
mit
10,676
"use strict"; let datafire = require('datafire'); let openapi = require('./openapi.json'); module.exports = datafire.Integration.fromOpenAPI(openapi, "azure_sql_failoverdatabases");
DataFire/Integrations
integrations/generated/azure_sql_failoverdatabases/index.js
JavaScript
mit
181
package generated.zcsclient.mail; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for messagePartHitInfo complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="messagePartHitInfo"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="e" type="{urn:zimbraMail}emailInfo" minOccurs="0"/> * &lt;element name="su" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="sf" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="s" type="{http://www.w3.org/2001/XMLSchema}long" /> * &lt;attribute name="d" type="{http://www.w3.org/2001/XMLSchema}long" /> * &lt;attribute name="cid" type="{http://www.w3.org/2001/XMLSchema}int" /> * &lt;attribute name="mid" type="{http://www.w3.org/2001/XMLSchema}int" /> * &lt;attribute name="ct" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="part" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "messagePartHitInfo", propOrder = { "e", "su" }) public class testMessagePartHitInfo { protected testEmailInfo e; protected String su; @XmlAttribute(name = "id") protected String id; @XmlAttribute(name = "sf") protected String sf; @XmlAttribute(name = "s") protected Long s; @XmlAttribute(name = "d") protected Long d; @XmlAttribute(name = "cid") protected Integer cid; @XmlAttribute(name = "mid") protected Integer mid; @XmlAttribute(name = "ct") protected String ct; @XmlAttribute(name = "name") protected String name; @XmlAttribute(name = "part") protected String part; /** * Gets the value of the e property. * * @return * possible object is * {@link testEmailInfo } * */ public testEmailInfo getE() { return e; } /** * Sets the value of the e property. * * @param value * allowed object is * {@link testEmailInfo } * */ public void setE(testEmailInfo value) { this.e = value; } /** * Gets the value of the su property. * * @return * possible object is * {@link String } * */ public String getSu() { return su; } /** * Sets the value of the su property. * * @param value * allowed object is * {@link String } * */ public void setSu(String value) { this.su = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the sf property. * * @return * possible object is * {@link String } * */ public String getSf() { return sf; } /** * Sets the value of the sf property. * * @param value * allowed object is * {@link String } * */ public void setSf(String value) { this.sf = value; } /** * Gets the value of the s property. * * @return * possible object is * {@link Long } * */ public Long getS() { return s; } /** * Sets the value of the s property. * * @param value * allowed object is * {@link Long } * */ public void setS(Long value) { this.s = value; } /** * Gets the value of the d property. * * @return * possible object is * {@link Long } * */ public Long getD() { return d; } /** * Sets the value of the d property. * * @param value * allowed object is * {@link Long } * */ public void setD(Long value) { this.d = value; } /** * Gets the value of the cid property. * * @return * possible object is * {@link Integer } * */ public Integer getCid() { return cid; } /** * Sets the value of the cid property. * * @param value * allowed object is * {@link Integer } * */ public void setCid(Integer value) { this.cid = value; } /** * Gets the value of the mid property. * * @return * possible object is * {@link Integer } * */ public Integer getMid() { return mid; } /** * Sets the value of the mid property. * * @param value * allowed object is * {@link Integer } * */ public void setMid(Integer value) { this.mid = value; } /** * Gets the value of the ct property. * * @return * possible object is * {@link String } * */ public String getCt() { return ct; } /** * Sets the value of the ct property. * * @param value * allowed object is * {@link String } * */ public void setCt(String value) { this.ct = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the part property. * * @return * possible object is * {@link String } * */ public String getPart() { return part; } /** * Sets the value of the part property. * * @param value * allowed object is * {@link String } * */ public void setPart(String value) { this.part = value; } }
nico01f/z-pec
ZimbraSoap/src/wsdl-test/generated/zcsclient/mail/testMessagePartHitInfo.java
Java
mit
7,074
require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require "active_model/railtie" require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" require "sprockets/railtie" # require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module ClassroomLibrary 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
amjacobowitz/classroom-library
classroom-library/config/application.rb
Ruby
mit
1,224
/* * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved. * * 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. * */ /*jslint vars: true, plusplus: true, devel: true, node: true, nomen: true, indent: 4, maxerr: 50 */ /*global expect, describe, it, beforeEach, afterEach */ "use strict"; var ExtensionsDomain = require("../ExtensionManagerDomain"), fs = require("fs-extra"), async = require("async"), path = require("path"); var testFilesDirectory = path.join(path.dirname(module.filename), "..", // node "..", // extensibility "..", // src "..", // brackets "test", "spec", "extension-test-files"), installParent = path.join(path.dirname(module.filename), "extensions"), installDirectory = path.join(installParent, "good"), disabledDirectory = path.join(installParent, "disabled"); var basicValidExtension = path.join(testFilesDirectory, "basic-valid-extension.zip"), basicValidExtension2 = path.join(testFilesDirectory, "basic-valid-extension-2.0.zip"), missingMain = path.join(testFilesDirectory, "missing-main.zip"), oneLevelDown = path.join(testFilesDirectory, "one-level-extension-master.zip"), incompatibleVersion = path.join(testFilesDirectory, "incompatible-version.zip"), invalidZip = path.join(testFilesDirectory, "invalid-zip-file.zip"), missingPackageJSON = path.join(testFilesDirectory, "missing-package-json.zip"); describe("Package Installation", function () { var standardOptions = { disabledDirectory: disabledDirectory, apiVersion: "0.22.0" }; beforeEach(function (done) { fs.mkdirs(installDirectory, function (err) { fs.mkdirs(disabledDirectory, function (err) { done(); }); }); }); afterEach(function (done) { fs.remove(installParent, function (err) { done(); }); }); function checkPaths(pathsToCheck, callback) { var existsCalls = []; pathsToCheck.forEach(function (path) { existsCalls.push(function (callback) { fs.exists(path, async.apply(callback, null)); }); }); async.parallel(existsCalls, function (err, results) { expect(err).toBeNull(); results.forEach(function (result, num) { expect(result ? "" : pathsToCheck[num] + " does not exist").toEqual(""); }); callback(); }); } it("should validate the package", function (done) { ExtensionsDomain._cmdInstall(missingMain, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); var errors = result.errors; expect(errors.length).toEqual(1); done(); }); }); it("should work fine if all is well", function (done) { ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) { var extensionDirectory = path.join(installDirectory, "basic-valid-extension"); expect(err).toBeNull(); var errors = result.errors; expect(errors.length).toEqual(0); expect(result.metadata.name).toEqual("basic-valid-extension"); expect(result.name).toEqual("basic-valid-extension"); expect(result.installedTo).toEqual(extensionDirectory); var pathsToCheck = [ path.join(extensionDirectory, "package.json"), path.join(extensionDirectory, "main.js") ]; checkPaths(pathsToCheck, done); }); }); // This is mildly redundant. the validation check should catch this. // But, I wanted to be sure that the install function doesn't try to // do anything with the file before validation. it("should fail for missing package", function (done) { ExtensionsDomain._cmdInstall(path.join(testFilesDirectory, "NOT A PACKAGE"), installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); var errors = result.errors; expect(errors.length).toEqual(1); expect(errors[0][0]).toEqual("NOT_FOUND_ERR"); done(); }); }); it("should install to the disabled directory if it's already installed", function (done) { ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); expect(result.disabledReason).toBeNull(); ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); expect(result.disabledReason).toEqual("ALREADY_INSTALLED"); var extensionDirectory = path.join(disabledDirectory, "basic-valid-extension"); var pathsToCheck = [ path.join(extensionDirectory, "package.json"), path.join(extensionDirectory, "main.js") ]; checkPaths(pathsToCheck, done); }); }); }); it("should yield an error if there's no disabled directory set", function (done) { ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, { apiVersion: "0.22.0" }, function (err, result) { expect(err.message).toEqual("MISSING_REQUIRED_OPTIONS"); done(); }); }); it("should yield an error if there's no apiVersion set", function (done) { ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, { disabledDirectory: disabledDirectory }, function (err, result) { expect(err.message).toEqual("MISSING_REQUIRED_OPTIONS"); done(); }); }); it("should overwrite the disabled directory copy if there's already one", function (done) { ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); expect(result.disabledReason).toBeNull(); ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); expect(result.disabledReason).toEqual("ALREADY_INSTALLED"); ExtensionsDomain._cmdInstall(basicValidExtension2, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); expect(result.disabledReason).toEqual("ALREADY_INSTALLED"); var extensionDirectory = path.join(disabledDirectory, "basic-valid-extension"); fs.readJson(path.join(extensionDirectory, "package.json"), function (err, packageObj) { expect(err).toBeNull(); expect(packageObj.version).toEqual("2.0.0"); done(); }); }); }); }); }); it("should derive the name from the zip if there's no package.json", function (done) { ExtensionsDomain._cmdInstall(missingPackageJSON, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); expect(result.disabledReason).toBeNull(); var extensionDirectory = path.join(installDirectory, "missing-package-json"); var pathsToCheck = [ path.join(extensionDirectory, "main.js") ]; checkPaths(pathsToCheck, done); }); }); it("should install with the common prefix removed", function (done) { ExtensionsDomain._cmdInstall(oneLevelDown, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); var extensionDirectory = path.join(installDirectory, "one-level-extension"); var pathsToCheck = [ path.join(extensionDirectory, "main.js"), path.join(extensionDirectory, "package.json"), path.join(extensionDirectory, "lib", "foo.js") ]; checkPaths(pathsToCheck, done); }); }); it("should disable extensions that are not compatible with the current Brackets API", function (done) { ExtensionsDomain._cmdInstall(incompatibleVersion, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); expect(result.disabledReason).toEqual("API_NOT_COMPATIBLE"); var extensionDirectory = path.join(disabledDirectory, "incompatible-version"); var pathsToCheck = [ path.join(extensionDirectory, "main.js"), path.join(extensionDirectory, "package.json") ]; checkPaths(pathsToCheck, done); }); }); it("should not have trouble with invalid zip files", function (done) { ExtensionsDomain._cmdInstall(invalidZip, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); expect(result.errors.length).toEqual(1); done(); }); }); });
L0g1k/quickfire-old
src/extensibility/node/spec/Installation.spec.js
JavaScript
mit
10,734
#include "stdafx.h" #include "Renderer.h" #include "RenderMethod_PhongPoint_CG.h" RenderMethod_PhongPoint_CG::RenderMethod_PhongPoint_CG(class Renderer *r) { ASSERT(r, "Null pointer: r"); renderer = r; useCG = true; } bool RenderMethod_PhongPoint_CG::isSupported() const { return areShadersAvailable(); } void RenderMethod_PhongPoint_CG::setupShader(CGcontext &cg, CGprofile &_cgVertexProfile, CGprofile &_cgFragmentProfile) { RenderMethod::setupShader(cg, _cgVertexProfile, _cgFragmentProfile); createVertexProgram(cg, FileName("data/shaders/cg/phong_point.vp.cg")); createFragmentProgram(cg, FileName("data/shaders/cg/phong_point.fp.cg")); // Vertex program parameters cgMVP = getVertexProgramParameter (cg, "MVP"); cgView = getVertexProgramParameter (cg, "View"); cgLightPos = getVertexProgramParameter (cg, "LightPos"); cgCameraPos = getVertexProgramParameter (cg, "CameraPos"); cgTexture = getFragmentProgramParameter(cg, "tex0"); cgKa = getFragmentProgramParameter(cg, "Ka"); cgKd = getFragmentProgramParameter(cg, "Kd"); cgKs = getFragmentProgramParameter(cg, "Ks"); cgShininess = getFragmentProgramParameter(cg, "shininess"); cgkC = getFragmentProgramParameter(cg, "kC"); cgkL = getFragmentProgramParameter(cg, "kL"); cgkQ = getFragmentProgramParameter(cg, "kQ"); } void RenderMethod_PhongPoint_CG::renderPass(RENDER_PASS pass) { switch (pass) { case OPAQUE_PASS: pass_opaque(); break; default: return; } } void RenderMethod_PhongPoint_CG::pass_opaque() { CHECK_GL_ERROR(); // Setup state glPushAttrib(GL_ALL_ATTRIB_BITS); glColor4fv(white); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); glEnable(GL_TEXTURE_2D); // Setup client state glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); // Render the geometry chunks renderChunks(); // Restore client state glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); // Restore settings glPopAttrib(); CHECK_GL_ERROR(); } void RenderMethod_PhongPoint_CG::setShaderData(const GeometryChunk &gc) { const Renderer::Light &light0 = renderer->getLight(); ASSERT(light0.type == Renderer::Light::POINT, "point lights only pls"); mat4 MI = (gc.transformation).inverse(); // world -> object projection // Set the position of the light (in object-space) vec3 LightPosObj = MI.transformVector(light0.position); cgGLSetParameter3fv(cgLightPos, LightPosObj); // Set the position of the camera (in object-space) vec3 CameraPosWld = renderer->getCamera().getPosition(); vec3 CameraPosObj = MI.transformVector(CameraPosWld); cgGLSetParameter3fv(cgCameraPos, CameraPosObj); // Set the light properties cgGLSetParameter1fv(cgkC, &light0.kC); cgGLSetParameter1fv(cgkL, &light0.kL); cgGLSetParameter1fv(cgkQ, &light0.kQ); // Set the material properties cgGLSetParameter4fv(cgKa, gc.material.Ka); cgGLSetParameter4fv(cgKd, gc.material.Kd); cgGLSetParameter4fv(cgKs, gc.material.Ks); cgGLSetParameter1fv(cgShininess, &gc.material.shininess); // Everything else cgGLSetStateMatrixParameter(cgMVP, CG_GL_MODELVIEW_PROJECTION_MATRIX, CG_GL_MATRIX_IDENTITY); cgGLSetStateMatrixParameter(cgView, CG_GL_MODELVIEW_MATRIX, CG_GL_MATRIX_IDENTITY); }
foxostro/CheeseTesseract
src/RenderMethod_PhongPoint_CG.cpp
C++
mit
3,567
class AddOriginalMd5ChecksumToVideos < ActiveRecord::Migration def change add_column :videos, :original_md5_checksum, :string, :limit => 40 end end
pr0d1r2/myvod
db/migrate/20130824090308_add_original_md5_checksum_to_videos.rb
Ruby
mit
156
import ReactIdSwiper from './ReactIdSwiper'; // Types export { ReactIdSwiperProps, ReactIdSwiperRenderProps, SelectableElement, SwiperInstance, WrappedElementType, ReactIdSwiperChildren, SwiperModuleName, SwiperRefNode } from './types'; // React-id-swiper export default ReactIdSwiper;
kidjp85/react-id-swiper
src/index.ts
TypeScript
mit
304
# -*- coding: utf-8 -*- # @Author: karthik # @Date: 2016-12-10 21:40:07 # @Last Modified by: chandan # @Last Modified time: 2016-12-11 12:55:27 from models.portfolio import Portfolio from models.company import Company from models.position import Position import tenjin from tenjin.helpers import * import wikipedia import matplotlib.pyplot as plt from data_helpers import * from stock_data import * import BeautifulSoup as bs import urllib2 import re from datetime import date as dt engine = tenjin.Engine(path=['templates']) # info fetch handler def send_info_handler(bot, update, args): args = list(parse_args(args)) if len(args) == 0 or "portfolio" in [arg.lower() for arg in args] : send_portfolio_info(bot, update) else: info_companies = get_companies(args) send_companies_info(bot, update, info_companies) # get portfolio function def send_portfolio_info(bot, update): print "Userid: %d requested portfolio information" %(update.message.chat_id) context = { 'positions': Portfolio.instance.positions, 'wallet_value': Portfolio.instance.wallet_value, } html_str = engine.render('portfolio_info.pyhtml', context) bot.sendMessage(parse_mode="HTML", chat_id=update.message.chat_id, text=html_str) # get companies information def send_companies_info(bot, update, companies): print "Userid: requested information for following companies %s" %','.join([c.name for c in companies]) for company in companies: context = { 'company': company, 'current_price': get_current_price(company), 'description': wikipedia.summary(company.name.split()[0], sentences=2) } wiki_page = wikipedia.page(company.name.split()[0]) html_page = urllib2.urlopen(wiki_page.url) soup = bs.BeautifulSoup(html_page) img_url = 'http:' + soup.find('td', { "class" : "logo" }).find('img')['src'] bot.sendPhoto(chat_id=update.message.chat_id, photo=img_url) html_str = engine.render('company_template.pyhtml', context) bot.sendMessage(parse_mode="HTML", chat_id=update.message.chat_id, text=html_str) symbols = [c.symbol for c in companies] if len(symbols) >= 2: symbol_string = ", ".join(symbols[:-1]) + " and " + symbols[-1] else: symbol_string = symbols[0] last_n_days = 10 if len(companies) < 4: create_graph(companies, last_n_days) history_text = ''' Here's the price history for {} for the last {} days '''.format(symbol_string, last_n_days) bot.sendMessage(chat_id=update.message.chat_id, text=history_text) bot.sendPhoto(chat_id=update.message.chat_id, photo=open("plots/temp.png",'rb')) def create_graph(companies, timedel): fig, ax = plt.subplots() for company in companies: dates, lookback_prices = get_lookback_prices(company, timedel) # dates = [i.strftime('%d/%m') for i in dates] h = ax.plot(dates, lookback_prices, label=company.symbol) ax.legend() plt.xticks(rotation=45) plt.savefig('plots/temp.png')
coders-creed/botathon
src/info/fetch_info.py
Python
mit
2,889
using System; using System.Collections.Generic; using System.Html; namespace wwtlib { public class PlotTile : Tile { bool topDown = true; protected PositionTexture[] bounds; protected bool backslash = false; List<PositionTexture> vertexList = null; List<Triangle>[] childTriangleList = null; protected float[] demArray; protected void ComputeBoundingSphere() { InitializeGrids(); TopLeft = bounds[0 + 3 * 0].Position.Copy(); BottomRight = bounds[2 + 3 * 2].Position.Copy(); TopRight = bounds[2 + 3 * 0].Position.Copy(); BottomLeft = bounds[0 + 3 * 2].Position.Copy(); CalcSphere(); } public override void RenderPart(RenderContext renderContext, int part, double opacity, bool combine) { if (renderContext.gl != null) { //todo draw in WebGL } else { if (part == 0) { foreach(Star star in stars) { double radDec = 25 / Math.Pow(1.6, star.Magnitude); Planets.DrawPointPlanet(renderContext, star.Position, radDec, star.Col, false); } } } } WebFile webFile; public override void RequestImage() { if (!Downloading && !ReadyToRender) { Downloading = true; webFile = new WebFile(Util.GetProxiedUrl(this.URL)); webFile.OnStateChange = FileStateChange; webFile.Send(); } } public void FileStateChange() { if(webFile.State == StateType.Error) { Downloading = false; ReadyToRender = false; errored = true; RequestPending = false; TileCache.RemoveFromQueue(this.Key, true); } else if(webFile.State == StateType.Received) { texReady = true; Downloading = false; errored = false; ReadyToRender = texReady && (DemReady || !demTile); RequestPending = false; TileCache.RemoveFromQueue(this.Key, true); LoadData(webFile.GetText()); } } List<Star> stars = new List<Star>(); private void LoadData(string data) { string[] rows = data.Replace("\r\n","\n").Split("\n"); bool firstRow = true; PointType type = PointType.Move; Star star = null; foreach (string row in rows) { if (firstRow) { firstRow = false; continue; } if (row.Trim().Length > 5) { star = new Star(row); star.Position = Coordinates.RADecTo3dAu(star.RA, star.Dec, 1); stars.Add(star); } } } public override bool IsPointInTile(double lat, double lng) { if (Level == 0) { return true; } if (Level == 1) { if ((lng >= 0 && lng <= 90) && (tileX == 0 && tileY == 1)) { return true; } if ((lng > 90 && lng <= 180) && (tileX == 1 && tileY == 1)) { return true; } if ((lng < 0 && lng >= -90) && (tileX == 0 && tileY == 0)) { return true; } if ((lng < -90 && lng >= -180) && (tileX == 1 && tileY == 0)) { return true; } return false; } if (!this.DemReady || this.DemData == null) { return false; } Vector3d testPoint = Coordinates.GeoTo3dDouble(-lat, lng); bool top = IsLeftOfHalfSpace(TopLeft.Copy(), TopRight.Copy(), testPoint); bool right = IsLeftOfHalfSpace(TopRight.Copy(), BottomRight.Copy(), testPoint); bool bottom = IsLeftOfHalfSpace(BottomRight.Copy(), BottomLeft.Copy(), testPoint); bool left = IsLeftOfHalfSpace(BottomLeft.Copy(), TopLeft.Copy(), testPoint); if (top && right && bottom && left) { // showSelected = true; return true; } return false; ; } private bool IsLeftOfHalfSpace(Vector3d pntA, Vector3d pntB, Vector3d pntTest) { pntA.Normalize(); pntB.Normalize(); Vector3d cross = Vector3d.Cross(pntA, pntB); double dot = Vector3d.Dot(cross, pntTest); return dot < 0; } private void InitializeGrids() { vertexList = new List<PositionTexture>(); childTriangleList = new List<Triangle>[4]; childTriangleList[0] = new List<Triangle>(); childTriangleList[1] = new List<Triangle>(); childTriangleList[2] = new List<Triangle>(); childTriangleList[3] = new List<Triangle>(); bounds = new PositionTexture[9]; if (Level > 0) { // Set in constuctor now //ToastTile parent = (ToastTile)TileCache.GetTile(level - 1, x / 2, y / 2, dataset, null); if (Parent == null) { Parent = TileCache.GetTile(Level - 1, tileX / 2, tileY / 2, dataset, null); } PlotTile parent = (PlotTile)Parent; int xIndex = tileX % 2; int yIndex = tileY % 2; if (Level > 1) { backslash = parent.backslash; } else { backslash = xIndex == 1 ^ yIndex == 1; } bounds[0 + 3 * 0] = parent.bounds[xIndex + 3 * yIndex].Copy(); bounds[1 + 3 * 0] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * yIndex]); bounds[2 + 3 * 0] = parent.bounds[xIndex + 1 + 3 * yIndex].Copy(); bounds[0 + 3 * 1] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]); if (backslash) { bounds[1 + 3 * 1] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); } else { bounds[1 + 3 * 1] = Midpoint(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]); } bounds[2 + 3 * 1] = Midpoint(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); bounds[0 + 3 * 2] = parent.bounds[xIndex + 3 * (yIndex + 1)].Copy(); bounds[1 + 3 * 2] = Midpoint(parent.bounds[xIndex + 3 * (yIndex + 1)], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); bounds[2 + 3 * 2] = parent.bounds[xIndex + 1 + 3 * (yIndex + 1)].Copy(); bounds[0 + 3 * 0].Tu = 0*uvMultiple; bounds[0 + 3 * 0].Tv = 0 * uvMultiple; bounds[1 + 3 * 0].Tu = .5f * uvMultiple; bounds[1 + 3 * 0].Tv = 0 * uvMultiple; bounds[2 + 3 * 0].Tu = 1 * uvMultiple; bounds[2 + 3 * 0].Tv = 0 * uvMultiple; bounds[0 + 3 * 1].Tu = 0 * uvMultiple; bounds[0 + 3 * 1].Tv = .5f * uvMultiple; bounds[1 + 3 * 1].Tu = .5f * uvMultiple; bounds[1 + 3 * 1].Tv = .5f * uvMultiple; bounds[2 + 3 * 1].Tu = 1 * uvMultiple; bounds[2 + 3 * 1].Tv = .5f * uvMultiple; bounds[0 + 3 * 2].Tu = 0 * uvMultiple; bounds[0 + 3 * 2].Tv = 1 * uvMultiple; bounds[1 + 3 * 2].Tu = .5f * uvMultiple; bounds[1 + 3 * 2].Tv = 1 * uvMultiple; bounds[2 + 3 * 2].Tu = 1 * uvMultiple; bounds[2 + 3 * 2].Tv = 1 * uvMultiple; } else { bounds[0 + 3 * 0] = PositionTexture.Create(0, -1, 0, 0, 0); bounds[1 + 3 * 0] = PositionTexture.Create(0, 0, 1, .5f, 0); bounds[2 + 3 * 0] = PositionTexture.Create(0, -1, 0, 1, 0); bounds[0 + 3 * 1] = PositionTexture.Create(-1, 0, 0, 0, .5f); bounds[1 + 3 * 1] = PositionTexture.Create(0, 1, 0, .5f, .5f); bounds[2 + 3 * 1] = PositionTexture.Create(1, 0, 0, 1, .5f); bounds[0 + 3 * 2] = PositionTexture.Create(0, -1, 0, 0, 1); bounds[1 + 3 * 2] = PositionTexture.Create(0, 0, -1, .5f, 1); bounds[2 + 3 * 2] = PositionTexture.Create(0, -1, 0, 1, 1); // Setup default matrix of points. } } private PositionTexture Midpoint(PositionTexture positionNormalTextured, PositionTexture positionNormalTextured_2) { Vector3d a1 = Vector3d.Lerp(positionNormalTextured.Position, positionNormalTextured_2.Position, .5f); Vector2d a1uv = Vector2d.Lerp(Vector2d.Create(positionNormalTextured.Tu, positionNormalTextured.Tv), Vector2d.Create(positionNormalTextured_2.Tu, positionNormalTextured_2.Tv), .5f); a1.Normalize(); return PositionTexture.CreatePos(a1, a1uv.X, a1uv.Y); } int subDivisionLevel = 4; bool subDivided = false; public override bool CreateGeometry(RenderContext renderContext) { if (GeometryCreated) { return true; } GeometryCreated = true; base.CreateGeometry(renderContext); return true; } public PlotTile() { } public static PlotTile Create(int level, int xc, int yc, Imageset dataset, Tile parent) { PlotTile temp = new PlotTile(); temp.Parent = parent; temp.Level = level; temp.tileX = xc; temp.tileY = yc; temp.dataset = dataset; temp.topDown = !dataset.BottomsUp; if (temp.tileX != (int)xc) { Script.Literal("alert('bad')"); } //temp.ComputeQuadrant(); if (dataset.MeanRadius != 0) { temp.DemScaleFactor = dataset.MeanRadius; } else { if (dataset.DataSetType == ImageSetType.Earth) { temp.DemScaleFactor = 6371000; } else { temp.DemScaleFactor = 3396010; } } temp.ComputeBoundingSphere(); return temp; } public override void CleanUp(bool removeFromParent) { base.CleanUp(removeFromParent); if (vertexList != null) { vertexList = null; } if (childTriangleList != null) { childTriangleList = null; } subDivided = false; demArray = null; } } }
juoni/wwt-web-client
HTML5SDK/wwtlib/PlotTile.cs
C#
mit
11,749
<?php /** * This file is part of the browscap-json-cache package. * * (c) Thomas Mueller <mimmi20@live.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types = 1); namespace Browscap\Cache; use BrowscapPHP\Cache\BrowscapCacheInterface; use WurflCache\Adapter\AdapterInterface; /** * a cache proxy to be able to use the cache adapters provided by the WurflCache package * * @category Browscap-PHP * * @copyright Copyright (c) 1998-2014 Browser Capabilities Project * * @version 3.0 * * @license http://www.opensource.org/licenses/MIT MIT License * * @see https://github.com/browscap/browscap-php/ */ final class JsonCache implements BrowscapCacheInterface { /** * The cache livetime in seconds. * * @var int */ public const CACHE_LIVETIME = 315360000; // ~10 years (60 * 60 * 24 * 365 * 10) /** * Path to the cache directory * * @var \WurflCache\Adapter\AdapterInterface */ private $cache; /** * Detected browscap version (read from INI file) * * @var int */ private $version; /** * Release date of the Browscap data (read from INI file) * * @var string */ private $releaseDate; /** * Type of the Browscap data (read from INI file) * * @var string */ private $type; /** * Constructor class, checks for the existence of (and loads) the cache and * if needed updated the definitions * * @param \WurflCache\Adapter\AdapterInterface $adapter * @param int $updateInterval */ public function __construct(AdapterInterface $adapter, $updateInterval = self::CACHE_LIVETIME) { $this->cache = $adapter; $this->cache->setExpiration($updateInterval); } /** * Gets the version of the Browscap data * * @return int|null */ public function getVersion(): ?int { if (null === $this->version) { $success = true; $version = $this->getItem('browscap.version', false, $success); if (null !== $version && $success) { $this->version = (int) $version; } } return $this->version; } /** * Gets the release date of the Browscap data * * @return string */ public function getReleaseDate(): string { if (null === $this->releaseDate) { $success = true; $releaseDate = $this->getItem('browscap.releaseDate', false, $success); if (null !== $releaseDate && $success) { $this->releaseDate = $releaseDate; } } return $this->releaseDate; } /** * Gets the type of the Browscap data * * @return string|null */ public function getType(): ?string { if (null === $this->type) { $success = true; $type = $this->getItem('browscap.type', false, $success); if (null !== $type && $success) { $this->type = $type; } } return $this->type; } /** * Get an item. * * @param string $cacheId * @param bool $withVersion * @param bool|null $success * * @return mixed Data on success, null on failure */ public function getItem(string $cacheId, bool $withVersion = true, ?bool &$success = null) { if ($withVersion) { $cacheId .= '.' . $this->getVersion(); } if (!$this->cache->hasItem($cacheId)) { $success = false; return null; } $success = null; $data = $this->cache->getItem($cacheId, $success); if (!$success) { $success = false; return null; } if (!property_exists($data, 'content')) { $success = false; return null; } $success = true; return $data->content; } /** * save the content into an php file * * @param string $cacheId The cache id * @param mixed $content The content to store * @param bool $withVersion * * @return bool whether the file was correctly written to the disk */ public function setItem(string $cacheId, $content, bool $withVersion = true): bool { $data = new \stdClass(); // Get the whole PHP code $data->content = $content; if ($withVersion) { $cacheId .= '.' . $this->getVersion(); } // Save and return return $this->cache->setItem($cacheId, $data); } /** * Test if an item exists. * * @param string $cacheId * @param bool $withVersion * * @return bool */ public function hasItem(string $cacheId, bool $withVersion = true): bool { if ($withVersion) { $cacheId .= '.' . $this->getVersion(); } return $this->cache->hasItem($cacheId); } /** * Remove an item. * * @param string $cacheId * @param bool $withVersion * * @return bool */ public function removeItem(string $cacheId, bool $withVersion = true): bool { if ($withVersion) { $cacheId .= '.' . $this->getVersion(); } return $this->cache->removeItem($cacheId); } /** * Flush the whole storage * * @return bool */ public function flush(): bool { return $this->cache->flush(); } }
mimmi20/browscap-json-cache
src/JsonCache.php
PHP
mit
5,684
(function () { "use strict"; require('futures/forEachAsync'); var fs = require('fs'), crypto = require('crypto'), path = require('path'), exec = require('child_process').exec, mime = require('mime'), FileStat = require('filestat'), dbaccess = require('../dbaccess'), utils = require('../utils'), hashAlgo = "md5"; function readFile(filePath, callback) { var readStream, hash = crypto.createHash(hashAlgo); readStream = fs.createReadStream(filePath); readStream.on('data', function (data) { hash.update(data); }); readStream.on('error', function (err) { console.log("Read Error: " + err.toString()); readStream.destroy(); fs.unlink(filePath); callback(err); }); readStream.on('end', function () { callback(null, hash.digest("hex")); }); } function saveToFs(md5, filePath, callback) { var newPath = utils.hashToPath(md5); path.exists(newPath, function (exists) { if (exists) { fs.move(filePath, newPath, function (err) { callback(err, newPath); }); return; } exec('mkdir -p ' + newPath, function (err, stdout, stderr) { var tError; if (err || stderr) { console.log("Err: " + (err ? err : "none")); console.log("stderr: " + (stderr ? stderr : "none")); tError = {error: err, stderr: stderr, stdout: stdout}; return callback(tError, newPath); } console.log("stdout: " + (stdout ? stdout : "none")); fs.move(filePath, newPath, function (moveErr) { callback(moveErr, newPath); }); }); }); } function addKeysToFileStats(fieldNames, stats) { var fileStats = []; stats.forEach(function (item) { var fileStat = new FileStat(); item.forEach(function (fieldValue, i) { fileStat[fieldNames[i]] = fieldValue; }); if (fileStat.path) { fileStat.type = mime.lookup(fileStat.path); } fileStats.push(fileStat); }); return fileStats; } function importFile(fileStat, tmpFile, username, callback) { var oldPath; oldPath = tmpFile.path; readFile(oldPath, function (err, md5) { if (err) { fileStat.err = err; callback(err, fileStat); return; } // if we have an md5sum and they don't match, abandon ship if (fileStat.md5 && fileStat.md5 !== md5) { callback("MD5 sums don't match"); return; } fileStat.md5 = md5; fileStat.genTmd5(function (error, tmd5) { if (!error) { fileStat.tmd5 = tmd5; saveToFs(fileStat.md5, oldPath, function (fserr) { if (fserr) { // ignoring possible unlink error fs.unlink(oldPath); fileStat.err = "File did not save"; } else { dbaccess.put(fileStat, username); } callback(fserr, fileStat); }); } }); }); } function handleUpload(req, res, next) { if (!req.form) { return next(); } req.form.complete(function (err, fields, files) { var fileStats, bFirst; fields.statsHeader = JSON.parse(fields.statsHeader); fields.stats = JSON.parse(fields.stats); fileStats = addKeysToFileStats(fields.statsHeader, fields.stats); dbaccess.createViews(req.remoteUser, fileStats); res.writeHead(200, {'Content-Type': 'application/json'}); // response as array res.write("["); bFirst = true; function handleFileStat(next, fileStat) { // this callback is synchronous fileStat.checkMd5(function (qmd5Error, qmd5) { function finishReq(err) { console.log(fileStat); fileStat.err = err; // we only want to add a comma after the first one if (!bFirst) { res.write(","); } bFirst = false; res.write(JSON.stringify(fileStat)); return next(); } if (qmd5Error) { return finishReq(qmd5Error); } importFile(fileStat, files[qmd5], req.remoteUser, finishReq); }); } fileStats.forEachAsync(handleFileStat).then(function () { // end response array res.end("]"); }); }); } module.exports = handleUpload; }());
beatgammit/node-filesync
server/lib/routes/upload.js
JavaScript
mit
3,981
#!/usr/bin/python from typing import List, Optional """ 16. 3Sum Closest https://leetcode.com/problems/3sum-closest/ """ def bsearch(nums, left, right, res, i, j, target): while left <= right: middle = (left + right) // 2 candidate = nums[i] + nums[j] + nums[middle] if res is None or abs(candidate - target) < abs(res - target): res = candidate if candidate == target: return res elif candidate > target: right = middle - 1 else: left = middle + 1 return res class Solution: def threeSumClosest(self, nums: List[int], target: int) -> Optional[int]: res = None nums = sorted(nums) for i in range(len(nums)): for j in range(i + 1, len(nums)): res = bsearch(nums, j + 1, len(nums) - 1, res, i, j, target) return res def main(): sol = Solution() print(sol.threeSumClosest([-111, -111, 3, 6, 7, 16, 17, 18, 19], 13)) return 0 if __name__ == '__main__': raise SystemExit(main())
pisskidney/leetcode
medium/16.py
Python
mit
1,070
package bits; /** * Created by krzysztofkaczor on 3/10/15. */ public class ExclusiveOrOperator implements BinaryOperator { @Override public BitArray combine(BitArray operand1, BitArray operand2) { if(operand1.size() != operand2.size()) { throw new IllegalArgumentException("ExclusiveOrOperator operands must have same size"); } int size = operand1.size(); BitArray result = new BitArray(size); for (int i = 0;i < size;i++) { boolean a = operand1.get(i); boolean b = operand2.get(i); result.set(i, a != b ); } return result; } }
krzkaczor/IDEA
src/main/java/bits/ExclusiveOrOperator.java
Java
mit
651
/*"use strict"; var expect = require("expect.js"), ShellController = require("../lib/shell-controller"), testView = require("./test-shell-view"); describe("ShellController", function() { var ctrl; it("is defined", function() { expect(ShellController).to.be.an("function"); }); describe("constructor", function() { before(function() { ctrl = new ShellController(testView); }); it("create an object", function() { expect(ctrl).to.be.an("object"); }); }); describe("on command event", function() { before(function(done) { ctrl.events.on("commandExecuted", done); testView.invokeCommand("ls test/files --color"); }); after(function() { testView.reset(); }); it("write commands output to view", function() { var expected = " <span style=\'color:rgba(170,170,170,255)\'>1.txt<br> 2.txt<br><br><br></span>"; expect(testView.content).to.be.equal(expected); }); }); describe("findCommandRunner", function() { var runner; before(function(done) { ctrl.findCommandRunner("ls test/files", function(cmdRunner) { runner = cmdRunner; done(); }); }); it("return a command runner", function() { expect(runner.run).to.be.a("function"); }); }); });*/
parroit/shell-js
test/shell-controller_test.js
JavaScript
mit
1,229
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); // Database var mongo = require('mongodb'); var monk = require('monk'); var db = monk('localhost:27017/mydb'); var index = require('./routes/index'); var buyer = require('./routes/buyer'); var seller = require('./routes/seller'); var products = require('./routes/products'); var app = express(); const ObjectID = mongo.ObjectID; // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.engine('html', require('ejs').renderFile); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // Make our db accessible to our router app.use(function(req,res,next){ req.db = db; req.ObjectID = ObjectID; next(); }); app.use('/', index); app.use('/buyer', buyer); app.use('/seller', seller); app.use('/products', products); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error.html', err); }); module.exports = app;
imRishabhGupta/smart-kart
app.js
JavaScript
mit
1,740
# Smallest Integer # I worked on this challenge [by myself, with: ]. # smallest_integer is a method that takes an array of integers as its input # and returns the smallest integer in the array # # +list_of_nums+ is an array of integers # smallest_integer(list_of_nums) should return the smallest integer in +list_of_nums+ # # If +list_of_nums+ is empty the method should return nil # Your Solution Below def smallest_integer(list_of_nums) if list_of_nums.empty? return nil else list_of_nums.sort! return list_of_nums[0] end end
NoahHeinrich/phase-0
week-4/smallest-integer/my_solution.rb
Ruby
mit
548
FactoryGirl.define do factory :user do provider 'trello' uid 'trello-special-uid' full_name 'Dennis Martinez' nickname 'dennmart' oauth_token 'trello-token' trait :admin do admin true end end end
dennmart/echo_for_trello
spec/factories/users.rb
Ruby
mit
235
from multiprocessing import Pool import os, time, random def long_time_task(name): print 'Run task %s (%s)...' % (name, os.getpid()) start = time.time() time.sleep(random.random() * 3) end = time.time() print 'Task %s runs %0.2f seconds.' % (name, (end - start)) if __name__ == '__main__': print 'Parent process %s.' % os.getpid() p = Pool() for i in range(5): p.apply_async(long_time_task, args=(i,)) print 'Waiting for all subprocesses done...' p.close() p.join() print 'All subprocesses done.' """ 代码解读: 对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了。 请注意输出的结果,task 0,1,2,3是立刻执行的,而task 4要等待前面某个task完成后才执行,这是因为Pool的默认大小在我的电脑上是4,因此,最多同时执行4个进程。这是Pool有意设计的限制,并不是操作系统的限制。如果改成: p = Pool(5) """
Jayin/practice_on_py
Process&Thread/PoolTest.py
Python
mit
1,094
package net.comfreeze.lib; import android.app.AlarmManager; import android.app.Application; import android.app.NotificationManager; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.content.res.Resources; import android.location.LocationManager; import android.media.AudioManager; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import net.comfreeze.lib.audio.SoundManager; import java.io.File; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Calendar; import java.util.TimeZone; abstract public class CFZApplication extends Application { public static final String TAG = "CFZApplication"; public static final String PACKAGE = "com.rastermedia"; public static final String KEY_DEBUG = "debug"; public static final String KEY_SYNC_PREFEX = "sync_"; public static SharedPreferences preferences = null; protected static Context context = null; protected static CFZApplication instance; public static LocalBroadcastManager broadcast; public static boolean silent = true; @Override public void onCreate() { if (!silent) Log.d(TAG, "Initializing"); instance = this; setContext(); setPreferences(); broadcast = LocalBroadcastManager.getInstance(context); super.onCreate(); } @Override public void onLowMemory() { if (!silent) Log.d(TAG, "Low memory!"); super.onLowMemory(); } @Override public void onTerminate() { unsetContext(); if (!silent) Log.d(TAG, "Terminating"); super.onTerminate(); } abstract public void setPreferences(); abstract public void setContext(); abstract public void unsetContext(); abstract public String getProductionKey(); public static CFZApplication getInstance(Class<?> className) { // log("Returning current application instance"); if (instance == null) { synchronized (className) { if (instance == null) try { instance = (CFZApplication) className.newInstance(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } } } return instance; } public void clearApplicationData() { File cache = getCacheDir(); File appDir = new File(cache.getParent()); if (appDir.exists()) { String[] children = appDir.list(); for (String dir : children) { if (!dir.equals("lib")) { deleteDir(new File(appDir, dir)); } } } preferences.edit().clear().commit(); } private static boolean deleteDir(File dir) { if (dir != null) { if (!silent) Log.d(PACKAGE, "Deleting: " + dir.getAbsolutePath()); if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) return false; } } return dir.delete(); } return false; } public static int dipsToPixel(float value, float scale) { return (int) (value * scale + 0.5f); } public static long timezoneOffset() { Calendar calendar = Calendar.getInstance(); return (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)); } public static long timezoneOffset(String timezone) { Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(timezone)); return (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)); } public static Resources res() { return context.getResources(); } public static LocationManager getLocationManager(Context context) { return (LocationManager) context.getSystemService(LOCATION_SERVICE); } public static AlarmManager getAlarmManager(Context context) { return (AlarmManager) context.getSystemService(ALARM_SERVICE); } public static NotificationManager getNotificationManager(Context context) { return (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE); } public static AudioManager getAudioManager(Context context) { return (AudioManager) context.getSystemService(AUDIO_SERVICE); } public static SoundManager getSoundManager(CFZApplication application) { return (SoundManager) SoundManager.instance(application); } public static void setSyncDate(String key, long date) { preferences.edit().putLong(KEY_SYNC_PREFEX + key, date).commit(); } public static long getSyncDate(String key) { return preferences.getLong(KEY_SYNC_PREFEX + key, -1L); } public static boolean needSync(String key, long limit) { return (System.currentTimeMillis() - getSyncDate(key) > limit); } public static String hash(final String algorithm, final String s) { try { // Create specified hash MessageDigest digest = java.security.MessageDigest.getInstance(algorithm); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); // Create hex string StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) h = "0" + h; hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } public boolean isProduction(Context context) { boolean result = false; try { ComponentName component = new ComponentName(context, instance.getClass()); PackageInfo info = context.getPackageManager().getPackageInfo(component.getPackageName(), PackageManager.GET_SIGNATURES); Signature[] sigs = info.signatures; for (int i = 0; i < sigs.length; i++) if (!silent) Log.d(TAG, "Signing key: " + sigs[i].toCharsString()); String targetKey = getProductionKey(); if (null == targetKey) targetKey = ""; if (targetKey.equals(sigs[0].toCharsString())) { result = true; if (!silent) Log.d(TAG, "Signed with production key"); } else { if (!silent) Log.d(TAG, "Not signed with production key"); } } catch (PackageManager.NameNotFoundException e) { if (!silent) Log.e(TAG, "Package exception", e); } return result; } public static class LOG { // Without Throwables public static void v(String tag, String message) { if (!silent) Log.v(tag, message); } public static void d(String tag, String message) { if (!silent) Log.d(tag, message); } public static void i(String tag, String message) { if (!silent) Log.i(tag, message); } public static void w(String tag, String message) { if (!silent) Log.w(tag, message); } public static void e(String tag, String message) { if (!silent) Log.e(tag, message); } public static void wtf(String tag, String message) { if (!silent) Log.wtf(tag, message); } // With Throwables public static void v(String tag, String message, Throwable t) { if (!silent) Log.v(tag, message, t); } public static void d(String tag, String message, Throwable t) { if (!silent) Log.d(tag, message, t); } public static void i(String tag, String message, Throwable t) { if (!silent) Log.i(tag, message, t); } public static void w(String tag, String message, Throwable t) { if (!silent) Log.w(tag, message, t); } public static void e(String tag, String message, Throwable t) { if (!silent) Log.e(tag, message, t); } public static void wtf(String tag, String message, Throwable t) { if (!silent) Log.wtf(tag, message, t); } } }
comfreeze/android-tools
CFZLib/src/main/java/net/comfreeze/lib/CFZApplication.java
Java
mit
8,991
/** * @author yomboprime https://github.com/yomboprime * * GPUComputationRenderer, based on SimulationRenderer by zz85 * * The GPUComputationRenderer uses the concept of variables. These variables are RGBA float textures that hold 4 floats * for each compute element (texel) * * Each variable has a fragment shader that defines the computation made to obtain the variable in question. * You can use as many variables you need, and make dependencies so you can use textures of other variables in the shader * (the sampler uniforms are added automatically) Most of the variables will need themselves as dependency. * * The renderer has actually two render targets per variable, to make ping-pong. Textures from the current frame are used * as inputs to render the textures of the next frame. * * The render targets of the variables can be used as input textures for your visualization shaders. * * Variable names should be valid identifiers and should not collide with THREE GLSL used identifiers. * a common approach could be to use 'texture' prefixing the variable name; i.e texturePosition, textureVelocity... * * The size of the computation (sizeX * sizeY) is defined as 'resolution' automatically in the shader. For example: * #DEFINE resolution vec2( 1024.0, 1024.0 ) * * ------------- * * Basic use: * * // Initialization... * * // Create computation renderer * var gpuCompute = new GPUComputationRenderer( 1024, 1024, renderer ); * * // Create initial state float textures * var pos0 = gpuCompute.createTexture(); * var vel0 = gpuCompute.createTexture(); * // and fill in here the texture data... * * // Add texture variables * var velVar = gpuCompute.addVariable( "textureVelocity", fragmentShaderVel, pos0 ); * var posVar = gpuCompute.addVariable( "texturePosition", fragmentShaderPos, vel0 ); * * // Add variable dependencies * gpuCompute.setVariableDependencies( velVar, [ velVar, posVar ] ); * gpuCompute.setVariableDependencies( posVar, [ velVar, posVar ] ); * * // Add custom uniforms * velVar.material.uniforms.time = { value: 0.0 }; * * // Check for completeness * var error = gpuCompute.init(); * if ( error !== null ) { * console.error( error ); * } * * * // In each frame... * * // Compute! * gpuCompute.compute(); * * // Update texture uniforms in your visualization materials with the gpu renderer output * myMaterial.uniforms.myTexture.value = gpuCompute.getCurrentRenderTarget( posVar ).texture; * * // Do your rendering * renderer.render( myScene, myCamera ); * * ------------- * * Also, you can use utility functions to create ShaderMaterial and perform computations (rendering between textures) * Note that the shaders can have multiple input textures. * * var myFilter1 = gpuCompute.createShaderMaterial( myFilterFragmentShader1, { theTexture: { value: null } } ); * var myFilter2 = gpuCompute.createShaderMaterial( myFilterFragmentShader2, { theTexture: { value: null } } ); * * var inputTexture = gpuCompute.createTexture(); * * // Fill in here inputTexture... * * myFilter1.uniforms.theTexture.value = inputTexture; * * var myRenderTarget = gpuCompute.createRenderTarget(); * myFilter2.uniforms.theTexture.value = myRenderTarget.texture; * * var outputRenderTarget = gpuCompute.createRenderTarget(); * * // Now use the output texture where you want: * myMaterial.uniforms.map.value = outputRenderTarget.texture; * * // And compute each frame, before rendering to screen: * gpuCompute.doRenderTarget( myFilter1, myRenderTarget ); * gpuCompute.doRenderTarget( myFilter2, outputRenderTarget ); * * * * @param {int} sizeX Computation problem size is always 2d: sizeX * sizeY elements. * @param {int} sizeY Computation problem size is always 2d: sizeX * sizeY elements. * @param {WebGLRenderer} renderer The renderer */ import { Camera, ClampToEdgeWrapping, DataTexture, FloatType, HalfFloatType, Mesh, NearestFilter, PlaneBufferGeometry, RGBAFormat, Scene, ShaderMaterial, WebGLRenderTarget } from "./three.module.js"; var GPUComputationRenderer = function ( sizeX, sizeY, renderer ) { this.variables = []; this.currentTextureIndex = 0; var scene = new Scene(); var camera = new Camera(); camera.position.z = 1; var passThruUniforms = { passThruTexture: { value: null } }; var passThruShader = createShaderMaterial( getPassThroughFragmentShader(), passThruUniforms ); var mesh = new Mesh( new PlaneBufferGeometry( 2, 2 ), passThruShader ); scene.add( mesh ); this.addVariable = function ( variableName, computeFragmentShader, initialValueTexture ) { var material = this.createShaderMaterial( computeFragmentShader ); var variable = { name: variableName, initialValueTexture: initialValueTexture, material: material, dependencies: null, renderTargets: [], wrapS: null, wrapT: null, minFilter: NearestFilter, magFilter: NearestFilter }; this.variables.push( variable ); return variable; }; this.setVariableDependencies = function ( variable, dependencies ) { variable.dependencies = dependencies; }; this.init = function () { if ( ! renderer.extensions.get( "OES_texture_float" ) && ! renderer.capabilities.isWebGL2 ) { return "No OES_texture_float support for float textures."; } if ( renderer.capabilities.maxVertexTextures === 0 ) { return "No support for vertex shader textures."; } for ( var i = 0; i < this.variables.length; i ++ ) { var variable = this.variables[ i ]; // Creates rendertargets and initialize them with input texture variable.renderTargets[ 0 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter ); variable.renderTargets[ 1 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter ); this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 0 ] ); this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 1 ] ); // Adds dependencies uniforms to the ShaderMaterial var material = variable.material; var uniforms = material.uniforms; if ( variable.dependencies !== null ) { for ( var d = 0; d < variable.dependencies.length; d ++ ) { var depVar = variable.dependencies[ d ]; if ( depVar.name !== variable.name ) { // Checks if variable exists var found = false; for ( var j = 0; j < this.variables.length; j ++ ) { if ( depVar.name === this.variables[ j ].name ) { found = true; break; } } if ( ! found ) { return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name; } } uniforms[ depVar.name ] = { value: null }; material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader; } } } this.currentTextureIndex = 0; return null; }; this.compute = function () { var currentTextureIndex = this.currentTextureIndex; var nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0; for ( var i = 0, il = this.variables.length; i < il; i ++ ) { var variable = this.variables[ i ]; // Sets texture dependencies uniforms if ( variable.dependencies !== null ) { var uniforms = variable.material.uniforms; for ( var d = 0, dl = variable.dependencies.length; d < dl; d ++ ) { var depVar = variable.dependencies[ d ]; uniforms[ depVar.name ].value = depVar.renderTargets[ currentTextureIndex ].texture; } } // Performs the computation for this variable this.doRenderTarget( variable.material, variable.renderTargets[ nextTextureIndex ] ); } this.currentTextureIndex = nextTextureIndex; }; this.getCurrentRenderTarget = function ( variable ) { return variable.renderTargets[ this.currentTextureIndex ]; }; this.getAlternateRenderTarget = function ( variable ) { return variable.renderTargets[ this.currentTextureIndex === 0 ? 1 : 0 ]; }; function addResolutionDefine( materialShader ) { materialShader.defines.resolution = 'vec2( ' + sizeX.toFixed( 1 ) + ', ' + sizeY.toFixed( 1 ) + " )"; } this.addResolutionDefine = addResolutionDefine; // The following functions can be used to compute things manually function createShaderMaterial( computeFragmentShader, uniforms ) { uniforms = uniforms || {}; var material = new ShaderMaterial( { uniforms: uniforms, vertexShader: getPassThroughVertexShader(), fragmentShader: computeFragmentShader } ); addResolutionDefine( material ); return material; } this.createShaderMaterial = createShaderMaterial; this.createRenderTarget = function ( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) { sizeXTexture = sizeXTexture || sizeX; sizeYTexture = sizeYTexture || sizeY; wrapS = wrapS || ClampToEdgeWrapping; wrapT = wrapT || ClampToEdgeWrapping; minFilter = minFilter || NearestFilter; magFilter = magFilter || NearestFilter; var renderTarget = new WebGLRenderTarget( sizeXTexture, sizeYTexture, { wrapS: wrapS, wrapT: wrapT, minFilter: minFilter, magFilter: magFilter, format: RGBAFormat, type: ( /(iPad|iPhone|iPod)/g.test( navigator.userAgent ) ) ? HalfFloatType : FloatType, stencilBuffer: false, depthBuffer: false } ); return renderTarget; }; this.createTexture = function () { var a = new Float32Array( sizeX * sizeY * 4 ); var texture = new DataTexture( a, sizeX, sizeY, RGBAFormat, FloatType ); texture.needsUpdate = true; return texture; }; this.renderTexture = function ( input, output ) { // Takes a texture, and render out in rendertarget // input = Texture // output = RenderTarget passThruUniforms.passThruTexture.value = input; this.doRenderTarget( passThruShader, output ); passThruUniforms.passThruTexture.value = null; }; this.doRenderTarget = function ( material, output ) { var currentRenderTarget = renderer.getRenderTarget(); mesh.material = material; renderer.setRenderTarget( output ); renderer.render( scene, camera ); mesh.material = passThruShader; renderer.setRenderTarget( currentRenderTarget ); }; // Shaders function getPassThroughVertexShader() { return "void main() {\n" + "\n" + " gl_Position = vec4( position, 1.0 );\n" + "\n" + "}\n"; } function getPassThroughFragmentShader() { return "uniform sampler2D passThruTexture;\n" + "\n" + "void main() {\n" + "\n" + " vec2 uv = gl_FragCoord.xy / resolution.xy;\n" + "\n" + " gl_FragColor = texture2D( passThruTexture, uv );\n" + "\n" + "}\n"; } }; export { GPUComputationRenderer };
ChenJiaH/chenjiah.github.io
js/GPUComputationRenderer.js
JavaScript
mit
10,733
package com.example.mesh; import java.util.HashMap; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; @Path("/") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class EndpointControlResource { /** * @see <a href="https://relay.bluejeans.com/docs/mesh.html#capabilities">https://relay.bluejeans.com/docs/mesh.html#capabilities</a> */ @GET @Path("{ipAddress}/capabilities") public Map<String, Boolean> capabilities(@PathParam("ipAddress") final String ipAddress, @QueryParam("port") final Integer port, @QueryParam("name") final String name) { System.out.println("Received capabilities request"); System.out.println(" ipAddress = " + ipAddress); System.out.println(" port = " + port); System.out.println(" name = " + name); final Map<String, Boolean> capabilities = new HashMap<>(); capabilities.put("JOIN", true); capabilities.put("HANGUP", true); capabilities.put("STATUS", true); capabilities.put("MUTEMICROPHONE", true); return capabilities; } /** * @see <a href="https://relay.bluejeans.com/docs/mesh.html#status">https://relay.bluejeans.com/docs/mesh.html#status</a> */ @GET @Path("{ipAddress}/status") public Map<String, Boolean> status(@PathParam("ipAddress") final String ipAddress, @QueryParam("port") final Integer port, @QueryParam("name") final String name) { System.out.println("Received status request"); System.out.println(" ipAddress = " + ipAddress); System.out.println(" port = " + port); System.out.println(" name = " + name); final Map<String, Boolean> status = new HashMap<>(); status.put("callActive", false); status.put("microphoneMuted", false); return status; } /** * @see <a href="https://relay.bluejeans.com/docs/mesh.html#join">https://relay.bluejeans.com/docs/mesh.html#join</a> */ @POST @Path("{ipAddress}/join") public void join(@PathParam("ipAddress") final String ipAddress, @QueryParam("dialString") final String dialString, @QueryParam("meetingId") final String meetingId, @QueryParam("passcode") final String passcode, @QueryParam("bridgeAddress") final String bridgeAddress, final Endpoint endpoint) { System.out.println("Received join request"); System.out.println(" ipAddress = " + ipAddress); System.out.println(" dialString = " + dialString); System.out.println(" meetingId = " + meetingId); System.out.println(" passcode = " + passcode); System.out.println(" bridgeAddress = " + bridgeAddress); System.out.println(" endpoint = " + endpoint); } /** * @see <a href="https://relay.bluejeans.com/docs/mesh.html#hangup">https://relay.bluejeans.com/docs/mesh.html#hangup</a> */ @POST @Path("{ipAddress}/hangup") public void hangup(@PathParam("ipAddress") final String ipAddress, final Endpoint endpoint) { System.out.println("Received hangup request"); System.out.println(" ipAddress = " + ipAddress); System.out.println(" endpoint = " + endpoint); } /** * @see <a href="https://relay.bluejeans.com/docs/mesh.html#mutemicrophone">https://relay.bluejeans.com/docs/mesh.html#mutemicrophone</a> */ @POST @Path("{ipAddress}/mutemicrophone") public void muteMicrophone(@PathParam("ipAddress") final String ipAddress, final Endpoint endpoint) { System.out.println("Received mutemicrophone request"); System.out.println(" ipAddress = " + ipAddress); System.out.println(" endpoint = " + endpoint); } /** * @see <a href="https://relay.bluejeans.com/docs/mesh.html#mutemicrophone">https://relay.bluejeans.com/docs/mesh.html#mutemicrophone</a> */ @POST @Path("{ipAddress}/unmutemicrophone") public void unmuteMicrophone(@PathParam("ipAddress") final String ipAddress, final Endpoint endpoint) { System.out.println("Received unmutemicrophone request"); System.out.println(" ipAddress = " + ipAddress); System.out.println(" endpoint = " + endpoint); } }
Aldaviva/relay-mesh-example-java
src/main/java/com/example/mesh/EndpointControlResource.java
Java
mit
4,452
/*jshint node:true*/ /*global test, suite, setup, teardown*/ 'use strict'; var assert = require('assert'); var tika = require('../'); suite('document tests', function() { test('detect txt content-type', function(done) { tika.type('test/data/file.txt', function(err, contentType) { assert.ifError(err); assert.equal(typeof contentType, 'string'); assert.equal(contentType, 'text/plain'); done(); }); }); test('detect txt content-type and charset', function(done) { tika.typeAndCharset('test/data/file.txt', function(err, contentType) { assert.ifError(err); assert.equal(typeof contentType, 'string'); assert.equal(contentType, 'text/plain; charset=ISO-8859-1'); done(); }); }); test('extract from txt', function(done) { tika.text('test/data/file.txt', function(err, text) { assert.ifError(err); assert.equal(typeof text, 'string'); assert.equal(text, 'Just some text.\n\n'); done(); }); }); test('extract meta from txt', function(done) { tika.meta('test/data/file.txt', function(err, meta) { assert.ifError(err); assert.ok(meta); assert.equal(typeof meta.resourceName[0], 'string'); assert.deepEqual(meta.resourceName, ['file.txt']); assert.deepEqual(meta['Content-Type'], ['text/plain; charset=ISO-8859-1']); assert.deepEqual(meta['Content-Encoding'], ['ISO-8859-1']); done(); }); }); test('extract meta and text from txt', function(done) { tika.extract('test/data/file.txt', function(err, text, meta) { assert.ifError(err); assert.equal(typeof text, 'string'); assert.equal(text, 'Just some text.\n\n'); assert.ok(meta); assert.equal(typeof meta.resourceName[0], 'string'); assert.deepEqual(meta.resourceName, ['file.txt']); assert.deepEqual(meta['Content-Type'], ['text/plain; charset=ISO-8859-1']); assert.deepEqual(meta['Content-Encoding'], ['ISO-8859-1']); done(); }); }); test('extract from extensionless txt', function(done) { tika.text('test/data/extensionless/txt', function(err, text) { assert.ifError(err); assert.equal(text, 'Just some text.\n\n'); done(); }); }); test('extract from doc', function(done) { tika.text('test/data/file.doc', function(err, text) { assert.ifError(err); assert.equal(text, 'Just some text.\n'); done(); }); }); test('extract meta from doc', function(done) { tika.meta('test/data/file.doc', function(err, meta) { assert.ifError(err); assert.ok(meta); assert.deepEqual(meta.resourceName, ['file.doc']); assert.deepEqual(meta['Content-Type'], ['application/msword']); assert.deepEqual(meta['dcterms:created'], ['2013-12-06T21:15:26Z']); done(); }); }); test('extract from extensionless doc', function(done) { tika.text('test/data/extensionless/doc', function(err, text) { assert.ifError(err); assert.equal(text, 'Just some text.\n'); done(); }); }); test('extract from docx', function(done) { tika.text('test/data/file.docx', function(err, text) { assert.ifError(err); assert.equal(text, 'Just some text.\n'); done(); }); }); test('extract meta from docx', function(done) { tika.meta('test/data/file.docx', function(err, meta) { assert.ifError(err); assert.ok(meta); assert.deepEqual(meta.resourceName, ['file.docx']); assert.deepEqual(meta['Content-Type'], ['application/vnd.openxmlformats-officedocument.wordprocessingml.document']); assert.deepEqual(meta['Application-Name'], ['LibreOffice/4.1.3.2$MacOSX_x86 LibreOffice_project/70feb7d99726f064edab4605a8ab840c50ec57a']); done(); }); }); test('extract from extensionless docx', function(done) { tika.text('test/data/extensionless/docx', function(err, text) { assert.ifError(err); assert.equal(text, 'Just some text.\n'); done(); }); }); test('extract meta from extensionless docx', function(done) { tika.meta('test/data/extensionless/docx', function(err, meta) { assert.ifError(err); assert.ok(meta); assert.deepEqual(meta.resourceName, ['docx']); assert.deepEqual(meta['Content-Type'], ['application/vnd.openxmlformats-officedocument.wordprocessingml.document']); assert.deepEqual(meta['Application-Name'], ['LibreOffice/4.1.3.2$MacOSX_x86 LibreOffice_project/70feb7d99726f064edab4605a8ab840c50ec57a']); done(); }); }); test('extract from pdf', function(done) { tika.text('test/data/file.pdf', function(err, text) { assert.ifError(err); assert.equal(text.trim(), 'Just some text.'); done(); }); }); test('detect content-type of pdf', function(done) { tika.type('test/data/file.pdf', function(err, contentType) { assert.ifError(err); assert.equal(contentType, 'application/pdf'); done(); }); }); test('extract meta from pdf', function(done) { tika.meta('test/data/file.pdf', function(err, meta) { assert.ifError(err); assert.ok(meta); assert.deepEqual(meta.resourceName, ['file.pdf']); assert.deepEqual(meta['Content-Type'], ['application/pdf']); assert.deepEqual(meta.producer, ['LibreOffice 4.1']); done(); }); }); test('extract from extensionless pdf', function(done) { tika.text('test/data/extensionless/pdf', function(err, text) { assert.ifError(err); assert.equal(text.trim(), 'Just some text.'); done(); }); }); test('extract meta from extensionless pdf', function(done) { tika.meta('test/data/extensionless/pdf', function(err, meta) { assert.ifError(err); assert.ok(meta); assert.deepEqual(meta.resourceName, ['pdf']); assert.deepEqual(meta['Content-Type'], ['application/pdf']); assert.deepEqual(meta.producer, ['LibreOffice 4.1']); done(); }); }); test('extract from protected pdf', function(done) { tika.text('test/data/protected/file.pdf', function(err, text) { assert.ifError(err); assert.equal(text.trim(), 'Just some text.'); done(); }); }); test('extract meta from protected pdf', function(done) { tika.meta('test/data/protected/file.pdf', function(err, meta) { assert.ifError(err); assert.ok(meta); assert.deepEqual(meta.resourceName, ['file.pdf']); assert.deepEqual(meta['Content-Type'], ['application/pdf']); assert.deepEqual(meta.producer, ['LibreOffice 4.1']); done(); }); }); }); suite('partial document extraction tests', function() { test('extract from long txt', function(done) { tika.text('test/data/big/file.txt', { maxLength: 10 }, function(err, text) { assert.ifError(err); assert.equal(text.length, 10); assert.equal(text, 'Lorem ipsu'); done(); }); }); test('extract from pdf', function(done) { tika.text('test/data/file.pdf', { maxLength: 10 }, function(err, text) { assert.ifError(err); assert.equal(text.length, 10); assert.equal(text.trim(), 'Just some'); done(); }); }); }); suite('obscure document tests', function() { test('extract from Word 2003 XML', function(done) { tika.text('test/data/obscure/word2003.xml', function(err, text) { assert.ifError(err); assert.ok(-1 !== text.indexOf('Just some text.')); assert.ok(-1 === text.indexOf('<?xml')); done(); }); }); }); suite('structured data tests', function() { test('extract from plain XML', function(done) { tika.text('test/data/structured/plain.xml', function(err, text) { assert.ifError(err); assert.ok(-1 !== text.indexOf('Just some text.')); assert.ok(-1 === text.indexOf('<?xml')); done(); }); }); }); suite('image tests', function() { test('extract from png', function(done) { tika.text('test/data/file.png', function(err, text) { assert.ifError(err); assert.equal(text, ''); done(); }); }); test('extract from extensionless png', function(done) { tika.text('test/data/extensionless/png', function(err, text) { assert.ifError(err); assert.equal(text, ''); done(); }); }); test('extract from gif', function(done) { tika.text('test/data/file.gif', function(err, text) { assert.ifError(err); assert.equal(text, ''); done(); }); }); test('extract meta from gif', function(done) { tika.meta('test/data/file.gif', function(err, meta) { assert.ifError(err); assert.ok(meta); assert.deepEqual(meta.resourceName, ['file.gif']); assert.deepEqual(meta['Content-Type'], ['image/gif']); assert.deepEqual(meta['Dimension ImageOrientation'], ['Normal']); done(); }); }); test('extract from extensionless gif', function(done) { tika.text('test/data/extensionless/gif', function(err, text) { assert.ifError(err); assert.equal(text, ''); done(); }); }); test('extract meta from extensionless gif', function(done) { tika.meta('test/data/extensionless/gif', function(err, meta) { assert.ifError(err); assert.ok(meta); assert.deepEqual(meta.resourceName, ['gif']); assert.deepEqual(meta['Content-Type'], ['image/gif']); assert.deepEqual(meta['Dimension ImageOrientation'], ['Normal']); done(); }); }); }); suite('non-utf8 encoded document tests', function() { test('extract Windows Latin 1 text', function(done) { tika.text('test/data/nonutf8/windows-latin1.txt', function(err, text) { assert.ifError(err); assert.equal(text, 'Algún pequeño trozo de texto.\n\n'); done(); }); }); test('detect Windows Latin 1 text charset', function(done) { tika.charset('test/data/nonutf8/windows-latin1.txt', function(err, charset) { assert.ifError(err); assert.equal(typeof charset, 'string'); assert.equal(charset, 'ISO-8859-1'); done(); }); }); test('detect Windows Latin 1 text content-type and charset', function(done) { tika.typeAndCharset('test/data/nonutf8/windows-latin1.txt', function(err, contentType) { assert.ifError(err); assert.equal(contentType, 'text/plain; charset=ISO-8859-1'); done(); }); }); test('extract UTF-16 English-language text', function(done) { tika.text('test/data/nonutf8/utf16-english.txt', function(err, text) { assert.ifError(err); assert.equal(text, 'Just some text.\n\n'); done(); }); }); test('detect UTF-16 English-language text charset', function(done) { tika.charset('test/data/nonutf8/utf16-english.txt', function(err, charset) { assert.ifError(err); assert.equal(charset, 'UTF-16LE'); done(); }); }); test('detect UTF-16 English-language text content-type and charset', function(done) { tika.typeAndCharset('test/data/nonutf8/utf16-english.txt', function(err, contentType) { assert.ifError(err); assert.equal(contentType, 'text/plain; charset=UTF-16LE'); done(); }); }); test('extract UTF-16 Chinese (Simplified) text', function(done) { tika.text('test/data/nonutf8/utf16-chinese.txt', function(err, text) { assert.ifError(err); assert.equal(text, '\u53ea\u662f\u4e00\u4e9b\u6587\u5b57\u3002\n\n'); done(); }); }); test('detect UTF-16 Chinese (Simplified) text charset', function(done) { tika.charset('test/data/nonutf8/utf16-chinese.txt', function(err, charset) { assert.ifError(err); assert.equal(charset, 'UTF-16LE'); done(); }); }); test('detect UTF-16 Chinese (Simplified) text content-type and charset', function(done) { tika.typeAndCharset('test/data/nonutf8/utf16-chinese.txt', function(err, contentType) { assert.ifError(err); assert.equal(contentType, 'text/plain; charset=UTF-16LE'); done(); }); }); }); suite('archive tests', function() { test('extract from compressed archive', function(done) { tika.text('test/data/archive/files.zip', function(err, text) { assert.ifError(err); assert.equal(text.trim(), 'file1.txt\nSome text 1.\n\n\n\n\nfile2.txt\nSome text 2.\n\n\n\n\nfile3.txt\nSome text 3.'); done(); }); }); test('extract from compressed zlib archive', function(done) { tika.text('test/data/archive/files.zlib', function(err, text) { assert.ifError(err); assert.equal(text.trim(), 'files\nSome text 1.\nSome text 2.\nSome text 3.'); done(); }); }); test('detect compressed archive content-type', function(done) { tika.type('test/data/archive/files.zip', function(err, contentType) { assert.ifError(err); assert.equal(contentType, 'application/zip'); done(); }); }); test('extract from twice compressed archive', function(done) { tika.text('test/data/archive/files-files.zip', function(err, text) { assert.ifError(err); assert.equal(text.trim(), 'file4.txt\nSome text 4.\n\n\n\n\nfile5.txt\nSome text 5.\n\n\n\n\nfile6.txt\nSome text 6.\n\n\n\n\nfiles.zip\n\n\nfile1.txt\n\nSome text 1.\n\n\n\n\n\n\n\nfile2.txt\n\nSome text 2.\n\n\n\n\n\n\n\nfile3.txt\n\nSome text 3.'); done(); }); }); }); suite('encrypted doc tests', function() { test('detect encrypted pdf content-type', function(done) { tika.type('test/data/encrypted/file.pdf', function(err, contentType) { assert.ifError(err); assert.equal(contentType, 'application/pdf'); done(); }); }); test('detect encrypted doc content-type', function(done) { tika.type('test/data/encrypted/file.doc', function(err, contentType) { assert.ifError(err); assert.equal(contentType, 'application/msword'); done(); }); }); test('specify password to decrypt document', function(done) { tika.text('test/data/encrypted/file.pdf', { password: 'password' }, function(err, text) { assert.ifError(err); assert.equal(text.trim(), 'Just some text.'); done(); }); }); }); suite('error handling tests', function() { test('extract from encrypted doc', function(done) { tika.text('test/data/encrypted/file.doc', function(err, text) { assert.ok(err); assert.ok(-1 !== err.toString().indexOf('EncryptedDocumentException: Cannot process encrypted word file')); done(); }); }); test('extract from encrypted pdf', function(done) { tika.text('test/data/encrypted/file.pdf', function(err, text) { assert.ok(err); assert.ok(-1 !== err.toString().indexOf('Unable to process: document is encrypted')); done(); }); }); }); suite('http extraction tests', function() { test('extract from pdf over http', function(done) { tika.text('http://www.ohchr.org/EN/UDHR/Documents/UDHR_Translations/eng.pdf', function(err, text) { assert.ifError(err); assert.ok(-1 !== text.indexOf('Universal Declaration of Human Rights')); done(); }); }); }); suite('ftp extraction tests', function() { test('extract from text file over ftp', function(done) { tika.text('ftp://ftp.ed.ac.uk/INSTRUCTIONS-FOR-USING-THIS-SERVICE', function(err, text) { assert.ifError(err); assert.ok(-1 !== text.indexOf('This service is managed by Information Services')); done(); }); }); }); suite('language detection tests', function() { test('detect English text', function(done) { tika.language('This just some text in English.', function(err, language, reasonablyCertain) { assert.ifError(err); assert.equal(typeof language, 'string'); assert.equal(typeof reasonablyCertain, 'boolean'); assert.equal(language, 'en'); done(); }); }); });
ICIJ/node-tika
test/tika.js
JavaScript
mit
14,883
<?php namespace Screeenly\Screenshot; /** * Interface description. * * @author Stefan Zweifel */ interface ClientInterface { /** * Method description. * * @author Stefan Zweifel * * @param type $parameter * * @return type */ public function build(); public function capture(Screenshot $screenshot); }
imdanshraaj/screeenly
app/Screenshot/ClientInterface.php
PHP
mit
362
// cpu/test/unique-strings.cpp -*-C++-*- // ---------------------------------------------------------------------------- // Copyright (C) 2015 Dietmar Kuehl http://www.dietmar-kuehl.de // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, // merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // ---------------------------------------------------------------------------- #include "cpu/tube/context.hpp" #include <algorithm> #include <iostream> #include <iomanip> #include <sstream> #include <iterator> #include <string> #include <random> #include <set> #include <unordered_set> #include <vector> #if defined(HAS_BSL) #include <bsl_set.h> #include <bsl_unordered_set.h> #endif #include <stdlib.h> // ---------------------------------------------------------------------------- namespace std { template <typename Algo> void hashAppend(Algo& algo, std::string const& value) { algo(value.c_str(), value.size()); } } // ---------------------------------------------------------------------------- namespace { struct std_algos { std::string name() const { return "std::sort()/std::unique()"; } std::size_t run(std::vector<std::string> const& keys) const { std::vector<std::string> values(keys.begin(), keys.end()); std::sort(values.begin(), values.end()); auto end = std::unique(values.begin(), values.end()); values.erase(end, values.end()); return values.size(); } }; struct std_set { std::string name() const { return "std::set<std::string>"; } std::size_t run(std::vector<std::string> const& keys) const { std::set<std::string> values(keys.begin(), keys.end()); return values.size(); } }; struct std_insert_set { std::string name() const { return "std::set<std::string> (insert)"; } std::size_t run(std::vector<std::string> const& keys) const { std::set<std::string> values; for (std::string value: keys) { values.insert(value); } return values.size(); } }; struct std_reverse_set { std::string name() const { return "std::set<std::string> (reverse)"; } std::size_t run(std::vector<std::string> const& keys) const { std::set<std::string> values; for (std::string value: keys) { std::reverse(value.begin(), value.end()); values.insert(value); } return values.size(); } }; struct std_unordered_set { std::string name() const { return "std::unordered_set<std::string>"; } std::size_t run(std::vector<std::string> const& keys) const { std::unordered_set<std::string> values(keys.begin(), keys.end()); return values.size(); } }; struct std_insert_unordered_set { std::string name() const { return "std::unordered_set<std::string> (insert)"; } std::size_t run(std::vector<std::string> const& keys) const { std::unordered_set<std::string> values; for (std::string value: keys) { values.insert(value); } return values.size(); } }; struct std_reserve_unordered_set { std::string name() const { return "std::unordered_set<std::string> (reserve)"; } std::size_t run(std::vector<std::string> const& keys) const { std::unordered_set<std::string> values; values.reserve(keys.size()); for (std::string value: keys) { values.insert(value); } return values.size(); } }; #if defined(HAS_BSL) struct bsl_set { std::string name() const { return "bsl::set<std::string>"; } std::size_t run(std::vector<std::string> const& keys) const { bsl::set<std::string> values(keys.begin(), keys.end()); return values.size(); } }; struct bsl_insert_set { std::string name() const { return "bsl::set<std::string> (insert)"; } std::size_t run(std::vector<std::string> const& keys) const { bsl::set<std::string> values; for (std::string value: keys) { values.insert(value); } return values.size(); } }; struct bsl_reverse_set { std::string name() const { return "bsl::set<std::string> (reverse)"; } std::size_t run(std::vector<std::string> const& keys) const { bsl::set<std::string> values; for (std::string value: keys) { std::reverse(value.begin(), value.end()); values.insert(value); } return values.size(); } }; struct bsl_unordered_set { std::string name() const { return "bsl::unordered_set<std::string>"; } std::size_t run(std::vector<std::string> const& keys) const { bsl::unordered_set<std::string> values(keys.begin(), keys.end()); return values.size(); } }; struct bsl_insert_unordered_set { std::string name() const { return "bsl::unordered_set<std::string> (insert)"; } std::size_t run(std::vector<std::string> const& keys) const { bsl::unordered_set<std::string> values; for (std::string value: keys) { values.insert(value); } return values.size(); } }; struct bsl_reserve_unordered_set { std::string name() const { return "bsl::unordered_set<std::string> (reserve)"; } std::size_t run(std::vector<std::string> const& keys) const { bsl::unordered_set<std::string> values; values.reserve(keys.size()); for (std::string value: keys) { values.insert(value); } return values.size(); } }; #endif } // ---------------------------------------------------------------------------- namespace { template <typename Algo> void measure(cpu::tube::context& context, std::vector<std::string> const& keys, std::size_t basesize, Algo algo) { auto timer = context.start(); std::size_t size = algo.run(keys); auto time = timer.measure(); std::ostringstream out; out << std::left << std::setw(50) << algo.name() << " [" << keys.size() << "/" << basesize << "]"; context.report(out.str(), time, size); } } static void measure(cpu::tube::context& context, std::vector<std::string> const& keys, std::size_t basesize) { measure(context, keys, basesize, std_algos()); measure(context, keys, basesize, std_set()); measure(context, keys, basesize, std_insert_set()); measure(context, keys, basesize, std_reverse_set()); measure(context, keys, basesize, std_unordered_set()); measure(context, keys, basesize, std_insert_unordered_set()); measure(context, keys, basesize, std_reserve_unordered_set()); #if defined(HAS_BSL) measure(context, keys, basesize, bsl_set()); measure(context, keys, basesize, bsl_insert_set()); measure(context, keys, basesize, bsl_reverse_set()); measure(context, keys, basesize, bsl_unordered_set()); measure(context, keys, basesize, bsl_insert_unordered_set()); measure(context, keys, basesize, bsl_reserve_unordered_set()); #endif } // ---------------------------------------------------------------------------- static void run_tests(cpu::tube::context& context, int size) { std::string const bases[] = { "/usr/local/include/", "/some/medium/sized/path/as/a/prefix/to/the/actual/interesting/names/", "/finally/a/rather/long/string/including/pointless/sequences/like/" "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/" "just/to/make/the/string/longer/to/qualify/as/an/actual/long/string/" }; std::mt19937 gen(4711); std::uniform_int_distribution<> rand(0, size * 0.8); for (std::string const& base: bases) { std::vector<std::string> keys; keys.reserve(size); int i = 0; std::generate_n(std::back_inserter(keys), size, [i, &base, &rand, &gen]()mutable{ return base + std::to_string(rand(gen)); }); measure(context, keys, base.size()); } } // ---------------------------------------------------------------------------- int main(int ac, char* av[]) { cpu::tube::context context(CPUTUBE_CONTEXT_ARGS(ac, av)); int size(ac == 1? 0: atoi(av[1])); if (size) { run_tests(context, size); } else { for (int i(10); i <= 100000; i *= 10) { for (int j(1); j < 10; j *= 2) { run_tests(context, i * j); } } } }
dietmarkuehl/cputube
cpu/test/unique-strings.cpp
C++
mit
10,438
/* * Encog(tm) Core v3.1 - Java Version * http://www.heatonresearch.com/encog/ * http://code.google.com/p/encog-java/ * Copyright 2008-2012 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.plugin.system; import org.encog.EncogError; import org.encog.engine.network.activation.ActivationFunction; import org.encog.ml.MLMethod; import org.encog.ml.data.MLDataSet; import org.encog.ml.factory.MLTrainFactory; import org.encog.ml.factory.train.AnnealFactory; import org.encog.ml.factory.train.BackPropFactory; import org.encog.ml.factory.train.ClusterSOMFactory; import org.encog.ml.factory.train.GeneticFactory; import org.encog.ml.factory.train.LMAFactory; import org.encog.ml.factory.train.ManhattanFactory; import org.encog.ml.factory.train.NeighborhoodSOMFactory; import org.encog.ml.factory.train.NelderMeadFactory; import org.encog.ml.factory.train.PNNTrainFactory; import org.encog.ml.factory.train.PSOFactory; import org.encog.ml.factory.train.QuickPropFactory; import org.encog.ml.factory.train.RBFSVDFactory; import org.encog.ml.factory.train.RPROPFactory; import org.encog.ml.factory.train.SCGFactory; import org.encog.ml.factory.train.SVMFactory; import org.encog.ml.factory.train.SVMSearchFactory; import org.encog.ml.factory.train.TrainBayesianFactory; import org.encog.ml.train.MLTrain; import org.encog.plugin.EncogPluginBase; import org.encog.plugin.EncogPluginService1; public class SystemTrainingPlugin implements EncogPluginService1 { /** * The factory for K2 */ private final TrainBayesianFactory bayesianFactory = new TrainBayesianFactory(); /** * The factory for backprop. */ private final BackPropFactory backpropFactory = new BackPropFactory(); /** * The factory for LMA. */ private final LMAFactory lmaFactory = new LMAFactory(); /** * The factory for RPROP. */ private final RPROPFactory rpropFactory = new RPROPFactory(); /** * THe factory for basic SVM. */ private final SVMFactory svmFactory = new SVMFactory(); /** * The factory for SVM-Search. */ private final SVMSearchFactory svmSearchFactory = new SVMSearchFactory(); /** * The factory for SCG. */ private final SCGFactory scgFactory = new SCGFactory(); /** * The factory for simulated annealing. */ private final AnnealFactory annealFactory = new AnnealFactory(); /** * Nelder Mead Factory. */ private final NelderMeadFactory nmFactory = new NelderMeadFactory(); /** * The factory for neighborhood SOM. */ private final NeighborhoodSOMFactory neighborhoodFactory = new NeighborhoodSOMFactory(); /** * The factory for SOM cluster. */ private final ClusterSOMFactory somClusterFactory = new ClusterSOMFactory(); /** * The factory for genetic. */ private final GeneticFactory geneticFactory = new GeneticFactory(); /** * The factory for Manhattan networks. */ private final ManhattanFactory manhattanFactory = new ManhattanFactory(); /** * Factory for SVD. */ private final RBFSVDFactory svdFactory = new RBFSVDFactory(); /** * Factory for PNN. */ private final PNNTrainFactory pnnFactory = new PNNTrainFactory(); /** * Factory for quickprop. */ private final QuickPropFactory qpropFactory = new QuickPropFactory(); private final PSOFactory psoFactory = new PSOFactory(); /** * {@inheritDoc} */ @Override public final String getPluginDescription() { return "This plugin provides the built in training " + "methods for Encog."; } /** * {@inheritDoc} */ @Override public final String getPluginName() { return "HRI-System-Training"; } /** * @return This is a type-1 plugin. */ @Override public final int getPluginType() { return 1; } /** * This plugin does not support activation functions, so it will * always return null. * @return Null, because this plugin does not support activation functions. */ @Override public ActivationFunction createActivationFunction(String name) { return null; } @Override public MLMethod createMethod(String methodType, String architecture, int input, int output) { // TODO Auto-generated method stub return null; } @Override public MLTrain createTraining(MLMethod method, MLDataSet training, String type, String args) { String args2 = args; if (args2 == null) { args2 = ""; } if (MLTrainFactory.TYPE_RPROP.equalsIgnoreCase(type)) { return this.rpropFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_BACKPROP.equalsIgnoreCase(type)) { return this.backpropFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_SCG.equalsIgnoreCase(type)) { return this.scgFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_LMA.equalsIgnoreCase(type)) { return this.lmaFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_SVM.equalsIgnoreCase(type)) { return this.svmFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_SVM_SEARCH.equalsIgnoreCase(type)) { return this.svmSearchFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_SOM_NEIGHBORHOOD.equalsIgnoreCase( type)) { return this.neighborhoodFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_ANNEAL.equalsIgnoreCase(type)) { return this.annealFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_GENETIC.equalsIgnoreCase(type)) { return this.geneticFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_SOM_CLUSTER.equalsIgnoreCase(type)) { return this.somClusterFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_MANHATTAN.equalsIgnoreCase(type)) { return this.manhattanFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_SVD.equalsIgnoreCase(type)) { return this.svdFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_PNN.equalsIgnoreCase(type)) { return this.pnnFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_QPROP.equalsIgnoreCase(type)) { return this.qpropFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_BAYESIAN.equals(type) ) { return this.bayesianFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_NELDER_MEAD.equals(type) ) { return this.nmFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_PSO.equals(type) ) { return this.psoFactory.create(method, training, args2); } else { throw new EncogError("Unknown training type: " + type); } } /** * {@inheritDoc} */ @Override public int getPluginServiceType() { return EncogPluginBase.TYPE_SERVICE; } }
larhoy/SentimentProjectV2
SentimentAnalysisV2/encog-core-3.1.0/src/main/java/org/encog/plugin/system/SystemTrainingPlugin.java
Java
mit
7,358
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import './index.scss' import React, { Component } from 'react' // import { Grid, Col, Row } from 'react-bootstrap'; export default class IndexPage extends Component { render() { return ( <div className="top-page"> <div> <img className="top-image" src="/cover2.jpg" width="100%" alt="cover image" /> </div> <div className="top-page--footer"> The source code of this website is available&nbsp; <a href="https://github.com/odoruinu/odoruinu.net-pug" target="_blank" rel="noopener noreferrer" > here on GitHub </a> . </div> </div> ) } }
odoruinu/odoruinu.net-pug
pages/index.js
JavaScript
mit
908
# 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. # -------------------------------------------------------------------------- import pytest from os import path, remove, sys, urandom import platform import uuid from azure.storage.blob import ( BlobServiceClient, ContainerClient, BlobClient, ContentSettings ) if sys.version_info >= (3,): from io import BytesIO else: from cStringIO import StringIO as BytesIO from settings.testcase import BlobPreparer from devtools_testutils.storage import StorageTestCase # ------------------------------------------------------------------------------ TEST_BLOB_PREFIX = 'largeblob' LARGE_BLOB_SIZE = 12 * 1024 * 1024 LARGE_BLOCK_SIZE = 6 * 1024 * 1024 # ------------------------------------------------------------------------------ if platform.python_implementation() == 'PyPy': pytest.skip("Skip tests for Pypy", allow_module_level=True) class StorageLargeBlockBlobTest(StorageTestCase): def _setup(self, storage_account_name, key): # test chunking functionality by reducing the threshold # for chunking and the size of each chunk, otherwise # the tests would take too long to execute self.bsc = BlobServiceClient( self.account_url(storage_account_name, "blob"), credential=key, max_single_put_size=32 * 1024, max_block_size=2 * 1024 * 1024, min_large_block_upload_threshold=1 * 1024 * 1024) self.config = self.bsc._config self.container_name = self.get_resource_name('utcontainer') if self.is_live: try: self.bsc.create_container(self.container_name) except: pass def _teardown(self, file_name): if path.isfile(file_name): try: remove(file_name) except: pass # --Helpers----------------------------------------------------------------- def _get_blob_reference(self): return self.get_resource_name(TEST_BLOB_PREFIX) def _create_blob(self): blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) blob.upload_blob(b'') return blob def assertBlobEqual(self, container_name, blob_name, expected_data): blob = self.bsc.get_blob_client(container_name, blob_name) actual_data = blob.download_blob() self.assertEqual(b"".join(list(actual_data.chunks())), expected_data) # --Test cases for block blobs -------------------------------------------- @pytest.mark.live_test_only @BlobPreparer() def test_put_block_bytes_large(self, storage_account_name, storage_account_key): self._setup(storage_account_name, storage_account_key) blob = self._create_blob() # Act for i in range(5): resp = blob.stage_block( 'block {0}'.format(i).encode('utf-8'), urandom(LARGE_BLOCK_SIZE)) self.assertIsNotNone(resp) assert 'content_md5' in resp assert 'content_crc64' in resp assert 'request_id' in resp # Assert @pytest.mark.live_test_only @BlobPreparer() def test_put_block_bytes_large_with_md5(self, storage_account_name, storage_account_key): self._setup(storage_account_name, storage_account_key) blob = self._create_blob() # Act for i in range(5): resp = blob.stage_block( 'block {0}'.format(i).encode('utf-8'), urandom(LARGE_BLOCK_SIZE), validate_content=True) self.assertIsNotNone(resp) assert 'content_md5' in resp assert 'content_crc64' in resp assert 'request_id' in resp @pytest.mark.live_test_only @BlobPreparer() def test_put_block_stream_large(self, storage_account_name, storage_account_key): self._setup(storage_account_name, storage_account_key) blob = self._create_blob() # Act for i in range(5): stream = BytesIO(bytearray(LARGE_BLOCK_SIZE)) resp = resp = blob.stage_block( 'block {0}'.format(i).encode('utf-8'), stream, length=LARGE_BLOCK_SIZE) self.assertIsNotNone(resp) assert 'content_md5' in resp assert 'content_crc64' in resp assert 'request_id' in resp # Assert @pytest.mark.live_test_only @BlobPreparer() def test_put_block_stream_large_with_md5(self, storage_account_name, storage_account_key): self._setup(storage_account_name, storage_account_key) blob = self._create_blob() # Act for i in range(5): stream = BytesIO(bytearray(LARGE_BLOCK_SIZE)) resp = resp = blob.stage_block( 'block {0}'.format(i).encode('utf-8'), stream, length=LARGE_BLOCK_SIZE, validate_content=True) self.assertIsNotNone(resp) assert 'content_md5' in resp assert 'content_crc64' in resp assert 'request_id' in resp # Assert @pytest.mark.live_test_only @BlobPreparer() def test_create_large_blob_from_path(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = 'large_blob_from_path.temp.{}.dat'.format(str(uuid.uuid4())) with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, max_concurrency=2, overwrite=True) block_list = blob.get_block_list() # Assert self.assertIsNot(len(block_list), 0) self.assertBlobEqual(self.container_name, blob_name, data) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_create_large_blob_from_path_with_md5(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = "blob_from_path_with_md5.temp.dat" with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, validate_content=True, max_concurrency=2) # Assert self.assertBlobEqual(self.container_name, blob_name, data) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_create_large_blob_from_path_non_parallel(self, storage_account_name, storage_account_key): self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(self.get_random_bytes(100)) FILE_PATH = "blob_from_path_non_parallel.temp.dat" with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, max_concurrency=1) # Assert self.assertBlobEqual(self.container_name, blob_name, data) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_create_large_blob_from_path_with_progress(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = "blob_from_path_with_progress.temp.dat" with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act progress = [] def callback(response): current = response.context['upload_stream_current'] total = response.context['data_stream_total'] if current is not None: progress.append((current, total)) with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, max_concurrency=2, raw_response_hook=callback) # Assert self.assertBlobEqual(self.container_name, blob_name, data) self.assert_upload_progress(len(data), self.config.max_block_size, progress) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_create_large_blob_from_path_with_properties(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = 'blob_from_path_with_properties.temp.{}.dat'.format(str(uuid.uuid4())) with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act content_settings = ContentSettings( content_type='image/png', content_language='spanish') with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, content_settings=content_settings, max_concurrency=2) # Assert self.assertBlobEqual(self.container_name, blob_name, data) properties = blob.get_blob_properties() self.assertEqual(properties.content_settings.content_type, content_settings.content_type) self.assertEqual(properties.content_settings.content_language, content_settings.content_language) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_create_large_blob_from_stream_chunked_upload(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = 'blob_from_stream_chunked_upload.temp.{}.dat'.format(str(uuid.uuid4())) with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, max_concurrency=2) # Assert self.assertBlobEqual(self.container_name, blob_name, data) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_creat_lrgblob_frm_stream_w_progress_chnkd_upload(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = 'stream_w_progress_chnkd_upload.temp.{}.dat'.format(str(uuid.uuid4())) with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act progress = [] def callback(response): current = response.context['upload_stream_current'] total = response.context['data_stream_total'] if current is not None: progress.append((current, total)) with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, max_concurrency=2, raw_response_hook=callback) # Assert self.assertBlobEqual(self.container_name, blob_name, data) self.assert_upload_progress(len(data), self.config.max_block_size, progress) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_create_large_blob_from_stream_chunked_upload_with_count(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = 'chunked_upload_with_count.temp.{}.dat'.format(str(uuid.uuid4())) with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act blob_size = len(data) - 301 with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, length=blob_size, max_concurrency=2) # Assert self.assertBlobEqual(self.container_name, blob_name, data[:blob_size]) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_creat_lrgblob_frm_strm_chnkd_uplod_w_count_n_props(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = 'plod_w_count_n_props.temp.{}.dat'.format(str(uuid.uuid4())) with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act content_settings = ContentSettings( content_type='image/png', content_language='spanish') blob_size = len(data) - 301 with open(FILE_PATH, 'rb') as stream: blob.upload_blob( stream, length=blob_size, content_settings=content_settings, max_concurrency=2) # Assert self.assertBlobEqual(self.container_name, blob_name, data[:blob_size]) properties = blob.get_blob_properties() self.assertEqual(properties.content_settings.content_type, content_settings.content_type) self.assertEqual(properties.content_settings.content_language, content_settings.content_language) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_creat_lrg_blob_frm_stream_chnked_upload_w_props(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = 'creat_lrg_blob.temp.{}.dat'.format(str(uuid.uuid4())) with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act content_settings = ContentSettings( content_type='image/png', content_language='spanish') with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, content_settings=content_settings, max_concurrency=2) # Assert self.assertBlobEqual(self.container_name, blob_name, data) properties = blob.get_blob_properties() self.assertEqual(properties.content_settings.content_type, content_settings.content_type) self.assertEqual(properties.content_settings.content_language, content_settings.content_language) self._teardown(FILE_PATH) # ------------------------------------------------------------------------------
Azure/azure-sdk-for-python
sdk/storage/azure-storage-blob/tests/test_large_block_blob.py
Python
mit
16,306
package controllers; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Date; import models.Usuario; import play.Play; import play.mvc.*; import play.data.validation.*; import play.libs.*; import play.utils.*; public class Secure extends Controller { @Before(unless={"login", "authenticate", "logout"}) static void checkAccess() throws Throwable { // Authent if(!session.contains("username")) { flash.put("url", "GET".equals(request.method) ? request.url : Play.ctxPath + "/"); // seems a good default login(); } // Checks Check check = getActionAnnotation(Check.class); if(check != null) { check(check); } check = getControllerInheritedAnnotation(Check.class); if(check != null) { check(check); } } private static void check(Check check) throws Throwable { for(String profile : check.value()) { boolean hasProfile = (Boolean)Security.invoke("check", profile); if(!hasProfile) { Security.invoke("onCheckFailed", profile); } } } // ~~~ Login public static void login() throws Throwable { Http.Cookie remember = request.cookies.get("rememberme"); if(remember != null) { int firstIndex = remember.value.indexOf("-"); int lastIndex = remember.value.lastIndexOf("-"); if (lastIndex > firstIndex) { String sign = remember.value.substring(0, firstIndex); String restOfCookie = remember.value.substring(firstIndex + 1); String username = remember.value.substring(firstIndex + 1, lastIndex); String time = remember.value.substring(lastIndex + 1); Date expirationDate = new Date(Long.parseLong(time)); // surround with try/catch? Date now = new Date(); if (expirationDate == null || expirationDate.before(now)) { logout(); } if(Crypto.sign(restOfCookie).equals(sign)) { session.put("username", username); redirectToOriginalURL(); } } } flash.keep("url"); render(); } public static void authenticate(@Required String username, String password, boolean remember) throws Throwable { // Check tokens //Boolean allowed = false; Usuario usuario = Usuario.find("usuario = ? and clave = ?", username, password).first(); if(usuario != null){ //session.put("nombreCompleto", usuario.nombreCompleto); //session.put("idUsuario", usuario.id); //if(usuario.tienda != null){ //session.put("idTienda", usuario.id); //} //allowed = true; } else { flash.keep("url"); flash.error("secure.error"); params.flash(); login(); } /*try { // This is the deprecated method name allowed = (Boolean)Security.invoke("authenticate", username, password); } catch (UnsupportedOperationException e ) { // This is the official method name allowed = (Boolean)Security.invoke("authenticate", username, password); }*/ /*if(validation.hasErrors() || !allowed) { flash.keep("url"); flash.error("secure.error"); params.flash(); login(); }*/ // Mark user as connected session.put("username", username); // Remember if needed if(remember) { Date expiration = new Date(); String duration = "30d"; // maybe make this override-able expiration.setTime(expiration.getTime() + Time.parseDuration(duration)); response.setCookie("rememberme", Crypto.sign(username + "-" + expiration.getTime()) + "-" + username + "-" + expiration.getTime(), duration); } // Redirect to the original URL (or /) redirectToOriginalURL(); } public static void logout() throws Throwable { Security.invoke("onDisconnect"); session.clear(); response.removeCookie("rememberme"); Security.invoke("onDisconnected"); flash.success("secure.logout"); login(); } // ~~~ Utils static void redirectToOriginalURL() throws Throwable { Security.invoke("onAuthenticated"); String url = flash.get("url"); if(url == null) { url = Play.ctxPath + "/"; } redirect(url); } public static class Security extends Controller { /** * @Deprecated * * @param username * @param password * @return */ static boolean authentify(String username, String password) { throw new UnsupportedOperationException(); } /** * This method is called during the authentication process. This is where you check if * the user is allowed to log in into the system. This is the actual authentication process * against a third party system (most of the time a DB). * * @param username * @param password * @return true if the authentication process succeeded */ static boolean authenticate(String username, String password) { return true; } /** * This method checks that a profile is allowed to view this page/method. This method is called prior * to the method's controller annotated with the @Check method. * * @param profile * @return true if you are allowed to execute this controller method. */ static boolean check(String profile) { return true; } /** * This method returns the current connected username * @return */ static String connected() { return session.get("username"); } /** * Indicate if a user is currently connected * @return true if the user is connected */ static boolean isConnected() { return session.contains("username"); } /** * This method is called after a successful authentication. * You need to override this method if you with to perform specific actions (eg. Record the time the user signed in) */ static void onAuthenticated() { } /** * This method is called before a user tries to sign off. * You need to override this method if you wish to perform specific actions (eg. Record the name of the user who signed off) */ static void onDisconnect() { } /** * This method is called after a successful sign off. * You need to override this method if you wish to perform specific actions (eg. Record the time the user signed off) */ static void onDisconnected() { } /** * This method is called if a check does not succeed. By default it shows the not allowed page (the controller forbidden method). * @param profile */ static void onCheckFailed(String profile) { forbidden(); } private static Object invoke(String m, Object... args) throws Throwable { try { return Java.invokeChildOrStatic(Security.class, m, args); } catch(InvocationTargetException e) { throw e.getTargetException(); } } } }
marti1125/Project_Store
app/controllers/Secure.java
Java
mit
7,739
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import os import re import subprocess import sys from datetime import date import click import yaml from indico.util.console import cformat # Dictionary listing the files for which to change the header. # The key is the extension of the file (without the dot) and the value is another # dictionary containing two keys: # - 'regex' : A regular expression matching comments in the given file type # - 'format': A dictionary with the comment characters to add to the header. # There must be a `comment_start` inserted before the header, # `comment_middle` inserted at the beginning of each line except the # first and last one, and `comment_end` inserted at the end of the # header. (See the `HEADER` above) SUPPORTED_FILES = { 'py': { 'regex': re.compile(r'((^#|[\r\n]#).*)*'), 'format': {'comment_start': '#', 'comment_middle': '#', 'comment_end': ''}}, 'wsgi': { 'regex': re.compile(r'((^#|[\r\n]#).*)*'), 'format': {'comment_start': '#', 'comment_middle': '#', 'comment_end': ''}}, 'js': { 'regex': re.compile(r'/\*(.|[\r\n])*?\*/|((^//|[\r\n]//).*)*'), 'format': {'comment_start': '//', 'comment_middle': '//', 'comment_end': ''}}, 'jsx': { 'regex': re.compile(r'/\*(.|[\r\n])*?\*/|((^//|[\r\n]//).*)*'), 'format': {'comment_start': '//', 'comment_middle': '//', 'comment_end': ''}}, 'css': { 'regex': re.compile(r'/\*(.|[\r\n])*?\*/'), 'format': {'comment_start': '/*', 'comment_middle': ' *', 'comment_end': ' */'}}, 'scss': { 'regex': re.compile(r'/\*(.|[\r\n])*?\*/|((^//|[\r\n]//).*)*'), 'format': {'comment_start': '//', 'comment_middle': '//', 'comment_end': ''}}, } # The substring which must be part of a comment block in order for the comment to be updated by the header. SUBSTRING = 'This file is part of' USAGE = ''' Updates all the headers in the supported files ({supported_files}). By default, all the files tracked by git in the current repository are updated to the current year. You can specify a year to update to as well as a file or directory. This will update all the supported files in the scope including those not tracked by git. If the directory does not contain any supported files (or if the file specified is not supported) nothing will be updated. '''.format(supported_files=', '.join(SUPPORTED_FILES)).strip() def _walk_to_root(path): """Yield directories starting from the given directory up to the root.""" # Based on code from python-dotenv (BSD-licensed): # https://github.com/theskumar/python-dotenv/blob/e13d957b/src/dotenv/main.py#L245 if os.path.isfile(path): path = os.path.dirname(path) last_dir = None current_dir = os.path.abspath(path) while last_dir != current_dir: yield current_dir parent_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir)) last_dir, current_dir = current_dir, parent_dir def _get_config(path, end_year): config = {} for dirname in _walk_to_root(path): check_path = os.path.join(dirname, 'headers.yml') if os.path.isfile(check_path): with open(check_path) as f: config.update((k, v) for k, v in yaml.safe_load(f.read()).items() if k not in config) if config.pop('root', False): break if 'start_year' not in config: click.echo('no valid headers.yml files found: start_year missing') sys.exit(1) if 'name' not in config: click.echo('no valid headers.yml files found: name missing') sys.exit(1) if 'header' not in config: click.echo('no valid headers.yml files found: header missing') sys.exit(1) config['end_year'] = end_year return config def gen_header(data): if data['start_year'] == data['end_year']: data['dates'] = data['start_year'] else: data['dates'] = '{} - {}'.format(data['start_year'], data['end_year']) return '\n'.join(line.rstrip() for line in data['header'].format(**data).strip().splitlines()) def _update_header(file_path, config, substring, regex, data, ci): found = False with open(file_path) as file_read: content = orig_content = file_read.read() if not content.strip(): return False shebang_line = None if content.startswith('#!/'): shebang_line, content = content.split('\n', 1) for match in regex.finditer(content): if substring in match.group(): found = True content = content[:match.start()] + gen_header(data | config) + content[match.end():] if shebang_line: content = shebang_line + '\n' + content if content != orig_content: msg = 'Incorrect header in {}' if ci else cformat('%{green!}Updating header of %{blue!}{}') print(msg.format(os.path.relpath(file_path))) if not ci: with open(file_path, 'w') as file_write: file_write.write(content) return True elif not found: msg = 'Missing header in {}' if ci else cformat('%{red!}Missing header%{reset} in %{blue!}{}') print(msg.format(os.path.relpath(file_path))) return True def update_header(file_path, year, ci): config = _get_config(file_path, year) ext = file_path.rsplit('.', 1)[-1] if ext not in SUPPORTED_FILES or not os.path.isfile(file_path): return False if os.path.basename(file_path)[0] == '.': return False return _update_header(file_path, config, SUBSTRING, SUPPORTED_FILES[ext]['regex'], SUPPORTED_FILES[ext]['format'], ci) def blacklisted(root, path, _cache={}): orig_path = path if path not in _cache: _cache[orig_path] = False while (path + os.path.sep).startswith(root): if os.path.exists(os.path.join(path, '.no-headers')): _cache[orig_path] = True break path = os.path.normpath(os.path.join(path, '..')) return _cache[orig_path] @click.command(help=USAGE) @click.option('--ci', is_flag=True, help='Indicate that the script is running during CI and should use a non-zero ' 'exit code unless all headers were already up to date. This also prevents ' 'files from actually being updated.') @click.option('--year', '-y', type=click.IntRange(min=1000), default=date.today().year, metavar='YEAR', help='Indicate the target year') @click.option('--path', '-p', type=click.Path(exists=True), help='Restrict updates to a specific file or directory') @click.pass_context def main(ctx, ci, year, path): error = False if path and os.path.isdir(path): if not ci: print(cformat('Updating headers to the year %{yellow!}{year}%{reset} for all the files in ' '%{yellow!}{path}%{reset}...').format(year=year, path=path)) for root, _, filenames in os.walk(path): for filename in filenames: if not blacklisted(path, root): if update_header(os.path.join(root, filename), year, ci): error = True elif path and os.path.isfile(path): if not ci: print(cformat('Updating headers to the year %{yellow!}{year}%{reset} for the file ' '%{yellow!}{file}%{reset}...').format(year=year, file=path)) if update_header(path, year, ci): error = True else: if not ci: print(cformat('Updating headers to the year %{yellow!}{year}%{reset} for all ' 'git-tracked files...').format(year=year)) try: for filepath in subprocess.check_output(['git', 'ls-files'], text=True).splitlines(): filepath = os.path.abspath(filepath) if not blacklisted(os.getcwd(), os.path.dirname(filepath)): if update_header(filepath, year, ci): error = True except subprocess.CalledProcessError: raise click.UsageError(cformat('%{red!}You must be within a git repository to run this script.')) if not error: print(cformat('%{green}\u2705 All headers are up to date')) elif ci: print(cformat('%{red}\u274C Some headers need to be updated or added')) sys.exit(1) else: print(cformat('%{yellow}\U0001F504 Some headers have been updated (or are missing)')) if __name__ == '__main__': main()
ThiefMaster/indico
bin/maintenance/update_header.py
Python
mit
8,843
from django.shortcuts import redirect from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from paste.models import Paste, Language @csrf_exempt def add(request): print "jojo" if request.method == 'POST': language = request.POST['language'] content = request.POST['content'] try: lang = Language.objects.get(pk=language) except: print "lang not avalible", language lang = Language.objects.get(pk='txt') paste = Paste(content=content, language=lang) paste.save() paste = Paste.objects.latest() return HttpResponse(paste.pk, content_type='text/plain') else: return redirect('/api')
spezifanta/Paste-It
api/v01/views.py
Python
mit
749
module Ahoy module Stores class ActiveRecordStore < BaseStore def track_visit(options, &block) visit = visit_model.new do |v| v.id = ahoy.visit_id v.visitor_id = ahoy.visitor_id v.user = user if v.respond_to?(:user=) end set_visit_properties(visit) yield(visit) if block_given? begin visit.save! geocode(visit) rescue *unique_exception_classes # do nothing end end def track_event(name, properties, options, &block) event = event_model.new do |e| e.id = options[:id] e.visit_id = ahoy.visit_id e.visitor_id = ahoy.visitor_id e.user = user e.name = name properties.each do |name, value| e.properties.build(name: name, value: value) end end yield(event) if block_given? begin event.save! rescue *unique_exception_classes # do nothing end end def visit @visit ||= visit_model.where(id: ahoy.visit_id).first if ahoy.visit_id end protected def visit_model ::Visit end def event_model ::Ahoy::Event end end end end
littlebitselectronics/ahoy
lib/ahoy/stores/active_record_store.rb
Ruby
mit
1,335
import {extend} from 'lodash'; export default class User { /** * The User class * @class * @param {Object} user * @return {Object} A User */ constructor(user) { extend(this, user); console.log(this); } }
mpaarating/sports-thing-web
client/app/users/models/user.js
JavaScript
mit
236
using UnityEngine; using System.Collections; public class Intro : MonoBehaviour { public GameObject martin; public GameObject mrsStrump; public GameObject strumpFire; public Sprite sadMartin, slinkton, police, candles, houses, strumps; public Camera cam; // Use this for initialization void Start () { strumpFire.GetComponent<SpriteRenderer>().enabled = false; } // Update is called once per frame void Update () { if (Input.GetKeyDown ("space") || Input.GetMouseButtonDown (0)) Application.LoadLevel ("game"); float time = Time.timeSinceLevelLoad; if (time > 4.0F && time < 4.5F) { mrsStrump.transform.position = new Vector3(-13, 0, -5); } if (time > 4.5F && time < 4.6F) { mrsStrump.transform.position = new Vector3(-13, -1, -5); } if (time > 17.2F && time < 17.7F) { martin.transform.position = new Vector3(-11, 0, -5); } if (time > 17.7F && time < 17.8F) { martin.transform.position = new Vector3(-11, -1, -5); } if (time > 18.5F && time < 18.6F) { cam.transform.position = new Vector3(-4, 0, -10); } if (time > 18.6F && time < 18.7F) { martin.GetComponent<Rigidbody2D>().velocity = new Vector2(11, 0); martin.GetComponent<SpriteRenderer>().sprite = sadMartin; } if (time > 20.0F && time < 20.1F) { martin.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 0); martin.transform.position = new Vector3(5.8F, -2, -5); } if (time > 33.0F && time < 33.1F) { strumpFire.GetComponent<SpriteRenderer>().enabled = true; } if (time > 35.0F && time < 35.1F) { strumpFire.GetComponent<SpriteRenderer>().sprite = slinkton; } if (time > 37.7F && time < 37.8F) { strumpFire.GetComponent<SpriteRenderer>().sprite = police; } if (time > 39.2F && time < 39.3F) { strumpFire.GetComponent<SpriteRenderer>().sprite = candles; } if (time > 41.0F && time < 41.1F) { strumpFire.GetComponent<SpriteRenderer>().sprite = houses; } if (time > 42.5F && time < 42.6F) { strumpFire.GetComponent<SpriteRenderer>().sprite = strumps; } if (time > 43.5F && time < 43.6F) { strumpFire.GetComponent<SpriteRenderer>().enabled = false; } if (time > 51.5F) Application.LoadLevel ("game"); } }
Bonfanti/Platformer
S Run Ronald Strump/Assets/scripts/Intro.cs
C#
mit
2,199
module Parsers module Edi class IncomingTransaction attr_reader :errors def self.from_etf(etf, i_cache) incoming_transaction = new(etf) subscriber_policy_loop = etf.subscriber_loop.policy_loops.first find_policy = FindPolicy.new(incoming_transaction) policy = find_policy.by_subkeys({ :eg_id => subscriber_policy_loop.eg_id, :hios_plan_id => subscriber_policy_loop.hios_id }) person_loop_validator = PersonLoopValidator.new etf.people.each do |person_loop| person_loop_validator.validate(person_loop, incoming_transaction, policy) end policy_loop_validator = PolicyLoopValidator.new policy_loop_validator.validate(subscriber_policy_loop, incoming_transaction) incoming_transaction end def initialize(etf) @etf = etf @errors = [] end def valid? @errors.empty? end def import return unless valid? is_policy_term = false is_policy_cancel = false is_non_payment = false old_npt_flag = @policy.term_for_np @etf.people.each do |person_loop| begin enrollee = @policy.enrollee_for_member_id(person_loop.member_id) policy_loop = person_loop.policy_loops.first enrollee.c_id = person_loop.carrier_member_id enrollee.cp_id = policy_loop.id if(!@etf.is_shop? && policy_loop.action == :stop ) enrollee.coverage_status = 'inactive' enrollee.coverage_end = policy_loop.coverage_end if enrollee.subscriber? is_non_payment = person_loop.non_payment_change? if enrollee.coverage_start == enrollee.coverage_end is_policy_cancel = true policy_end_date = enrollee.coverage_end enrollee.policy.aasm_state = "canceled" enrollee.policy.term_for_np = is_non_payment enrollee.policy.save else is_policy_term = true policy_end_date = enrollee.coverage_end enrollee.policy.aasm_state = "terminated" enrollee.policy.term_for_np = is_non_payment enrollee.policy.save end end end rescue Exception puts @policy.eg_id puts person_loop.member_id raise $! end end save_val = @policy.save unless exempt_from_notification?(@policy, is_policy_cancel, is_policy_term, old_npt_flag == is_non_payment) Observers::PolicyUpdated.notify(@policy) end if is_policy_term # Broadcast the term reason_headers = if is_non_payment {:qualifying_reason => "urn:openhbx:terms:v1:benefit_maintenance#non_payment"} else {} end Amqp::EventBroadcaster.with_broadcaster do |eb| eb.broadcast( { :routing_key => "info.events.policy.terminated", :headers => { :resource_instance_uri => @policy.eg_id, :event_effective_date => @policy.policy_end.strftime("%Y%m%d"), :hbx_enrollment_ids => JSON.dump(@policy.hbx_enrollment_ids) }.merge(reason_headers) }, "") end elsif is_policy_cancel # Broadcast the cancel reason_headers = if is_non_payment {:qualifying_reason => "urn:openhbx:terms:v1:benefit_maintenance#non_payment"} else {} end Amqp::EventBroadcaster.with_broadcaster do |eb| eb.broadcast( { :routing_key => "info.events.policy.canceled", :headers => { :resource_instance_uri => @policy.eg_id, :event_effective_date => @policy.policy_end.strftime("%Y%m%d"), :hbx_enrollment_ids => JSON.dump(@policy.hbx_enrollment_ids) }.merge(reason_headers) }, "") end end save_val end def exempt_from_notification?(policy, is_cancel, is_term, npt_changed) return false if is_cancel return false if npt_changed return false unless is_term (policy.policy_end.day == 31) && (policy.policy_end.month == 12) end def policy_found(policy) @policy = policy end def termination_with_no_end_date(details) @errors << "File is a termination, but no or invalid end date is provided for a member: Member #{details[:member_id]}, Coverage End: #{details[:coverage_end_string]}" end def coverage_end_before_coverage_start(details) @errors << "Coverage end before coverage start: Member #{details[:member_id]}, coverage_start: #{details[:coverage_start]}, coverage_end: #{details[:coverage_end]}" end def term_or_cancel_for_2014_individual(details) @errors << "Cancel/Term issued on 2014 policy. Member #{details[:member_id]}, end date #{details[:date]}" end def effectuation_date_mismatch(details) @errors << "Effectuation date mismatch: member #{details[:member_id]}, enrollee start: #{details[:policy]}, effectuation start: #{details[:effectuation]}" end def indeterminate_policy_expiration(details) @errors << "Could not determine natural policy expiration date: member #{details[:member_id]}" end def termination_date_after_expiration(details) @errors << "Termination date after natural policy expiration: member #{details[:member_id]}, coverage end: #{details[:coverage_end]}, expiration_date: #{details[:expiration_date]}" end def policy_not_found(subkeys) @errors << "Policy not found. Details: #{subkeys}" end def plan_found(plan) @plan = plan end def plan_not_found(hios_id) @errors << "Plan not found. (hios id: #{hios_id})" end def carrier_found(carrier) @carrier = carrier end def carrier_not_found(fein) @errors << "Carrier not found. (fein: #{fein})" end def found_carrier_member_id(id) end def missing_carrier_member_id(person_loop) policy_loop = person_loop.policy_loops.first if(!policy_loop.canceled?) @errors << "Missing Carrier Member ID." end end def no_such_member(id) @errors << "Member not found in policy: #{id}" end def found_carrier_policy_id(id) end def missing_carrier_policy_id @errors << "Missing Carrier Policy ID." end def policy_id @policy ? @policy._id : nil end def carrier_id @carrier ? @carrier._id : nil end def employer_id @employer ? @employer._id : nil end end end end
dchbx/gluedb
app/models/parsers/edi/incoming_transaction.rb
Ruby
mit
7,194
exports._buildExclamationKeyObject = function (tuples) { var valueMap = {}; tuples.forEach(function (tuple) { valueMap['!' + tuple.value0] = tuple.value1; }); return valueMap; }; var templatePattern = /\$\{([^}]+)\}/g; exports._getTemplateVars = function (str) { return (str.match(templatePattern) || []).map(function (str) { return str.substring(2, str.length - 1); }); };
LiamGoodacre/purescript-template-strings
src/Data/TemplateString/TemplateString.js
JavaScript
mit
397
/** * @overview * API handler action creator * Takes a key-value -pair representing the event to handle as key and its respective * handler function as the value. * * Event-to-URL mapping is done in {@link ApiEventPaths}. * * @since 0.2.0 * @version 0.3.0 */ import { Seq, Map } from 'immutable'; import { createAction } from 'redux-actions'; import { Internal } from '../records'; import { ApiEventPaths } from '../constants'; import * as apiHandlerFns from '../actions/kcsapi'; /** * Ensure that the action handlers are mapped into {@link ApiHandler} records. * @type {Immutable.Iterable<any, any>} * @since 0.2.0 */ export const handlers = Seq.Keyed(ApiEventPaths) .flatMap((path, event) => Map.of(event, new Internal.ApiHandler({ path, event, handler: apiHandlerFns[event] }))); /** * A non-`Seq` version of the @see findEventSeq function. * @param {string} findPath * @returns {string} * @since 0.2.0 * @version 0.3.0 */ export const findEvent = (findPath) => { const pathRegex = new RegExp(`^${findPath}$`); return ApiEventPaths.findKey((path) => pathRegex.test(path)); }; /** * Create a `Seq` of action handlers that is in a usable form for the Redux application. * @type {Immutable.Iterable<any, any>} * @since 0.2.0 */ export const actionHandlers = Seq.Keyed(handlers) .flatMap((handlerRecord, event) => Map.of(event, createAction(event, handlerRecord.handler)));
rensouhou/dockyard-app
app/actions/api-actions.js
JavaScript
mit
1,532
// xParentN 2, Copyright 2005-2007 Olivier Spinelli // Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL function xParentN(e, n) { while (e && n--) e = e.parentNode; return e; }
sambaker/awe-core
test/x/lib/xparentn.js
JavaScript
mit
230
<?php /** * @file include/zot.php * @brief Hubzilla implementation of zot protocol. * * https://github.com/friendica/red/wiki/zot * https://github.com/friendica/red/wiki/Zot---A-High-Level-Overview * */ require_once('include/crypto.php'); require_once('include/items.php'); require_once('include/hubloc.php'); require_once('include/queue_fn.php'); require_once('include/perm_upgrade.php'); /** * @brief Generates a unique string for use as a zot guid. * * Generates a unique string for use as a zot guid using our DNS-based url, the * channel nickname and some entropy. * The entropy ensures uniqueness against re-installs where the same URL and * nickname are chosen. * * @note zot doesn't require this to be unique. Internally we use a whirlpool * hash of this guid and the signature of this guid signed with the channel * private key. This can be verified and should make the probability of * collision of the verified result negligible within the constraints of our * immediate universe. * * @param string $channel_nick a unique nickname of controlling entity * @returns string */ function zot_new_uid($channel_nick) { $rawstr = z_root() . '/' . $channel_nick . '.' . mt_rand(); return(base64url_encode(hash('whirlpool', $rawstr, true), true)); } /** * @brief Generates a portable hash identifier for a channel. * * Generates a portable hash identifier for the channel identified by $guid and * signed with $guid_sig. * * @note This ID is portable across the network but MUST be calculated locally * by verifying the signature and can not be trusted as an identity. * * @param string $guid * @param string $guid_sig */ function make_xchan_hash($guid, $guid_sig) { return base64url_encode(hash('whirlpool', $guid . $guid_sig, true)); } /** * @brief Given a zot hash, return all distinct hubs. * * This function is used in building the zot discovery packet and therefore * should only be used by channels which are defined on this hub. * * @param string $hash - xchan_hash * @returns array of hubloc (hub location structures) * * \b hubloc_id int * * \b hubloc_guid char(255) * * \b hubloc_guid_sig text * * \b hubloc_hash char(255) * * \b hubloc_addr char(255) * * \b hubloc_flags int * * \b hubloc_status int * * \b hubloc_url char(255) * * \b hubloc_url_sig text * * \b hubloc_host char(255) * * \b hubloc_callback char(255) * * \b hubloc_connect char(255) * * \b hubloc_sitekey text * * \b hubloc_updated datetime * * \b hubloc_connected datetime */ function zot_get_hublocs($hash) { /* Only search for active hublocs - e.g. those that haven't been marked deleted */ $ret = q("select * from hubloc where hubloc_hash = '%s' and hubloc_deleted = 0 order by hubloc_url ", dbesc($hash) ); return $ret; } /** * @brief Builds a zot notification packet. * * Builds a zot notification packet that you can either store in the queue with * a message array or call zot_zot to immediately zot it to the other side. * * @param array $channel * sender channel structure * @param string $type * packet type: one of 'ping', 'pickup', 'purge', 'refresh', 'force_refresh', 'notify', 'auth_check' * @param array $recipients * envelope information, array ( 'guid' => string, 'guid_sig' => string ); empty for public posts * @param string $remote_key * optional public site key of target hub used to encrypt entire packet * NOTE: remote_key and encrypted packets are required for 'auth_check' packets, optional for all others * @param string $secret * random string, required for packets which require verification/callback * e.g. 'pickup', 'purge', 'notify', 'auth_check'. Packet types 'ping', 'force_refresh', and 'refresh' do not require verification * @param string $extra * @returns string json encoded zot packet */ function zot_build_packet($channel, $type = 'notify', $recipients = null, $remote_key = null, $secret = null, $extra = null) { $data = array( 'type' => $type, 'sender' => array( 'guid' => $channel['channel_guid'], 'guid_sig' => base64url_encode(rsa_sign($channel['channel_guid'],$channel['channel_prvkey'])), 'url' => z_root(), 'url_sig' => base64url_encode(rsa_sign(z_root(),$channel['channel_prvkey'])), 'sitekey' => get_config('system','pubkey') ), 'callback' => '/post', 'version' => ZOT_REVISION ); if ($recipients) { for ($x = 0; $x < count($recipients); $x ++) unset($recipients[$x]['hash']); $data['recipients'] = $recipients; } if ($secret) { $data['secret'] = $secret; $data['secret_sig'] = base64url_encode(rsa_sign($secret,$channel['channel_prvkey'])); } if ($extra) { foreach ($extra as $k => $v) $data[$k] = $v; } logger('zot_build_packet: ' . print_r($data,true), LOGGER_DATA, LOG_DEBUG); // Hush-hush ultra top-secret mode if ($remote_key) { $data = crypto_encapsulate(json_encode($data),$remote_key); } return json_encode($data); } /** * @brief * * @see z_post_url() * * @param string $url * @param array $data * @return array see z_post_url() for returned data format */ function zot_zot($url, $data) { return z_post_url($url, array('data' => $data)); } /** * @brief Look up information about channel. * * @param string $webbie * does not have to be host qualified e.g. 'foo' is treated as 'foo\@thishub' * @param array $channel * (optional), if supplied permissions will be enumerated specifically for $channel * @param boolean $autofallback * fallback/failover to http if https connection cannot be established. Default is true. * * @return array see z_post_url() and \ref mod/zfinger.php */ function zot_finger($webbie, $channel = null, $autofallback = true) { if (strpos($webbie,'@') === false) { $address = $webbie; $host = App::get_hostname(); } else { $address = substr($webbie,0,strpos($webbie,'@')); $host = substr($webbie,strpos($webbie,'@')+1); } $xchan_addr = $address . '@' . $host; if ((! $address) || (! $xchan_addr)) { logger('zot_finger: no address :' . $webbie); return array('success' => false); } logger('using xchan_addr: ' . $xchan_addr, LOGGER_DATA, LOG_DEBUG); // potential issue here; the xchan_addr points to the primary hub. // The webbie we were called with may not, so it might not be found // unless we query for hubloc_addr instead of xchan_addr $r = q("select xchan.*, hubloc.* from xchan left join hubloc on xchan_hash = hubloc_hash where xchan_addr = '%s' and hubloc_primary = 1 limit 1", dbesc($xchan_addr) ); if ($r) { $url = $r[0]['hubloc_url']; if ($r[0]['hubloc_network'] && $r[0]['hubloc_network'] !== 'zot') { logger('zot_finger: alternate network: ' . $webbie); logger('url: '.$url.', net: '.var_export($r[0]['hubloc_network'],true), LOGGER_DATA, LOG_DEBUG); return array('success' => false); } } else { $url = 'https://' . $host; } $rhs = '/.well-known/zot-info'; $https = ((strpos($url,'https://') === 0) ? true : false); logger('zot_finger: ' . $address . ' at ' . $url, LOGGER_DEBUG); if ($channel) { $postvars = array( 'address' => $address, 'target' => $channel['channel_guid'], 'target_sig' => $channel['channel_guid_sig'], 'key' => $channel['channel_pubkey'] ); $result = z_post_url($url . $rhs,$postvars); if ((! $result['success']) && ($autofallback)) { if ($https) { logger('zot_finger: https failed. falling back to http'); $result = z_post_url('http://' . $host . $rhs,$postvars); } } } else { $rhs .= '?f=&address=' . urlencode($address); $result = z_fetch_url($url . $rhs); if ((! $result['success']) && ($autofallback)) { if ($https) { logger('zot_finger: https failed. falling back to http'); $result = z_fetch_url('http://' . $host . $rhs); } } } if (! $result['success']) logger('zot_finger: no results'); return $result; } /** * @brief Refreshes after permission changed or friending, etc. * * zot_refresh is typically invoked when somebody has changed permissions of a channel and they are notified * to fetch new permissions via a finger/discovery operation. This may result in a new connection * (abook entry) being added to a local channel and it may result in auto-permissions being granted. * * Friending in zot is accomplished by sending a refresh packet to a specific channel which indicates a * permission change has been made by the sender which affects the target channel. The hub controlling * the target channel does targetted discovery (a zot-finger request requesting permissions for the local * channel). These are decoded here, and if necessary and abook structure (addressbook) is created to store * the permissions assigned to this channel. * * Initially these abook structures are created with a 'pending' flag, so that no reverse permissions are * implied until this is approved by the owner channel. A channel can also auto-populate permissions in * return and send back a refresh packet of its own. This is used by forum and group communication channels * so that friending and membership in the channel's "club" is automatic. * * @param array $them => xchan structure of sender * @param array $channel => local channel structure of target recipient, required for "friending" operations * @param array $force default false * * @returns boolean true if successful, else false */ function zot_refresh($them, $channel = null, $force = false) { if (array_key_exists('xchan_network', $them) && ($them['xchan_network'] !== 'zot')) { logger('zot_refresh: not got zot. ' . $them['xchan_name']); return true; } logger('zot_refresh: them: ' . print_r($them,true), LOGGER_DATA, LOG_DEBUG); if ($channel) logger('zot_refresh: channel: ' . print_r($channel,true), LOGGER_DATA, LOG_DEBUG); $url = null; if ($them['hubloc_url']) { $url = $them['hubloc_url']; } else { $r = null; // if they re-installed the server we could end up with the wrong record - pointing to the old install. // We'll order by reverse id to try and pick off the newest one first and hopefully end up with the // correct hubloc. If this doesn't work we may have to re-write this section to try them all. if(array_key_exists('xchan_addr',$them) && $them['xchan_addr']) { $r = q("select hubloc_url, hubloc_primary from hubloc where hubloc_addr = '%s' order by hubloc_id desc", dbesc($them['xchan_addr']) ); } if(! $r) { $r = q("select hubloc_url, hubloc_primary from hubloc where hubloc_hash = '%s' order by hubloc_id desc", dbesc($them['xchan_hash']) ); } if ($r) { foreach ($r as $rr) { if (intval($rr['hubloc_primary'])) { $url = $rr['hubloc_url']; break; } } if (! $url) $url = $r[0]['hubloc_url']; } } if (! $url) { logger('zot_refresh: no url'); return false; } $token = random_string(); $postvars = array(); $postvars['token'] = $token; if($channel) { $postvars['target'] = $channel['channel_guid']; $postvars['target_sig'] = $channel['channel_guid_sig']; $postvars['key'] = $channel['channel_pubkey']; } if (array_key_exists('xchan_addr',$them) && $them['xchan_addr']) $postvars['address'] = $them['xchan_addr']; if (array_key_exists('xchan_hash',$them) && $them['xchan_hash']) $postvars['guid_hash'] = $them['xchan_hash']; if (array_key_exists('xchan_guid',$them) && $them['xchan_guid'] && array_key_exists('xchan_guid_sig',$them) && $them['xchan_guid_sig']) { $postvars['guid'] = $them['xchan_guid']; $postvars['guid_sig'] = $them['xchan_guid_sig']; } $rhs = '/.well-known/zot-info'; $result = z_post_url($url . $rhs,$postvars); logger('zot_refresh: zot-info: ' . print_r($result,true), LOGGER_DATA, LOG_DEBUG); if ($result['success']) { $j = json_decode($result['body'],true); if (! (($j) && ($j['success']))) { logger('zot_refresh: result not decodable'); return false; } $signed_token = ((is_array($j) && array_key_exists('signed_token',$j)) ? $j['signed_token'] : null); if($signed_token) { $valid = rsa_verify('token.' . $token,base64url_decode($signed_token),$j['key']); if(! $valid) { logger('invalid signed token: ' . $url . $rhs, LOGGER_NORMAL, LOG_ERR); return false; } } else { logger('No signed token from ' . $url . $rhs, LOGGER_NORMAL, LOG_WARNING); // after 2017-01-01 this will be a hard error unless you over-ride it. if((time() > 1483228800) && (! get_config('system','allow_unsigned_zotfinger'))) { return false; } } $x = import_xchan($j, (($force) ? UPDATE_FLAGS_FORCED : UPDATE_FLAGS_UPDATED)); if(! $x['success']) return false; if($channel) { if($j['permissions']['data']) { $permissions = crypto_unencapsulate(array( 'data' => $j['permissions']['data'], 'key' => $j['permissions']['key'], 'iv' => $j['permissions']['iv']), $channel['channel_prvkey']); if($permissions) $permissions = json_decode($permissions,true); logger('decrypted permissions: ' . print_r($permissions,true), LOGGER_DATA, LOG_DEBUG); } else $permissions = $j['permissions']; $connected_set = false; if($permissions && is_array($permissions)) { $old_read_stream_perm = get_abconfig($channel['channel_id'],$x['hash'],'their_perms','view_stream'); foreach($permissions as $k => $v) { set_abconfig($channel['channel_id'],$x['hash'],'their_perms',$k,$v); } } if(array_key_exists('profile',$j) && array_key_exists('next_birthday',$j['profile'])) { $next_birthday = datetime_convert('UTC','UTC',$j['profile']['next_birthday']); } else { $next_birthday = NULL_DATE; } $r = q("select * from abook where abook_xchan = '%s' and abook_channel = %d and abook_self = 0 limit 1", dbesc($x['hash']), intval($channel['channel_id']) ); if($r) { // connection exists // if the dob is the same as what we have stored (disregarding the year), keep the one // we have as we may have updated the year after sending a notification; and resetting // to the one we just received would cause us to create duplicated events. if(substr($r[0]['abook_dob'],5) == substr($next_birthday,5)) $next_birthday = $r[0]['abook_dob']; $y = q("update abook set abook_dob = '%s' where abook_xchan = '%s' and abook_channel = %d and abook_self = 0 ", dbescdate($next_birthday), dbesc($x['hash']), intval($channel['channel_id']) ); if(! $y) logger('abook update failed'); else { // if we were just granted read stream permission and didn't have it before, try to pull in some posts if((! $old_read_stream_perm) && (intval($permissions['view_stream']))) Zotlabs\Daemon\Master::Summon(array('Onepoll',$r[0]['abook_id'])); } } else { // new connection $my_perms = null; $automatic = false; $role = get_pconfig($channel['channel_id'],'system','permissions_role'); if($role) { $xx = \Zotlabs\Access\PermissionRoles::role_perms($role); if($xx['perms_auto']) { $automatic = true; $default_perms = $xx['perms_connect']; $my_perms = \Zotlabs\Access\Permissions::FilledPerms($default_perms); } } if(! $my_perms) { $m = \Zotlabs\Access\Permissions::FilledAutoperms($channel['channel_id']); if($m) { $automatic = true; $my_perms = $m; } } if($my_perms) { foreach($my_perms as $k => $v) { set_abconfig($channel['channel_id'],$x['hash'],'my_perms',$k,$v); } } // Keep original perms to check if we need to notify them $previous_perms = get_all_perms($channel['channel_id'],$x['hash']); $closeness = get_pconfig($channel['channel_id'],'system','new_abook_closeness'); if($closeness === false) $closeness = 80; $y = q("insert into abook ( abook_account, abook_channel, abook_closeness, abook_xchan, abook_created, abook_updated, abook_dob, abook_pending ) values ( %d, %d, %d, '%s', '%s', '%s', '%s', %d )", intval($channel['channel_account_id']), intval($channel['channel_id']), intval($closeness), dbesc($x['hash']), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc($next_birthday), intval(($automatic) ? 0 : 1) ); if($y) { logger("New introduction received for {$channel['channel_name']}"); $new_perms = get_all_perms($channel['channel_id'],$x['hash']); // Send a clone sync packet and a permissions update if permissions have changed $new_connection = q("select * from abook left join xchan on abook_xchan = xchan_hash where abook_xchan = '%s' and abook_channel = %d and abook_self = 0 order by abook_created desc limit 1", dbesc($x['hash']), intval($channel['channel_id']) ); if($new_connection) { if(! \Zotlabs\Access\Permissions::PermsCompare($new_perms,$previous_perms)) Zotlabs\Daemon\Master::Summon(array('Notifier','permission_create',$new_connection[0]['abook_id'])); Zotlabs\Lib\Enotify::submit(array( 'type' => NOTIFY_INTRO, 'from_xchan' => $x['hash'], 'to_xchan' => $channel['channel_hash'], 'link' => z_root() . '/connedit/' . $new_connection[0]['abook_id'], )); if(intval($permissions['view_stream'])) { if(intval(get_pconfig($channel['channel_id'],'perm_limits','send_stream') & PERMS_PENDING) || (! intval($new_connection[0]['abook_pending']))) Zotlabs\Daemon\Master::Summon(array('Onepoll',$new_connection[0]['abook_id'])); } /** If there is a default group for this channel, add this connection to it */ $default_group = $channel['channel_default_group']; if($default_group) { require_once('include/group.php'); $g = group_rec_byhash($channel['channel_id'],$default_group); if($g) group_add_member($channel['channel_id'],'',$x['hash'],$g['id']); } unset($new_connection[0]['abook_id']); unset($new_connection[0]['abook_account']); unset($new_connection[0]['abook_channel']); $abconfig = load_abconfig($channel['channel_id'],$new_connection['abook_xchan']); if($abconfig) $new_connection['abconfig'] = $abconfig; build_sync_packet($channel['channel_id'], array('abook' => $new_connection)); } } } } return true; } return false; } /** * @brief Look up if channel is known and previously verified. * * A guid and a url, both signed by the sender, distinguish a known sender at a * known location. * This function looks these up to see if the channel is known and therefore * previously verified. If not, we will need to verify it. * * @param array $arr an associative array which must contain: * * \e string \b guid => guid of conversant * * \e string \b guid_sig => guid signed with conversant's private key * * \e string \b url => URL of the origination hub of this communication * * \e string \b url_sig => URL signed with conversant's private key * * @returns array|null null if site is blacklisted or not found, otherwise an * array with an hubloc record */ function zot_gethub($arr,$multiple = false) { if($arr['guid'] && $arr['guid_sig'] && $arr['url'] && $arr['url_sig']) { if(! check_siteallowed($arr['url'])) { logger('blacklisted site: ' . $arr['url']); return null; } $limit = (($multiple) ? '' : ' limit 1 '); $sitekey = ((array_key_exists('sitekey',$arr) && $arr['sitekey']) ? " and hubloc_sitekey = '" . protect_sprintf($arr['sitekey']) . "' " : ''); $r = q("select * from hubloc where hubloc_guid = '%s' and hubloc_guid_sig = '%s' and hubloc_url = '%s' and hubloc_url_sig = '%s' $sitekey $limit", dbesc($arr['guid']), dbesc($arr['guid_sig']), dbesc($arr['url']), dbesc($arr['url_sig']) ); if($r) { logger('zot_gethub: found', LOGGER_DEBUG); return (($multiple) ? $r : $r[0]); } } logger('zot_gethub: not found: ' . print_r($arr,true), LOGGER_DEBUG); return null; } /** * @brief Registers an unknown hub. * * A communication has been received which has an unknown (to us) sender. * Perform discovery based on our calculated hash of the sender at the * origination address. This will fetch the discovery packet of the sender, * which contains the public key we need to verify our guid and url signatures. * * @param array $arr an associative array which must contain: * * \e string \b guid => guid of conversant * * \e string \b guid_sig => guid signed with conversant's private key * * \e string \b url => URL of the origination hub of this communication * * \e string \b url_sig => URL signed with conversant's private key * * @returns array an associative array with * * \b success boolean true or false * * \b message (optional) error string only if success is false */ function zot_register_hub($arr) { $result = array('success' => false); if($arr['url'] && $arr['url_sig'] && $arr['guid'] && $arr['guid_sig']) { $guid_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']); $url = $arr['url'] . '/.well-known/zot-info/?f=&guid_hash=' . $guid_hash; logger('zot_register_hub: ' . $url, LOGGER_DEBUG); $x = z_fetch_url($url); logger('zot_register_hub: ' . print_r($x,true), LOGGER_DATA, LOG_DEBUG); if($x['success']) { $record = json_decode($x['body'],true); /* * We now have a key - only continue registration if our signatures are valid * AND the guid and guid sig in the returned packet match those provided in * our current communication. */ if((rsa_verify($arr['guid'],base64url_decode($arr['guid_sig']),$record['key'])) && (rsa_verify($arr['url'],base64url_decode($arr['url_sig']),$record['key'])) && ($arr['guid'] === $record['guid']) && ($arr['guid_sig'] === $record['guid_sig'])) { $c = import_xchan($record); if($c['success']) $result['success'] = true; } else { logger('zot_register_hub: failure to verify returned packet.'); } } } return $result; } /** * @brief Takes an associative array of a fetched discovery packet and updates * all internal data structures which need to be updated as a result. * * @param array $arr => json_decoded discovery packet * @param int $ud_flags * Determines whether to create a directory update record if any changes occur, default is UPDATE_FLAGS_UPDATED * $ud_flags = UPDATE_FLAGS_FORCED indicates a forced refresh where we unconditionally create a directory update record * this typically occurs once a month for each channel as part of a scheduled ping to notify the directory * that the channel still exists * @param array $ud_arr * If set [typically by update_directory_entry()] indicates a specific update table row and more particularly * contains a particular address (ud_addr) which needs to be updated in that table. * * @return associative array * * \e boolean \b success boolean true or false * * \e string \b message (optional) error string only if success is false */ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { call_hooks('import_xchan', $arr); $ret = array('success' => false); $dirmode = intval(get_config('system','directory_mode')); $changed = false; $what = ''; if(! (is_array($arr) && array_key_exists('success',$arr) && $arr['success'])) { logger('import_xchan: invalid data packet: ' . print_r($arr,true)); $ret['message'] = t('Invalid data packet'); return $ret; } if(! ($arr['guid'] && $arr['guid_sig'])) { logger('import_xchan: no identity information provided. ' . print_r($arr,true)); return $ret; } $xchan_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']); $arr['hash'] = $xchan_hash; $import_photos = false; if(! rsa_verify($arr['guid'],base64url_decode($arr['guid_sig']),$arr['key'])) { logger('import_xchan: Unable to verify channel signature for ' . $arr['address']); $ret['message'] = t('Unable to verify channel signature'); return $ret; } logger('import_xchan: ' . $xchan_hash, LOGGER_DEBUG); $r = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($xchan_hash) ); if(! array_key_exists('connect_url', $arr)) $arr['connect_url'] = ''; if(strpos($arr['address'],'/') !== false) $arr['address'] = substr($arr['address'],0,strpos($arr['address'],'/')); if($r) { if($r[0]['xchan_photo_date'] != $arr['photo_updated']) $import_photos = true; // if we import an entry from a site that's not ours and either or both of us is off the grid - hide the entry. /** @TODO: check if we're the same directory realm, which would mean we are allowed to see it */ $dirmode = get_config('system','directory_mode'); if((($arr['site']['directory_mode'] === 'standalone') || ($dirmode & DIRECTORY_MODE_STANDALONE)) && ($arr['site']['url'] != z_root())) $arr['searchable'] = false; $hidden = (1 - intval($arr['searchable'])); $hidden_changed = $adult_changed = $deleted_changed = $pubforum_changed = 0; if(intval($r[0]['xchan_hidden']) != (1 - intval($arr['searchable']))) $hidden_changed = 1; if(intval($r[0]['xchan_selfcensored']) != intval($arr['adult_content'])) $adult_changed = 1; if(intval($r[0]['xchan_deleted']) != intval($arr['deleted'])) $deleted_changed = 1; if(intval($r[0]['xchan_pubforum']) != intval($arr['public_forum'])) $pubforum_changed = 1; if(($r[0]['xchan_name_date'] != $arr['name_updated']) || ($r[0]['xchan_connurl'] != $arr['connections_url']) || ($r[0]['xchan_addr'] != $arr['address']) || ($r[0]['xchan_follow'] != $arr['follow_url']) || ($r[0]['xchan_connpage'] != $arr['connect_url']) || ($r[0]['xchan_url'] != $arr['url']) || $hidden_changed || $adult_changed || $deleted_changed || $pubforum_changed ) { $rup = q("update xchan set xchan_name = '%s', xchan_name_date = '%s', xchan_connurl = '%s', xchan_follow = '%s', xchan_connpage = '%s', xchan_hidden = %d, xchan_selfcensored = %d, xchan_deleted = %d, xchan_pubforum = %d, xchan_addr = '%s', xchan_url = '%s' where xchan_hash = '%s'", dbesc(($arr['name']) ? $arr['name'] : '-'), dbesc($arr['name_updated']), dbesc($arr['connections_url']), dbesc($arr['follow_url']), dbesc($arr['connect_url']), intval(1 - intval($arr['searchable'])), intval($arr['adult_content']), intval($arr['deleted']), intval($arr['public_forum']), dbesc($arr['address']), dbesc($arr['url']), dbesc($xchan_hash) ); logger('import_xchan: update: existing: ' . print_r($r[0],true), LOGGER_DATA, LOG_DEBUG); logger('import_xchan: update: new: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); $what .= 'xchan '; $changed = true; } } else { $import_photos = true; if((($arr['site']['directory_mode'] === 'standalone') || ($dirmode & DIRECTORY_MODE_STANDALONE)) && ($arr['site']['url'] != z_root())) $arr['searchable'] = false; $x = q("insert into xchan ( xchan_hash, xchan_guid, xchan_guid_sig, xchan_pubkey, xchan_photo_mimetype, xchan_photo_l, xchan_addr, xchan_url, xchan_connurl, xchan_follow, xchan_connpage, xchan_name, xchan_network, xchan_photo_date, xchan_name_date, xchan_hidden, xchan_selfcensored, xchan_deleted, xchan_pubforum ) values ( '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d) ", dbesc($xchan_hash), dbesc($arr['guid']), dbesc($arr['guid_sig']), dbesc($arr['key']), dbesc($arr['photo_mimetype']), dbesc($arr['photo']), dbesc($arr['address']), dbesc($arr['url']), dbesc($arr['connections_url']), dbesc($arr['follow_url']), dbesc($arr['connect_url']), dbesc(($arr['name']) ? $arr['name'] : '-'), dbesc('zot'), dbescdate($arr['photo_updated']), dbescdate($arr['name_updated']), intval(1 - intval($arr['searchable'])), intval($arr['adult_content']), intval($arr['deleted']), intval($arr['public_forum']) ); $what .= 'new_xchan'; $changed = true; } if ($import_photos) { require_once('include/photo/photo_driver.php'); // see if this is a channel clone that's hosted locally - which we treat different from other xchans/connections $local = q("select channel_account_id, channel_id from channel where channel_hash = '%s' limit 1", dbesc($xchan_hash) ); if ($local) { $ph = z_fetch_url($arr['photo'], true); if ($ph['success']) { $hash = import_channel_photo($ph['body'], $arr['photo_mimetype'], $local[0]['channel_account_id'], $local[0]['channel_id']); if($hash) { // unless proven otherwise $is_default_profile = 1; $profile = q("select is_default from profile where aid = %d and uid = %d limit 1", intval($local[0]['channel_account_id']), intval($local[0]['channel_id']) ); if($profile) { if(! intval($profile[0]['is_default'])) $is_default_profile = 0; } // If setting for the default profile, unset the profile photo flag from any other photos I own if($is_default_profile) { q("UPDATE photo SET photo_usage = %d WHERE photo_usage = %d AND resource_id != '%s' AND aid = %d AND uid = %d", intval(PHOTO_NORMAL), intval(PHOTO_PROFILE), dbesc($hash), intval($local[0]['channel_account_id']), intval($local[0]['channel_id']) ); } } // reset the names in case they got messed up when we had a bug in this function $photos = array( z_root() . '/photo/profile/l/' . $local[0]['channel_id'], z_root() . '/photo/profile/m/' . $local[0]['channel_id'], z_root() . '/photo/profile/s/' . $local[0]['channel_id'], $arr['photo_mimetype'], false ); } } else { $photos = import_xchan_photo($arr['photo'], $xchan_hash); } if ($photos) { if ($photos[4]) { // importing the photo failed somehow. Leave the photo_date alone so we can try again at a later date. // This often happens when somebody joins the matrix with a bad cert. $r = q("update xchan set xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_hash = '%s'", dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), dbesc($photos[3]), dbesc($xchan_hash) ); } else { $r = q("update xchan set xchan_photo_date = '%s', xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_hash = '%s'", dbescdate(datetime_convert('UTC','UTC',$arr['photo_updated'])), dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), dbesc($photos[3]), dbesc($xchan_hash) ); } $what .= 'photo '; $changed = true; } } // what we are missing for true hub independence is for any changes in the primary hub to // get reflected not only in the hublocs, but also to update the URLs and addr in the appropriate xchan $s = sync_locations($arr, $arr); if($s) { if($s['change_message']) $what .= $s['change_message']; if($s['changed']) $changed = $s['changed']; if($s['message']) $ret['message'] .= $s['message']; } // Which entries in the update table are we interested in updating? $address = (($ud_arr && $ud_arr['ud_addr']) ? $ud_arr['ud_addr'] : $arr['address']); // Are we a directory server of some kind? $other_realm = false; $realm = get_directory_realm(); if(array_key_exists('site',$arr) && array_key_exists('realm',$arr['site']) && (strpos($arr['site']['realm'],$realm) === false)) $other_realm = true; if($dirmode != DIRECTORY_MODE_NORMAL) { // We're some kind of directory server. However we can only add directory information // if the entry is in the same realm (or is a sub-realm). Sub-realms are denoted by // including the parent realm in the name. e.g. 'RED_GLOBAL:foo' would allow an entry to // be in directories for the local realm (foo) and also the RED_GLOBAL realm. if(array_key_exists('profile',$arr) && is_array($arr['profile']) && (! $other_realm)) { $profile_changed = import_directory_profile($xchan_hash,$arr['profile'],$address,$ud_flags, 1); if($profile_changed) { $what .= 'profile '; $changed = true; } } else { logger('import_xchan: profile not available - hiding'); // they may have made it private $r = q("delete from xprof where xprof_hash = '%s'", dbesc($xchan_hash) ); $r = q("delete from xtag where xtag_hash = '%s' and xtag_flags = 0", dbesc($xchan_hash) ); } } if(array_key_exists('site',$arr) && is_array($arr['site'])) { $profile_changed = import_site($arr['site'],$arr['key']); if($profile_changed) { $what .= 'site '; $changed = true; } } if(($changed) || ($ud_flags == UPDATE_FLAGS_FORCED)) { $guid = random_string() . '@' . App::get_hostname(); update_modtime($xchan_hash,$guid,$address,$ud_flags); logger('import_xchan: changed: ' . $what,LOGGER_DEBUG); } elseif(! $ud_flags) { // nothing changed but we still need to update the updates record q("update updates set ud_flags = ( ud_flags | %d ) where ud_addr = '%s' and not (ud_flags & %d)>0 ", intval(UPDATE_FLAGS_UPDATED), dbesc($address), intval(UPDATE_FLAGS_UPDATED) ); } if(! x($ret,'message')) { $ret['success'] = true; $ret['hash'] = $xchan_hash; } logger('import_xchan: result: ' . print_r($ret,true), LOGGER_DATA, LOG_DEBUG); return $ret; } /** * @brief Called immediately after sending a zot message which is using queue processing. * * Updates the queue item according to the response result and logs any information * returned to aid communications troubleshooting. * * @param string $hub - url of site we just contacted * @param array $arr - output of z_post_url() * @param array $outq - The queue structure attached to this request */ function zot_process_response($hub, $arr, $outq) { if (! $arr['success']) { logger('zot_process_response: failed: ' . $hub); return; } $x = json_decode($arr['body'], true); if (! $x) { logger('zot_process_response: No json from ' . $hub); logger('zot_process_response: headers: ' . print_r($arr['header'],true), LOGGER_DATA, LOG_DEBUG); } if(is_array($x) && array_key_exists('delivery_report',$x) && is_array($x['delivery_report'])) { foreach($x['delivery_report'] as $xx) { if(is_array($xx) && array_key_exists('message_id',$xx) && delivery_report_is_storable($xx)) { q("insert into dreport ( dreport_mid, dreport_site, dreport_recip, dreport_result, dreport_time, dreport_xchan ) values ( '%s', '%s','%s','%s','%s','%s' ) ", dbesc($xx['message_id']), dbesc($xx['location']), dbesc($xx['recipient']), dbesc($xx['status']), dbesc(datetime_convert($xx['date'])), dbesc($xx['sender']) ); } } } // we have a more descriptive delivery report, so discard the per hub 'queued' report. q("delete from dreport where dreport_queue = '%s' ", dbesc($outq['outq_hash']) ); // update the timestamp for this site q("update site set site_dead = 0, site_update = '%s' where site_url = '%s'", dbesc(datetime_convert()), dbesc(dirname($hub)) ); // synchronous message types are handled immediately // async messages remain in the queue until processed. if(intval($outq['outq_async'])) remove_queue_item($outq['outq_hash'],$outq['outq_channel']); logger('zot_process_response: ' . print_r($x,true), LOGGER_DEBUG); } /** * @brief * * We received a notification packet (in mod_post) that a message is waiting for us, and we've verified the sender. * Now send back a pickup message, using our message tracking ID ($arr['secret']), which we will sign with our site * private key. * The entire pickup message is encrypted with the remote site's public key. * If everything checks out on the remote end, we will receive back a packet containing one or more messages, * which will be processed and delivered before this function ultimately returns. * * @see zot_import() * * @param array $arr * decrypted and json decoded notify packet from remote site * @return array from zot_import() */ function zot_fetch($arr) { logger('zot_fetch: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); $url = $arr['sender']['url'] . $arr['callback']; // set $multiple param on zot_gethub() to return all matching hubs // This allows us to recover from re-installs when a redundant (but invalid) hubloc for // this identity is widely dispersed throughout the network. $ret_hubs = zot_gethub($arr['sender'],true); if(! $ret_hubs) { logger('zot_fetch: no hub: ' . print_r($arr['sender'],true)); return; } foreach($ret_hubs as $ret_hub) { $data = array( 'type' => 'pickup', 'url' => z_root(), 'callback_sig' => base64url_encode(rsa_sign(z_root() . '/post',get_config('system','prvkey'))), 'callback' => z_root() . '/post', 'secret' => $arr['secret'], 'secret_sig' => base64url_encode(rsa_sign($arr['secret'],get_config('system','prvkey'))) ); $datatosend = json_encode(crypto_encapsulate(json_encode($data),$ret_hub['hubloc_sitekey'])); $fetch = zot_zot($url,$datatosend); $result = zot_import($fetch, $arr['sender']['url']); if($result) return $result; } return; } /** * @brief Process incoming array of messages. * * Process an incoming array of messages which were obtained via pickup, and * import, update, delete as directed. * * The message types handled here are 'activity' (e.g. posts), 'mail' , * 'profile', 'location' and 'channel_sync'. * * @param array $arr * 'pickup' structure returned from remote site * @param string $sender_url * the url specified by the sender in the initial communication. * We will verify the sender and url in each returned message structure and * also verify that all the messages returned match the site url that we are * currently processing. * * @returns array * suitable for logging remotely, enumerating the processing results of each message/recipient combination * * [0] => \e string $channel_hash * * [1] => \e string $delivery_status * * [2] => \e string $address */ function zot_import($arr, $sender_url) { $data = json_decode($arr['body'], true); if(! $data) { logger('zot_import: empty body'); return array(); } if(array_key_exists('iv', $data)) { $data = json_decode(crypto_unencapsulate($data,get_config('system','prvkey')),true); } if(! $data['success']) { if($data['message']) logger('remote pickup failed: ' . $data['message']); return false; } $incoming = $data['pickup']; $return = array(); if(is_array($incoming)) { foreach($incoming as $i) { if(! is_array($i)) { logger('incoming is not an array'); continue; } $result = null; if(array_key_exists('iv',$i['notify'])) { $i['notify'] = json_decode(crypto_unencapsulate($i['notify'],get_config('system','prvkey')),true); } logger('zot_import: notify: ' . print_r($i['notify'],true), LOGGER_DATA, LOG_DEBUG); $hub = zot_gethub($i['notify']['sender']); if((! $hub) || ($hub['hubloc_url'] != $sender_url)) { logger('zot_import: potential forgery: wrong site for sender: ' . $sender_url . ' != ' . print_r($i['notify'],true)); continue; } $message_request = ((array_key_exists('message_id',$i['notify'])) ? true : false); if($message_request) logger('processing message request'); $i['notify']['sender']['hash'] = make_xchan_hash($i['notify']['sender']['guid'],$i['notify']['sender']['guid_sig']); $deliveries = null; if(array_key_exists('message',$i) && array_key_exists('type',$i['message']) && $i['message']['type'] === 'rating') { // rating messages are processed only by directory servers logger('Rating received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); $result = process_rating_delivery($i['notify']['sender'],$i['message']); continue; } if(array_key_exists('recipients',$i['notify']) && count($i['notify']['recipients'])) { logger('specific recipients'); $recip_arr = array(); foreach($i['notify']['recipients'] as $recip) { if(is_array($recip)) { $recip_arr[] = make_xchan_hash($recip['guid'],$recip['guid_sig']); } } $r = false; if($recip_arr) { stringify_array_elms($recip_arr); $recips = implode(',',$recip_arr); $r = q("select channel_hash as hash from channel where channel_hash in ( " . $recips . " ) and channel_removed = 0 "); } if(! $r) { logger('recips: no recipients on this site'); continue; } // It's a specifically targetted post. If we were sent a public_scope hint (likely), // get rid of it so that it doesn't get stored and cause trouble. if(($i) && is_array($i) && array_key_exists('message',$i) && is_array($i['message']) && $i['message']['type'] === 'activity' && array_key_exists('public_scope',$i['message'])) unset($i['message']['public_scope']); $deliveries = $r; // We found somebody on this site that's in the recipient list. } else { if(($i['message']) && (array_key_exists('flags',$i['message'])) && (in_array('private',$i['message']['flags'])) && $i['message']['type'] === 'activity') { if(array_key_exists('public_scope',$i['message']) && $i['message']['public_scope'] === 'public') { // This should not happen but until we can stop it... logger('private message was delivered with no recipients.'); continue; } } logger('public post'); // Public post. look for any site members who are or may be accepting posts from this sender // and who are allowed to see them based on the sender's permissions $deliveries = allowed_public_recips($i); if($i['message'] && array_key_exists('type',$i['message']) && $i['message']['type'] === 'location') { $sys = get_sys_channel(); $deliveries = array(array('hash' => $sys['xchan_hash'])); } // if the scope is anything but 'public' we're going to store it as private regardless // of the private flag on the post. if($i['message'] && array_key_exists('public_scope',$i['message']) && $i['message']['public_scope'] !== 'public') { if(! array_key_exists('flags',$i['message'])) $i['message']['flags'] = array(); if(! in_array('private',$i['message']['flags'])) $i['message']['flags'][] = 'private'; } } // Go through the hash array and remove duplicates. array_unique() won't do this because the array is more than one level. $no_dups = array(); if($deliveries) { foreach($deliveries as $d) { if(! is_array($d)) { logger('Delivery hash array is not an array: ' . print_r($d,true)); continue; } if(! in_array($d['hash'],$no_dups)) $no_dups[] = $d['hash']; } if($no_dups) { $deliveries = array(); foreach($no_dups as $n) { $deliveries[] = array('hash' => $n); } } } if(! $deliveries) { logger('zot_import: no deliveries on this site'); continue; } if($i['message']) { if($i['message']['type'] === 'activity') { $arr = get_item_elements($i['message']); $v = validate_item_elements($i['message'],$arr); if(! $v['success']) { logger('Activity rejected: ' . $v['message'] . ' ' . print_r($i['message'],true)); continue; } logger('Activity received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); logger('Activity recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); $relay = ((array_key_exists('flags',$i['message']) && in_array('relay',$i['message']['flags'])) ? true : false); $result = process_delivery($i['notify']['sender'],$arr,$deliveries,$relay,false,$message_request); } elseif($i['message']['type'] === 'mail') { $arr = get_mail_elements($i['message']); logger('Mail received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); logger('Mail recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); $result = process_mail_delivery($i['notify']['sender'],$arr,$deliveries); } elseif($i['message']['type'] === 'profile') { $arr = get_profile_elements($i['message']); logger('Profile received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); logger('Profile recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); $result = process_profile_delivery($i['notify']['sender'],$arr,$deliveries); } elseif($i['message']['type'] === 'channel_sync') { // $arr = get_channelsync_elements($i['message']); $arr = $i['message']; logger('Channel sync received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); logger('Channel sync recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); $result = process_channel_sync_delivery($i['notify']['sender'],$arr,$deliveries); } elseif($i['message']['type'] === 'location') { $arr = $i['message']; logger('Location message received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); logger('Location message recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); $result = process_location_delivery($i['notify']['sender'],$arr,$deliveries); } } if($result){ $return = array_merge($return, $result); } } } return $return; } /** * @brief * * A public message with no listed recipients can be delivered to anybody who * has PERMS_NETWORK for that type of post, PERMS_AUTHED (in-network senders are * by definition authenticated) or PERMS_SITE and is one the same site, * or PERMS_SPECIFIC and the sender is a contact who is granted permissions via * their connection permissions in the address book. * Here we take a given message and construct a list of hashes of everybody * on the site that we should try and deliver to. * Some of these will be rejected, but this gives us a place to start. * * @param array $msg * @return NULL|array */ function public_recips($msg) { require_once('include/channel.php'); $check_mentions = false; $include_sys = false; if($msg['message']['type'] === 'activity') { if(! get_config('system','disable_discover_tab')) $include_sys = true; $perm = 'send_stream'; if(array_key_exists('flags',$msg['message']) && in_array('thread_parent', $msg['message']['flags'])) { // check mention recipient permissions on top level posts only $check_mentions = true; } else { // This doesn't look like it works so I have to explain what happened. These are my // notes (below) from when I got this section of code working. You would think that // we only have to find those with the requisite stream or comment permissions, // depending on whether this is a top-level post or a comment - but you would be wrong. // ... so public_recips and allowed_public_recips is working so much better // than before, but was still not quite right. We seem to be getting all the right // results for top-level posts now, but comments aren't getting through on channels // for which we've allowed them to send us their stream, but not comment on our posts. // The reason is we were seeing if they could comment - and we only need to do that if // we own the post. If they own the post, we only need to check if they can send us their stream. // if this is a comment and it wasn't sent by the post owner, check to see who is allowing them to comment. // We should have one specific recipient and this step shouldn't be needed unless somebody stuffed up // their software. We may need this step to protect us from bad guys intentionally stuffing up their software. // If it is sent by the post owner, we don't need to do this. We only need to see who is receiving the // owner's stream (which was already set above) - as they control the comment permissions, not us. // Note that by doing this we introduce another bug because some public forums have channel_w_stream // permissions set to themselves only. We also need in this function to add these public forums to the // public recipient list based on if they are tagged or not and have tag permissions. This is complicated // by the fact that this activity doesn't have the public forum tag. It's the parent activity that // contains the tag. we'll solve that further below. if($msg['notify']['sender']['guid_sig'] != $msg['message']['owner']['guid_sig']) { $perm = 'post_comments'; } } } elseif($msg['message']['type'] === 'mail') $perm = 'post_mail'; $r = array(); $c = q("select channel_id, channel_hash from channel where channel_removed = 0"); if($c) { foreach($c as $cc) { if(perm_is_allowed($cc['channel_id'],$msg['notify']['sender']['hash'],$perm)) { $r[] = [ 'hash' => $cc['channel_hash'] ]; } } } // logger('message: ' . print_r($msg['message'],true)); if($include_sys && array_key_exists('public_scope',$msg['message']) && $msg['message']['public_scope'] === 'public') { $sys = get_sys_channel(); if($sys) $r[] = [ 'hash' => $sys['channel_hash'] ]; } // look for any public mentions on this site // They will get filtered by tgroup_check() so we don't need to check permissions now if($check_mentions) { // It's a top level post. Look at the tags. See if any of them are mentions and are on this hub. if($msg['message']['tags']) { if(is_array($msg['message']['tags']) && $msg['message']['tags']) { foreach($msg['message']['tags'] as $tag) { if(($tag['type'] === 'mention') && (strpos($tag['url'],z_root()) !== false)) { $address = basename($tag['url']); if($address) { $z = q("select channel_hash as hash from channel where channel_address = '%s' and channel_removed = 0 limit 1", dbesc($address) ); if($z) $r = array_merge($r,$z); } } } } } } else { // This is a comment. We need to find any parent with ITEM_UPLINK set. But in fact, let's just return // everybody that stored a copy of the parent. This way we know we're covered. We'll check the // comment permissions when we deliver them. if($msg['message']['message_top']) { $z = q("select owner_xchan as hash from item where parent_mid = '%s' ", dbesc($msg['message']['message_top']) ); if($z) $r = array_merge($r,$z); } } // There are probably a lot of duplicates in $r at this point. We need to filter those out. // It's a bit of work since it's a multi-dimensional array if($r) { $uniq = array(); foreach($r as $rr) { if(! in_array($rr['hash'],$uniq)) $uniq[] = $rr['hash']; } $r = array(); foreach($uniq as $rr) { $r[] = array('hash' => $rr); } } logger('public_recips: ' . print_r($r,true), LOGGER_DATA, LOG_DEBUG); return $r; } /** * @brief * * This is the second part of public_recips(). * We'll find all the channels willing to accept public posts from us, then * match them against the sender privacy scope and see who in that list that * the sender is allowing. * * @see public_recipes() * @param array $msg * @return array */ function allowed_public_recips($msg) { logger('allowed_public_recips: ' . print_r($msg,true),LOGGER_DATA, LOG_DEBUG); if(array_key_exists('public_scope',$msg['message'])) $scope = $msg['message']['public_scope']; // Mail won't have a public scope. // in fact, it's doubtful mail will ever get here since it almost universally // has a recipient, but in fact we don't require this, so it's technically // possible to send mail to anybody that's listening. $recips = public_recips($msg); if(! $recips) return $recips; if($msg['message']['type'] === 'mail') return $recips; if($scope === 'public' || $scope === 'network: red' || $scope === 'authenticated') return $recips; if(strpos($scope,'site:') === 0) { if(($scope === 'site: ' . App::get_hostname()) && ($msg['notify']['sender']['url'] === z_root())) return $recips; else return array(); } $hash = make_xchan_hash($msg['notify']['sender']['guid'],$msg['notify']['sender']['guid_sig']); if($scope === 'self') { foreach($recips as $r) if($r['hash'] === $hash) return array('hash' => $hash); } // note: we shouldn't ever see $scope === 'specific' in this function, but handle it anyway if($scope === 'contacts' || $scope === 'any connections' || $scope === 'specific') { $condensed_recips = array(); foreach($recips as $rr) $condensed_recips[] = $rr['hash']; $results = array(); $r = q("select channel_hash as hash from channel left join abook on abook_channel = channel_id where abook_xchan = '%s' and channel_removed = 0 ", dbesc($hash) ); if($r) { foreach($r as $rr) if(in_array($rr['hash'],$condensed_recips)) $results[] = array('hash' => $rr['hash']); } return $results; } return array(); } /** * @brief * * @param array $sender * @param array $arr * @param array $deliveries * @param boolean $relay * @param boolean $public (optional) default false * @param boolean $request (optional) default false * @return array */ function process_delivery($sender, $arr, $deliveries, $relay, $public = false, $request = false) { $result = array(); $result['site'] = z_root(); // We've validated the sender. Now make sure that the sender is the owner or author if(! $public) { if($sender['hash'] != $arr['owner_xchan'] && $sender['hash'] != $arr['author_xchan']) { logger("process_delivery: sender {$sender['hash']} is not owner {$arr['owner_xchan']} or author {$arr['author_xchan']} - mid {$arr['mid']}"); return; } } foreach($deliveries as $d) { $local_public = $public; $DR = new Zotlabs\Zot\DReport(z_root(),$sender['hash'],$d['hash'],$arr['mid']); $r = q("select * from channel where channel_hash = '%s' limit 1", dbesc($d['hash']) ); if(! $r) { $DR->update('recipient not found'); $result[] = $DR->get(); continue; } $channel = $r[0]; $DR->addto_recipient($channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . App::get_hostname() . '>'); /* blacklisted channels get a permission denied, no special message to tip them off */ if(! check_channelallowed($sender['hash'])) { $DR->update('permission denied'); $result[] = $DR->get(); continue; } /** * @FIXME: Somehow we need to block normal message delivery from our clones, as the delivered * message doesn't have ACL information in it as the cloned copy does. That copy * will normally arrive first via sync delivery, but this isn't guaranteed. * There's a chance the current delivery could take place before the cloned copy arrives * hence the item could have the wrong ACL and *could* be used in subsequent deliveries or * access checks. So far all attempts at identifying this situation precisely * have caused issues with delivery of relayed comments. */ // if(($d['hash'] === $sender['hash']) && ($sender['url'] !== z_root()) && (! $relay)) { // $DR->update('self delivery ignored'); // $result[] = $DR->get(); // continue; // } // allow public postings to the sys channel regardless of permissions, but not // for comments travelling upstream. Wait and catch them on the way down. // They may have been blocked by the owner. if(intval($channel['channel_system']) && (! $arr['item_private']) && (! $relay)) { $local_public = true; $r = q("select xchan_selfcensored from xchan where xchan_hash = '%s' limit 1", dbesc($sender['hash']) ); // don't import sys channel posts from selfcensored authors if($r && (intval($r[0]['xchan_selfcensored']))) { $local_public = false; continue; } } $tag_delivery = tgroup_check($channel['channel_id'],$arr); $perm = 'send_stream'; if(($arr['mid'] !== $arr['parent_mid']) && ($relay)) $perm = 'post_comments'; // This is our own post, possibly coming from a channel clone if($arr['owner_xchan'] == $d['hash']) { $arr['item_wall'] = 1; } else { $arr['item_wall'] = 0; } if((! perm_is_allowed($channel['channel_id'],$sender['hash'],$perm)) && (! $tag_delivery) && (! $local_public)) { logger("permission denied for delivery to channel {$channel['channel_id']} {$channel['channel_address']}"); $DR->update('permission denied'); $result[] = $DR->get(); continue; } if($arr['mid'] != $arr['parent_mid']) { // check source route. // We are only going to accept comments from this sender if the comment has the same route as the top-level-post, // this is so that permissions mismatches between senders apply to the entire conversation // As a side effect we will also do a preliminary check that we have the top-level-post, otherwise // processing it is pointless. $r = q("select route, id from item where mid = '%s' and uid = %d limit 1", dbesc($arr['parent_mid']), intval($channel['channel_id']) ); if(! $r) { $DR->update('comment parent not found'); $result[] = $DR->get(); // We don't seem to have a copy of this conversation or at least the parent // - so request a copy of the entire conversation to date. // Don't do this if it's a relay post as we're the ones who are supposed to // have the copy and we don't want the request to loop. // Also don't do this if this comment came from a conversation request packet. // It's possible that comments are allowed but posting isn't and that could // cause a conversation fetch loop. We can detect these packets since they are // delivered via a 'notify' packet type that has a message_id element in the // initial zot packet (just like the corresponding 'request' packet type which // makes the request). // We'll also check the send_stream permission - because if it isn't allowed, // the top level post is unlikely to be imported and // this is just an exercise in futility. if((! $relay) && (! $request) && (! $local_public) && perm_is_allowed($channel['channel_id'],$sender['hash'],'send_stream')) { Zotlabs\Daemon\Master::Summon(array('Notifier', 'request', $channel['channel_id'], $sender['hash'], $arr['parent_mid'])); } continue; } if($relay) { // reset the route in case it travelled a great distance upstream // use our parent's route so when we go back downstream we'll match // with whatever route our parent has. $arr['route'] = $r[0]['route']; } else { // going downstream check that we have the same upstream provider that // sent it to us originally. Ignore it if it came from another source // (with potentially different permissions). // only compare the last hop since it could have arrived at the last location any number of ways. // Always accept empty routes and firehose items (route contains 'undefined') . $existing_route = explode(',', $r[0]['route']); $routes = count($existing_route); if($routes) { $last_hop = array_pop($existing_route); $last_prior_route = implode(',',$existing_route); } else { $last_hop = ''; $last_prior_route = ''; } if(in_array('undefined',$existing_route) || $last_hop == 'undefined' || $sender['hash'] == 'undefined') $last_hop = ''; $current_route = (($arr['route']) ? $arr['route'] . ',' : '') . $sender['hash']; if($last_hop && $last_hop != $sender['hash']) { logger('comment route mismatch: parent route = ' . $r[0]['route'] . ' expected = ' . $current_route, LOGGER_DEBUG); logger('comment route mismatch: parent msg = ' . $r[0]['id'],LOGGER_DEBUG); $DR->update('comment route mismatch'); $result[] = $DR->get(); continue; } // we'll add sender['hash'] onto this when we deliver it. $last_prior_route now has the previously stored route // *except* for the sender['hash'] which would've been the last hop before it got to us. $arr['route'] = $last_prior_route; } } $ab = q("select * from abook where abook_channel = %d and abook_xchan = '%s'", intval($channel['channel_id']), dbesc($arr['owner_xchan']) ); $abook = (($ab) ? $ab[0] : null); if(intval($arr['item_deleted'])) { // remove_community_tag is a no-op if this isn't a community tag activity remove_community_tag($sender,$arr,$channel['channel_id']); // set these just in case we need to store a fresh copy of the deleted post. // This could happen if the delete got here before the original post did. $arr['aid'] = $channel['channel_account_id']; $arr['uid'] = $channel['channel_id']; $item_id = delete_imported_item($sender,$arr,$channel['channel_id'],$relay); $DR->update(($item_id) ? 'deleted' : 'delete_failed'); $result[] = $DR->get(); if($relay && $item_id) { logger('process_delivery: invoking relay'); Zotlabs\Daemon\Master::Summon(array('Notifier','relay',intval($item_id))); $DR->update('relayed'); $result[] = $DR->get(); } continue; } $r = q("select * from item where mid = '%s' and uid = %d limit 1", dbesc($arr['mid']), intval($channel['channel_id']) ); if($r) { // We already have this post. $item_id = $r[0]['id']; if(intval($r[0]['item_deleted'])) { // It was deleted locally. $DR->update('update ignored'); $result[] = $DR->get(); continue; } // Maybe it has been edited? elseif($arr['edited'] > $r[0]['edited']) { $arr['id'] = $r[0]['id']; $arr['uid'] = $channel['channel_id']; if(($arr['mid'] == $arr['parent_mid']) && (! post_is_importable($arr,$abook))) { $DR->update('update ignored'); $result[] = $DR->get(); } else { update_imported_item($sender,$arr,$r[0],$channel['channel_id']); $DR->update('updated'); $result[] = $DR->get(); if(! $relay) add_source_route($item_id,$sender['hash']); } } else { $DR->update('update ignored'); $result[] = $DR->get(); // We need this line to ensure wall-to-wall comments are relayed (by falling through to the relay bit), // and at the same time not relay any other relayable posts more than once, because to do so is very wasteful. if(! intval($r[0]['item_origin'])) continue; } } else { $arr['aid'] = $channel['channel_account_id']; $arr['uid'] = $channel['channel_id']; // if it's a sourced post, call the post_local hooks as if it were // posted locally so that crosspost connectors will be triggered. if(check_item_source($arr['uid'], $arr)) call_hooks('post_local', $arr); $item_id = 0; if(($arr['mid'] == $arr['parent_mid']) && (! post_is_importable($arr,$abook))) { $DR->update('post ignored'); $result[] = $DR->get(); } else { $item_result = item_store($arr); if($item_result['success']) { $item_id = $item_result['item_id']; $parr = array('item_id' => $item_id,'item' => $arr,'sender' => $sender,'channel' => $channel); call_hooks('activity_received',$parr); // don't add a source route if it's a relay or later recipients will get a route mismatch if(! $relay) add_source_route($item_id,$sender['hash']); } $DR->update(($item_id) ? 'posted' : 'storage failed: ' . $item_result['message']); $result[] = $DR->get(); } } if($relay && $item_id) { logger('process_delivery: invoking relay'); Zotlabs\Daemon\Master::Summon(array('Notifier','relay',intval($item_id))); $DR->addto_update('relayed'); $result[] = $DR->get(); } } if(! $deliveries) $result[] = array('', 'no recipients', '', $arr['mid']); logger('process_delivery: local results: ' . print_r($result, true), LOGGER_DEBUG); return $result; } /** * @brief * * @param array $sender an associative array with * * \e string \b hash a xchan_hash * @param array $arr an associative array * * \e int \b verb * * \e int \b obj_type * * \e int \b mid * @param int $uid */ function remove_community_tag($sender, $arr, $uid) { if(! (activity_match($arr['verb'], ACTIVITY_TAG) && ($arr['obj_type'] == ACTIVITY_OBJ_TAGTERM))) return; logger('remove_community_tag: invoked'); if(! get_pconfig($uid,'system','blocktags')) { logger('remove_community tag: permission denied.'); return; } $r = q("select * from item where mid = '%s' and uid = %d limit 1", dbesc($arr['mid']), intval($uid) ); if(! $r) { logger('remove_community_tag: no item'); return; } if(($sender['hash'] != $r[0]['owner_xchan']) && ($sender['hash'] != $r[0]['author_xchan'])) { logger('remove_community_tag: sender not authorised.'); return; } $i = $r[0]; if($i['target']) $i['target'] = json_decode($i['target'],true); if($i['object']) $i['object'] = json_decode($i['object'],true); if(! ($i['target'] && $i['object'])) { logger('remove_community_tag: no target/object'); return; } $message_id = $i['target']['id']; $r = q("select id from item where mid = '%s' and uid = %d limit 1", dbesc($message_id), intval($uid) ); if(! $r) { logger('remove_community_tag: no parent message'); return; } q("delete from term where uid = %d and oid = %d and otype = %d and ttype in ( %d, %d ) and term = '%s' and url = '%s'", intval($uid), intval($r[0]['id']), intval(TERM_OBJ_POST), intval(TERM_HASHTAG), intval(TERM_COMMUNITYTAG), dbesc($i['object']['title']), dbesc(get_rel_link($i['object']['link'],'alternate')) ); } /** * @brief Just calls item_store_update() and logs result. * * @see item_store_update() * @param array $sender (unused) * @param array $item * @param int $uid (unused) */ function update_imported_item($sender, $item, $orig, $uid) { // If this is a comment being updated, remove any privacy information // so that item_store_update will set it from the original. if($item['mid'] !== $item['parent_mid']) { unset($item['allow_cid']); unset($item['allow_gid']); unset($item['deny_cid']); unset($item['deny_gid']); unset($item['item_private']); } $x = item_store_update($item); // If we're updating an event that we've saved locally, we store the item info first // because event_addtocal will parse the body to get the 'new' event details if($orig['resource_type'] === 'event') { $res = event_addtocal($orig['id'],$uid); if(! $res) logger('update event: failed'); } if(! $x['item_id']) logger('update_imported_item: failed: ' . $x['message']); else logger('update_imported_item'); } /** * @brief Deletes an imported item. * * @param array $sender * * \e string \b hash a xchan_hash * @param array $item * @param int $uid * @param boolean $relay * @return boolean|int post_id */ function delete_imported_item($sender, $item, $uid, $relay) { logger('delete_imported_item invoked', LOGGER_DEBUG); $ownership_valid = false; $item_found = false; $post_id = 0; $r = q("select id, author_xchan, owner_xchan, source_xchan, item_deleted from item where ( author_xchan = '%s' or owner_xchan = '%s' or source_xchan = '%s' ) and mid = '%s' and uid = %d limit 1", dbesc($sender['hash']), dbesc($sender['hash']), dbesc($sender['hash']), dbesc($item['mid']), intval($uid) ); if ($r) { if ($r[0]['author_xchan'] === $sender['hash'] || $r[0]['owner_xchan'] === $sender['hash'] || $r[0]['source_xchan'] === $sender['hash']) $ownership_valid = true; $post_id = $r[0]['id']; $item_found = true; } else { // perhaps the item is still in transit and the delete notification got here before the actual item did. Store it with the deleted flag set. // item_store() won't try to deliver any notifications or start delivery chains if this flag is set. // This means we won't end up with potentially even more delivery threads trying to push this delete notification. // But this will ensure that if the (undeleted) original post comes in at a later date, we'll reject it because it will have an older timestamp. logger('delete received for non-existent item - storing item data.'); /** @BUG $arr is undefined here, so this is dead code */ if ($arr['author_xchan'] === $sender['hash'] || $arr['owner_xchan'] === $sender['hash'] || $arr['source_xchan'] === $sender['hash']) { $ownership_valid = true; $item_result = item_store($arr); $post_id = $item_result['item_id']; } } if ($ownership_valid === false) { logger('delete_imported_item: failed: ownership issue'); return false; } require_once('include/items.php'); if ($item_found) { if (intval($r[0]['item_deleted'])) { logger('delete_imported_item: item was already deleted'); if (! $relay) return false; // This is a bit hackish, but may have to suffice until the notification/delivery loop is optimised // a bit further. We're going to strip the ITEM_ORIGIN on this item if it's a comment, because // it was already deleted, and we're already relaying, and this ensures that no other process or // code path downstream can relay it again (causing a loop). Since it's already gone it's not coming // back, and we aren't going to (or shouldn't at any rate) delete it again in the future - so losing // this information from the metadata should have no other discernible impact. if (($r[0]['id'] != $r[0]['parent']) && intval($r[0]['item_origin'])) { q("update item set item_origin = 0 where id = %d and uid = %d", intval($r[0]['id']), intval($r[0]['uid']) ); } } require_once('include/items.php'); // Use phased deletion to set the deleted flag, call both tag_deliver and the notifier to notify downstream channels // and then clean up after ourselves with a cron job after several days to do the delete_item_lowlevel() (DROPITEM_PHASE2). drop_item($post_id, false, DROPITEM_PHASE1); tag_deliver($uid, $post_id); } return $post_id; } function process_mail_delivery($sender, $arr, $deliveries) { $result = array(); if($sender['hash'] != $arr['from_xchan']) { logger('process_mail_delivery: sender is not mail author'); return; } foreach($deliveries as $d) { $DR = new Zotlabs\Zot\DReport(z_root(),$sender['hash'],$d['hash'],$arr['mid']); $r = q("select * from channel where channel_hash = '%s' limit 1", dbesc($d['hash']) ); if(! $r) { $DR->update('recipient not found'); $result[] = $DR->get(); continue; } $channel = $r[0]; $DR->addto_recipient($channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . App::get_hostname() . '>'); /* blacklisted channels get a permission denied, no special message to tip them off */ if(! check_channelallowed($sender['hash'])) { $DR->update('permission denied'); $result[] = $DR->get(); continue; } if(! perm_is_allowed($channel['channel_id'],$sender['hash'],'post_mail')) { logger("permission denied for mail delivery {$channel['channel_id']}"); $DR->update('permission denied'); $result[] = $DR->get(); continue; } $r = q("select id from mail where mid = '%s' and channel_id = %d limit 1", dbesc($arr['mid']), intval($channel['channel_id']) ); if($r) { if(intval($arr['mail_recalled'])) { $x = q("delete from mail where id = %d and channel_id = %d", intval($r[0]['id']), intval($channel['channel_id']) ); $DR->update('mail recalled'); $result[] = $DR->get(); logger('mail_recalled'); } else { $DR->update('duplicate mail received'); $result[] = $DR->get(); logger('duplicate mail received'); } continue; } else { $arr['account_id'] = $channel['channel_account_id']; $arr['channel_id'] = $channel['channel_id']; $item_id = mail_store($arr); $DR->update('mail delivered'); $result[] = $DR->get(); } } return $result; } /** * @brief Processes delivery of rating. * * @param array $sender * * \e string \b hash a xchan_hash * @param array $arr */ function process_rating_delivery($sender, $arr) { logger('process_rating_delivery: ' . print_r($arr,true)); if(! $arr['target']) return; $z = q("select xchan_pubkey from xchan where xchan_hash = '%s' limit 1", dbesc($sender['hash']) ); if((! $z) || (! rsa_verify($arr['target'] . '.' . $arr['rating'] . '.' . $arr['rating_text'], base64url_decode($arr['signature']),$z[0]['xchan_pubkey']))) { logger('failed to verify rating'); return; } $r = q("select * from xlink where xlink_xchan = '%s' and xlink_link = '%s' and xlink_static = 1 limit 1", dbesc($sender['hash']), dbesc($arr['target']) ); if($r) { if($r[0]['xlink_updated'] >= $arr['edited']) { logger('rating message duplicate'); return; } $x = q("update xlink set xlink_rating = %d, xlink_rating_text = '%s', xlink_sig = '%s', xlink_updated = '%s' where xlink_id = %d", intval($arr['rating']), dbesc($arr['rating_text']), dbesc($arr['signature']), dbesc(datetime_convert()), intval($r[0]['xlink_id']) ); logger('rating updated'); } else { $x = q("insert into xlink ( xlink_xchan, xlink_link, xlink_rating, xlink_rating_text, xlink_sig, xlink_updated, xlink_static ) values( '%s', '%s', %d, '%s', '%s', '%s', 1 ) ", dbesc($sender['hash']), dbesc($arr['target']), intval($arr['rating']), dbesc($arr['rating_text']), dbesc($arr['signature']), dbesc(datetime_convert()) ); logger('rating created'); } } /** * @brief Processes delivery of profile. * * @see import_directory_profile() * @param array $sender an associative array * * \e string \b hash a xchan_hash * @param array $arr * @param array $deliveries (unused) */ function process_profile_delivery($sender, $arr, $deliveries) { logger('process_profile_delivery', LOGGER_DEBUG); $r = q("select xchan_addr from xchan where xchan_hash = '%s' limit 1", dbesc($sender['hash']) ); if($r) import_directory_profile($sender['hash'], $arr, $r[0]['xchan_addr'], UPDATE_FLAGS_UPDATED, 0); } function process_location_delivery($sender,$arr,$deliveries) { // deliveries is irrelevant logger('process_location_delivery', LOGGER_DEBUG); $r = q("select xchan_pubkey from xchan where xchan_hash = '%s' limit 1", dbesc($sender['hash']) ); if($r) $sender['key'] = $r[0]['xchan_pubkey']; if(array_key_exists('locations',$arr) && $arr['locations']) { $x = sync_locations($sender,$arr,true); logger('process_location_delivery: results: ' . print_r($x,true), LOGGER_DEBUG); if($x['changed']) { $guid = random_string() . '@' . App::get_hostname(); update_modtime($sender['hash'],$sender['guid'],$arr['locations'][0]['address'],UPDATE_FLAGS_UPDATED); } } } /** * @brief checks for a moved UNO channel and sets the channel_moved flag * * Currently the effect of this flag is to turn the channel into 'read-only' mode. * New content will not be processed (there was still an issue with blocking the * ability to post comments as of 10-Mar-2016). * We do not physically remove the channel at this time. The hub admin may choose * to do so, but is encouraged to allow a grace period of several days in case there * are any issues migrating content. This packet will generally be received by the * original site when the basic channel import has been processed. * * This will only be executed on the UNO system which is the old location * if a new location is reported and there is only one location record. * The rest of the hubloc syncronisation will be handled within * sync_locations */ function check_location_move($sender_hash,$locations) { if(! $locations) return; if(get_config('system','server_role') !== 'basic') return; if(count($locations) != 1) return; $loc = $locations[0]; $r = q("select * from channel where channel_hash = '%s' limit 1", dbesc($sender_hash) ); if(! $r) return; if($loc['url'] !== z_root()) { $x = q("update channel set channel_moved = '%s' where channel_hash = '%s' limit 1", dbesc($loc['url']), dbesc($sender_hash) ); // federation plugins may wish to notify connections // of the move on singleton networks $arr = array('channel' => $r[0],'locations' => $locations); call_hooks('location_move',$arr); } } /** * @brief Synchronises locations. * * @param array $sender * @param array $arr * @param boolean $absolute (optional) default false * @return array */ function sync_locations($sender, $arr, $absolute = false) { $ret = array(); if($arr['locations']) { if($absolute) check_location_move($sender['hash'],$arr['locations']); $xisting = q("select hubloc_id, hubloc_url, hubloc_sitekey from hubloc where hubloc_hash = '%s'", dbesc($sender['hash']) ); // See if a primary is specified $has_primary = false; foreach($arr['locations'] as $location) { if($location['primary']) { $has_primary = true; break; } } // Ensure that they have one primary hub if(! $has_primary) $arr['locations'][0]['primary'] = true; foreach($arr['locations'] as $location) { if(! rsa_verify($location['url'],base64url_decode($location['url_sig']),$sender['key'])) { logger('sync_locations: Unable to verify site signature for ' . $location['url']); $ret['message'] .= sprintf( t('Unable to verify site signature for %s'), $location['url']) . EOL; continue; } for($x = 0; $x < count($xisting); $x ++) { if(($xisting[$x]['hubloc_url'] === $location['url']) && ($xisting[$x]['hubloc_sitekey'] === $location['sitekey'])) { $xisting[$x]['updated'] = true; } } if(! $location['sitekey']) { logger('sync_locations: empty hubloc sitekey. ' . print_r($location,true)); continue; } // Catch some malformed entries from the past which still exist if(strpos($location['address'],'/') !== false) $location['address'] = substr($location['address'],0,strpos($location['address'],'/')); // match as many fields as possible in case anything at all changed. $r = q("select * from hubloc where hubloc_hash = '%s' and hubloc_guid = '%s' and hubloc_guid_sig = '%s' and hubloc_url = '%s' and hubloc_url_sig = '%s' and hubloc_host = '%s' and hubloc_addr = '%s' and hubloc_callback = '%s' and hubloc_sitekey = '%s' ", dbesc($sender['hash']), dbesc($sender['guid']), dbesc($sender['guid_sig']), dbesc($location['url']), dbesc($location['url_sig']), dbesc($location['host']), dbesc($location['address']), dbesc($location['callback']), dbesc($location['sitekey']) ); if($r) { logger('sync_locations: hub exists: ' . $location['url'], LOGGER_DEBUG); // update connection timestamp if this is the site we're talking to // This only happens when called from import_xchan $current_site = false; $t = datetime_convert('UTC','UTC','now - 15 minutes'); if(array_key_exists('site',$arr) && $location['url'] == $arr['site']['url']) { q("update hubloc set hubloc_connected = '%s', hubloc_updated = '%s' where hubloc_id = %d and hubloc_connected < '%s'", dbesc(datetime_convert()), dbesc(datetime_convert()), intval($r[0]['hubloc_id']), dbesc($t) ); $current_site = true; } if($current_site && intval($r[0]['hubloc_error'])) { q("update hubloc set hubloc_error = 0 where hubloc_id = %d", intval($r[0]['hubloc_id']) ); if(intval($r[0]['hubloc_orphancheck'])) { q("update hubloc set hubloc_orphancheck = 0 where hubloc_id = %d", intval($r[0]['hubloc_id']) ); } q("update xchan set xchan_orphan = 0 where xchan_orphan = 1 and xchan_hash = '%s'", dbesc($sender['hash']) ); } // Remove pure duplicates if(count($r) > 1) { for($h = 1; $h < count($r); $h ++) { q("delete from hubloc where hubloc_id = %d", intval($r[$h]['hubloc_id']) ); $what .= 'duplicate_hubloc_removed '; $changed = true; } } if(intval($r[0]['hubloc_primary']) && (! $location['primary'])) { $m = q("update hubloc set hubloc_primary = 0, hubloc_updated = '%s' where hubloc_id = %d", dbesc(datetime_convert()), intval($r[0]['hubloc_id']) ); $r[0]['hubloc_primary'] = intval($location['primary']); hubloc_change_primary($r[0]); $what .= 'primary_hub '; $changed = true; } elseif((! intval($r[0]['hubloc_primary'])) && ($location['primary'])) { $m = q("update hubloc set hubloc_primary = 1, hubloc_updated = '%s' where hubloc_id = %d", dbesc(datetime_convert()), intval($r[0]['hubloc_id']) ); // make sure hubloc_change_primary() has current data $r[0]['hubloc_primary'] = intval($location['primary']); hubloc_change_primary($r[0]); $what .= 'primary_hub '; $changed = true; } elseif($absolute) { // Absolute sync - make sure the current primary is correctly reflected in the xchan $pr = hubloc_change_primary($r[0]); if($pr) { $what .= 'xchan_primary '; $changed = true; } } if(intval($r[0]['hubloc_deleted']) && (! intval($location['deleted']))) { $n = q("update hubloc set hubloc_deleted = 0, hubloc_updated = '%s' where hubloc_id = %d", dbesc(datetime_convert()), intval($r[0]['hubloc_id']) ); $what .= 'undelete_hub '; $changed = true; } elseif((! intval($r[0]['hubloc_deleted'])) && (intval($location['deleted']))) { logger('deleting hubloc: ' . $r[0]['hubloc_addr']); $n = q("update hubloc set hubloc_deleted = 1, hubloc_updated = '%s' where hubloc_id = %d", dbesc(datetime_convert()), intval($r[0]['hubloc_id']) ); $what .= 'delete_hub '; $changed = true; } continue; } // Existing hubs are dealt with. Now let's process any new ones. // New hub claiming to be primary. Make it so by removing any existing primaries. if(intval($location['primary'])) { $r = q("update hubloc set hubloc_primary = 0, hubloc_updated = '%s' where hubloc_hash = '%s' and hubloc_primary = 1", dbesc(datetime_convert()), dbesc($sender['hash']) ); } logger('sync_locations: new hub: ' . $location['url']); $r = q("insert into hubloc ( hubloc_guid, hubloc_guid_sig, hubloc_hash, hubloc_addr, hubloc_network, hubloc_primary, hubloc_url, hubloc_url_sig, hubloc_host, hubloc_callback, hubloc_sitekey, hubloc_updated, hubloc_connected) values ( '%s','%s','%s','%s', '%s', %d ,'%s','%s','%s','%s','%s','%s','%s')", dbesc($sender['guid']), dbesc($sender['guid_sig']), dbesc($sender['hash']), dbesc($location['address']), dbesc('zot'), intval($location['primary']), dbesc($location['url']), dbesc($location['url_sig']), dbesc($location['host']), dbesc($location['callback']), dbesc($location['sitekey']), dbesc(datetime_convert()), dbesc(datetime_convert()) ); $what .= 'newhub '; $changed = true; if($location['primary']) { $r = q("select * from hubloc where hubloc_addr = '%s' and hubloc_sitekey = '%s' limit 1", dbesc($location['address']), dbesc($location['sitekey']) ); if($r) hubloc_change_primary($r[0]); } } // get rid of any hubs we have for this channel which weren't reported. if($absolute && $xisting) { foreach($xisting as $x) { if(! array_key_exists('updated',$x)) { logger('sync_locations: deleting unreferenced hub location ' . $x['hubloc_addr']); $r = q("update hubloc set hubloc_deleted = 1, hubloc_updated = '%s' where hubloc_id = %d", dbesc(datetime_convert()), intval($x['hubloc_id']) ); $what .= 'removed_hub '; $changed = true; } } } } else { logger('No locations to sync!'); } $ret['change_message'] = $what; $ret['changed'] = $changed; return $ret; } /** * @brief Returns an array with all known distinct hubs for this channel. * * @see zot_get_hublocs() * @param array $channel an associative array which must contain * * \e string \b channel_hash the hash of the channel * @return array an array with associative arrays */ function zot_encode_locations($channel) { $ret = array(); $x = zot_get_hublocs($channel['channel_hash']); if($x && count($x)) { foreach($x as $hub) { // if this is a local channel that has been deleted, the hubloc is no good - make sure it is marked deleted // so that nobody tries to use it. if(intval($channel['channel_removed']) && $hub['hubloc_url'] === z_root()) $hub['hubloc_deleted'] = 1; $ret[] = array( 'host' => $hub['hubloc_host'], 'address' => $hub['hubloc_addr'], 'primary' => (intval($hub['hubloc_primary']) ? true : false), 'url' => $hub['hubloc_url'], 'url_sig' => $hub['hubloc_url_sig'], 'callback' => $hub['hubloc_callback'], 'sitekey' => $hub['hubloc_sitekey'], 'deleted' => (intval($hub['hubloc_deleted']) ? true : false) ); } } return $ret; } /** * @brief Imports a directory profile. * * @param string $hash * @param array $profile * @param string $addr * @param number $ud_flags * @param number $suppress_update default 0 * @return boolean $updated if something changed */ function import_directory_profile($hash, $profile, $addr, $ud_flags = UPDATE_FLAGS_UPDATED, $suppress_update = 0) { logger('import_directory_profile', LOGGER_DEBUG); if (! $hash) return false; $arr = array(); $arr['xprof_hash'] = $hash; $arr['xprof_dob'] = datetime_convert('','',$profile['birthday'],'Y-m-d'); // !!!! check this for 0000 year $arr['xprof_age'] = (($profile['age']) ? intval($profile['age']) : 0); $arr['xprof_desc'] = (($profile['description']) ? htmlspecialchars($profile['description'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_gender'] = (($profile['gender']) ? htmlspecialchars($profile['gender'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_marital'] = (($profile['marital']) ? htmlspecialchars($profile['marital'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_sexual'] = (($profile['sexual']) ? htmlspecialchars($profile['sexual'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_locale'] = (($profile['locale']) ? htmlspecialchars($profile['locale'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_region'] = (($profile['region']) ? htmlspecialchars($profile['region'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_postcode'] = (($profile['postcode']) ? htmlspecialchars($profile['postcode'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_country'] = (($profile['country']) ? htmlspecialchars($profile['country'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_about'] = (($profile['about']) ? htmlspecialchars($profile['about'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_homepage'] = (($profile['homepage']) ? htmlspecialchars($profile['homepage'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_hometown'] = (($profile['hometown']) ? htmlspecialchars($profile['hometown'], ENT_COMPAT,'UTF-8',false) : ''); $clean = array(); if (array_key_exists('keywords', $profile) and is_array($profile['keywords'])) { import_directory_keywords($hash,$profile['keywords']); foreach ($profile['keywords'] as $kw) { $kw = trim(htmlspecialchars($kw,ENT_COMPAT, 'UTF-8', false)); $kw = trim($kw, ','); $clean[] = $kw; } } $arr['xprof_keywords'] = implode(' ',$clean); // Self censored, make it so // These are not translated, so the German "erwachsenen" keyword will not censor the directory profile. Only the English form - "adult". if(in_arrayi('nsfw',$clean) || in_arrayi('adult',$clean)) { q("update xchan set xchan_selfcensored = 1 where xchan_hash = '%s'", dbesc($hash) ); } $r = q("select * from xprof where xprof_hash = '%s' limit 1", dbesc($hash) ); if ($arr['xprof_age'] > 150) $arr['xprof_age'] = 150; if ($arr['xprof_age'] < 0) $arr['xprof_age'] = 0; if ($r) { $update = false; foreach ($r[0] as $k => $v) { if ((array_key_exists($k,$arr)) && ($arr[$k] != $v)) { logger('import_directory_profile: update ' . $k . ' => ' . $arr[$k]); $update = true; break; } } if ($update) { q("update xprof set xprof_desc = '%s', xprof_dob = '%s', xprof_age = %d, xprof_gender = '%s', xprof_marital = '%s', xprof_sexual = '%s', xprof_locale = '%s', xprof_region = '%s', xprof_postcode = '%s', xprof_country = '%s', xprof_about = '%s', xprof_homepage = '%s', xprof_hometown = '%s', xprof_keywords = '%s' where xprof_hash = '%s'", dbesc($arr['xprof_desc']), dbesc($arr['xprof_dob']), intval($arr['xprof_age']), dbesc($arr['xprof_gender']), dbesc($arr['xprof_marital']), dbesc($arr['xprof_sexual']), dbesc($arr['xprof_locale']), dbesc($arr['xprof_region']), dbesc($arr['xprof_postcode']), dbesc($arr['xprof_country']), dbesc($arr['xprof_about']), dbesc($arr['xprof_homepage']), dbesc($arr['xprof_hometown']), dbesc($arr['xprof_keywords']), dbesc($arr['xprof_hash']) ); } } else { $update = true; logger('import_directory_profile: new profile '); q("insert into xprof (xprof_hash, xprof_desc, xprof_dob, xprof_age, xprof_gender, xprof_marital, xprof_sexual, xprof_locale, xprof_region, xprof_postcode, xprof_country, xprof_about, xprof_homepage, xprof_hometown, xprof_keywords) values ('%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s') ", dbesc($arr['xprof_hash']), dbesc($arr['xprof_desc']), dbesc($arr['xprof_dob']), intval($arr['xprof_age']), dbesc($arr['xprof_gender']), dbesc($arr['xprof_marital']), dbesc($arr['xprof_sexual']), dbesc($arr['xprof_locale']), dbesc($arr['xprof_region']), dbesc($arr['xprof_postcode']), dbesc($arr['xprof_country']), dbesc($arr['xprof_about']), dbesc($arr['xprof_homepage']), dbesc($arr['xprof_hometown']), dbesc($arr['xprof_keywords']) ); } $d = array('xprof' => $arr, 'profile' => $profile, 'update' => $update); call_hooks('import_directory_profile', $d); if (($d['update']) && (! $suppress_update)) update_modtime($arr['xprof_hash'],random_string() . '@' . App::get_hostname(), $addr, $ud_flags); return $d['update']; } /** * @brief * * @param string $hash * @param array $keywords */ function import_directory_keywords($hash, $keywords) { $existing = array(); $r = q("select * from xtag where xtag_hash = '%s' and xtag_flags = 0", dbesc($hash) ); if($r) { foreach($r as $rr) $existing[] = $rr['xtag_term']; } $clean = array(); foreach($keywords as $kw) { $kw = trim(htmlspecialchars($kw,ENT_COMPAT, 'UTF-8', false)); $kw = trim($kw, ','); $clean[] = $kw; } foreach($existing as $x) { if(! in_array($x, $clean)) $r = q("delete from xtag where xtag_hash = '%s' and xtag_term = '%s' and xtag_flags = 0", dbesc($hash), dbesc($x) ); } foreach($clean as $x) { if(! in_array($x, $existing)) { $r = q("insert into xtag ( xtag_hash, xtag_term, xtag_flags) values ( '%s' ,'%s', 0 )", dbesc($hash), dbesc($x) ); } } } /** * @brief * * @param string $hash * @param string $guid * @param string $addr * @param int $flags (optional) default 0 */ function update_modtime($hash, $guid, $addr, $flags = 0) { $dirmode = intval(get_config('system', 'directory_mode')); if($dirmode == DIRECTORY_MODE_NORMAL) return; if($flags) { q("insert into updates (ud_hash, ud_guid, ud_date, ud_flags, ud_addr ) values ( '%s', '%s', '%s', %d, '%s' )", dbesc($hash), dbesc($guid), dbesc(datetime_convert()), intval($flags), dbesc($addr) ); } else { q("update updates set ud_flags = ( ud_flags | %d ) where ud_addr = '%s' and not (ud_flags & %d)>0 ", intval(UPDATE_FLAGS_UPDATED), dbesc($addr), intval(UPDATE_FLAGS_UPDATED) ); } } /** * @brief * * @param array $arr * @param string $pubkey * @return boolean true if updated or inserted */ function import_site($arr, $pubkey) { if( (! is_array($arr)) || (! $arr['url']) || (! $arr['url_sig'])) return false; if(! rsa_verify($arr['url'], base64url_decode($arr['url_sig']), $pubkey)) { logger('import_site: bad url_sig'); return false; } $update = false; $exists = false; $r = q("select * from site where site_url = '%s' limit 1", dbesc($arr['url']) ); if($r) { $exists = true; $siterecord = $r[0]; } $site_directory = 0; if($arr['directory_mode'] == 'normal') $site_directory = DIRECTORY_MODE_NORMAL; if($arr['directory_mode'] == 'primary') $site_directory = DIRECTORY_MODE_PRIMARY; if($arr['directory_mode'] == 'secondary') $site_directory = DIRECTORY_MODE_SECONDARY; if($arr['directory_mode'] == 'standalone') $site_directory = DIRECTORY_MODE_STANDALONE; $register_policy = 0; if($arr['register_policy'] == 'closed') $register_policy = REGISTER_CLOSED; if($arr['register_policy'] == 'open') $register_policy = REGISTER_OPEN; if($arr['register_policy'] == 'approve') $register_policy = REGISTER_APPROVE; $access_policy = 0; if(array_key_exists('access_policy',$arr)) { if($arr['access_policy'] === 'private') $access_policy = ACCESS_PRIVATE; if($arr['access_policy'] === 'paid') $access_policy = ACCESS_PAID; if($arr['access_policy'] === 'free') $access_policy = ACCESS_FREE; if($arr['access_policy'] === 'tiered') $access_policy = ACCESS_TIERED; } // don't let insecure sites register as public hubs if(strpos($arr['url'],'https://') === false) $access_policy = ACCESS_PRIVATE; if($access_policy != ACCESS_PRIVATE) { $x = z_fetch_url($arr['url'] . '/siteinfo/json'); if(! $x['success']) $access_policy = ACCESS_PRIVATE; } $directory_url = htmlspecialchars($arr['directory_url'],ENT_COMPAT,'UTF-8',false); $url = htmlspecialchars(strtolower($arr['url']),ENT_COMPAT,'UTF-8',false); $sellpage = htmlspecialchars($arr['sellpage'],ENT_COMPAT,'UTF-8',false); $site_location = htmlspecialchars($arr['location'],ENT_COMPAT,'UTF-8',false); $site_realm = htmlspecialchars($arr['realm'],ENT_COMPAT,'UTF-8',false); $site_project = htmlspecialchars($arr['project'],ENT_COMPAT,'UTF-8',false); // You can have one and only one primary directory per realm. // Downgrade any others claiming to be primary. As they have // flubbed up this badly already, don't let them be directory servers at all. if(($site_directory === DIRECTORY_MODE_PRIMARY) && ($site_realm === get_directory_realm()) && ($arr['url'] != get_directory_primary())) { $site_directory = DIRECTORY_MODE_NORMAL; } if($exists) { if(($siterecord['site_flags'] != $site_directory) || ($siterecord['site_access'] != $access_policy) || ($siterecord['site_directory'] != $directory_url) || ($siterecord['site_sellpage'] != $sellpage) || ($siterecord['site_location'] != $site_location) || ($siterecord['site_register'] != $register_policy) || ($siterecord['site_project'] != $site_project) || ($siterecord['site_realm'] != $site_realm)) { $update = true; // logger('import_site: input: ' . print_r($arr,true)); // logger('import_site: stored: ' . print_r($siterecord,true)); $r = q("update site set site_dead = 0, site_location = '%s', site_flags = %d, site_access = %d, site_directory = '%s', site_register = %d, site_update = '%s', site_sellpage = '%s', site_realm = '%s', site_type = %d, site_project = '%s' where site_url = '%s'", dbesc($site_location), intval($site_directory), intval($access_policy), dbesc($directory_url), intval($register_policy), dbesc(datetime_convert()), dbesc($sellpage), dbesc($site_realm), intval(SITE_TYPE_ZOT), dbesc($site_project), dbesc($url) ); if(! $r) { logger('import_site: update failed. ' . print_r($arr,true)); } } else { // update the timestamp to indicate we communicated with this site q("update site set site_dead = 0, site_update = '%s' where site_url = '%s'", dbesc(datetime_convert()), dbesc($url) ); } } else { $update = true; $r = q("insert into site ( site_location, site_url, site_access, site_flags, site_update, site_directory, site_register, site_sellpage, site_realm, site_type, site_project ) values ( '%s', '%s', %d, %d, '%s', '%s', %d, '%s', '%s', %d, '%s' )", dbesc($site_location), dbesc($url), intval($access_policy), intval($site_directory), dbesc(datetime_convert()), dbesc($directory_url), intval($register_policy), dbesc($sellpage), dbesc($site_realm), intval(SITE_TYPE_ZOT), dbesc($site_project) ); if(! $r) { logger('import_site: record create failed. ' . print_r($arr,true)); } } return $update; } /** * Send a zot packet to all hubs where this channel is duplicated, refreshing * such things as personal settings, channel permissions, address book updates, etc. * * @param int $uid * @param array $packet (optional) default null * @param boolean $groups_changed (optional) default false */ function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) { if(get_config('system','server_role') === 'basic') return; logger('build_sync_packet'); if($packet) logger('packet: ' . print_r($packet, true),LOGGER_DATA, LOG_DEBUG); if(! $uid) $uid = local_channel(); if(! $uid) return; $r = q("select * from channel where channel_id = %d limit 1", intval($uid) ); if(! $r) return; $channel = $r[0]; translate_channel_perms_outbound($channel); if($packet && array_key_exists('abook',$packet) && $packet['abook']) { for($x = 0; $x < count($packet['abook']); $x ++) { translate_abook_perms_outbound($packet['abook'][$x]); } } if(intval($channel['channel_removed'])) return; $h = q("select * from hubloc where hubloc_hash = '%s' and hubloc_deleted = 0", dbesc($channel['channel_hash']) ); if(! $h) return; $synchubs = array(); foreach($h as $x) { if($x['hubloc_host'] == App::get_hostname()) continue; $y = q("select site_dead from site where site_url = '%s' limit 1", dbesc($x['hubloc_url']) ); if((! $y) || ($y[0]['site_dead'] == 0)) $synchubs[] = $x; } if(! $synchubs) return; $r = q("select xchan_guid, xchan_guid_sig from xchan where xchan_hash = '%s' limit 1", dbesc($channel['channel_hash']) ); if(! $r) return; $env_recips = array(); $env_recips[] = array('guid' => $r[0]['xchan_guid'],'guid_sig' => $r[0]['xchan_guid_sig']); $info = (($packet) ? $packet : array()); $info['type'] = 'channel_sync'; $info['encoding'] = 'red'; // note: not zot, this packet is very platform specific $info['relocate'] = ['channel_address' => $channel['channel_address'], 'url' => z_root() ]; if(array_key_exists($uid,App::$config) && array_key_exists('transient',App::$config[$uid])) { $settings = App::$config[$uid]['transient']; if($settings) { $info['config'] = $settings; } } if($channel) { $info['channel'] = array(); foreach($channel as $k => $v) { // filter out any joined tables like xchan if(strpos($k,'channel_') !== 0) continue; // don't pass these elements, they should not be synchronised $disallowed = array('channel_id','channel_account_id','channel_primary','channel_prvkey','channel_address','channel_deleted','channel_removed','channel_system'); if(in_array($k,$disallowed)) continue; $info['channel'][$k] = $v; } } if($groups_changed) { $r = q("select hash as collection, visible, deleted, gname as name from groups where uid = %d", intval($uid) ); if($r) $info['collections'] = $r; $r = q("select groups.hash as collection, group_member.xchan as member from groups left join group_member on groups.id = group_member.gid where group_member.uid = %d", intval($uid) ); if($r) $info['collection_members'] = $r; } $interval = ((get_config('system','delivery_interval') !== false) ? intval(get_config('system','delivery_interval')) : 2 ); logger('build_sync_packet: packet: ' . print_r($info,true), LOGGER_DATA, LOG_DEBUG); $total = count($synchubs); foreach($synchubs as $hub) { $hash = random_string(); $n = zot_build_packet($channel,'notify',$env_recips,$hub['hubloc_sitekey'],$hash); queue_insert(array( 'hash' => $hash, 'account_id' => $channel['channel_account_id'], 'channel_id' => $channel['channel_id'], 'posturl' => $hub['hubloc_callback'], 'notify' => $n, 'msg' => json_encode($info) )); Zotlabs\Daemon\Master::Summon(array('Deliver', $hash)); $total = $total - 1; if($interval && $total) @time_sleep_until(microtime(true) + (float) $interval); } } /** * @brief * * @param array $sender * @param array $arr * @param array $deliveries * @return array */ function process_channel_sync_delivery($sender, $arr, $deliveries) { if(get_config('system','server_role') === 'basic') return; require_once('include/import.php'); /** @FIXME this will sync red structures (channel, pconfig and abook). Eventually we need to make this application agnostic. */ $result = array(); foreach ($deliveries as $d) { $r = q("select * from channel where channel_hash = '%s' limit 1", dbesc($d['hash']) ); if (! $r) { $result[] = array($d['hash'],'not found'); continue; } $channel = $r[0]; $max_friends = service_class_fetch($channel['channel_id'],'total_channels'); $max_feeds = account_service_class_fetch($channel['channel_account_id'],'total_feeds'); if($channel['channel_hash'] != $sender['hash']) { logger('process_channel_sync_delivery: possible forgery. Sender ' . $sender['hash'] . ' is not ' . $channel['channel_hash']); $result[] = array($d['hash'],'channel mismatch',$channel['channel_name'],''); continue; } if(array_key_exists('config',$arr) && is_array($arr['config']) && count($arr['config'])) { foreach($arr['config'] as $cat => $k) { foreach($arr['config'][$cat] as $k => $v) set_pconfig($channel['channel_id'],$cat,$k,$v); } } if(array_key_exists('obj',$arr) && $arr['obj']) sync_objs($channel,$arr['obj']); if(array_key_exists('likes',$arr) && $arr['likes']) import_likes($channel,$arr['likes']); if(array_key_exists('app',$arr) && $arr['app']) sync_apps($channel,$arr['app']); if(array_key_exists('chatroom',$arr) && $arr['chatroom']) sync_chatrooms($channel,$arr['chatroom']); if(array_key_exists('conv',$arr) && $arr['conv']) import_conv($channel,$arr['conv']); if(array_key_exists('mail',$arr) && $arr['mail']) sync_mail($channel,$arr['mail']); if(array_key_exists('event',$arr) && $arr['event']) sync_events($channel,$arr['event']); if(array_key_exists('event_item',$arr) && $arr['event_item']) sync_items($channel,$arr['event_item'],((array_key_exists('relocate',$arr)) ? $arr['relocate'] : null)); if(array_key_exists('item',$arr) && $arr['item']) sync_items($channel,$arr['item'],((array_key_exists('relocate',$arr)) ? $arr['relocate'] : null)); // deprecated, maintaining for a few months for upward compatibility // this should sync webpages, but the logic is a bit subtle if(array_key_exists('item_id',$arr) && $arr['item_id']) sync_items($channel,$arr['item_id']); if(array_key_exists('menu',$arr) && $arr['menu']) sync_menus($channel,$arr['menu']); if(array_key_exists('file',$arr) && $arr['file']) sync_files($channel,$arr['file']); if(array_key_exists('channel',$arr) && is_array($arr['channel']) && count($arr['channel'])) { translate_channel_perms_inbound($arr['channel']); if(array_key_exists('channel_pageflags',$arr['channel']) && intval($arr['channel']['channel_pageflags'])) { // These flags cannot be sync'd. // remove the bits from the incoming flags. // These correspond to PAGE_REMOVED and PAGE_SYSTEM on redmatrix if($arr['channel']['channel_pageflags'] & 0x8000) $arr['channel']['channel_pageflags'] = $arr['channel']['channel_pageflags'] - 0x8000; if($arr['channel']['channel_pageflags'] & 0x1000) $arr['channel']['channel_pageflags'] = $arr['channel']['channel_pageflags'] - 0x1000; } $disallowed = [ 'channel_id', 'channel_account_id', 'channel_primary', 'channel_prvkey', 'channel_address', 'channel_notifyflags', 'channel_removed', 'channel_deleted', 'channel_system', 'channel_r_stream', 'channel_r_profile', 'channel_r_abook', 'channel_r_storage', 'channel_r_pages', 'channel_w_stream', 'channel_w_wall', 'channel_w_comment', 'channel_w_mail', 'channel_w_like', 'channel_w_tagwall', 'channel_w_chat', 'channel_w_storage', 'channel_w_pages', 'channel_a_republish', 'channel_a_delegate' ]; $clean = array(); foreach($arr['channel'] as $k => $v) { if(in_array($k,$disallowed)) continue; $clean[$k] = $v; } if(count($clean)) { foreach($clean as $k => $v) { $r = dbq("UPDATE channel set " . dbesc($k) . " = '" . dbesc($v) . "' where channel_id = " . intval($channel['channel_id']) ); } } } if(array_key_exists('abook',$arr) && is_array($arr['abook']) && count($arr['abook'])) { $total_friends = 0; $total_feeds = 0; $r = q("select abook_id, abook_feed from abook where abook_channel = %d", intval($channel['channel_id']) ); if($r) { // don't count yourself $total_friends = ((count($r) > 0) ? count($r) - 1 : 0); foreach($r as $rr) if(intval($rr['abook_feed'])) $total_feeds ++; } $disallowed = array('abook_id','abook_account','abook_channel','abook_rating','abook_rating_text'); foreach($arr['abook'] as $abook) { $abconfig = null; if(array_key_exists('abconfig',$abook) && is_array($abook['abconfig']) && count($abook['abconfig'])) $abconfig = $abook['abconfig']; if(! array_key_exists('abook_blocked',$abook)) { // convert from redmatrix $abook['abook_blocked'] = (($abook['abook_flags'] & 0x0001) ? 1 : 0); $abook['abook_ignored'] = (($abook['abook_flags'] & 0x0002) ? 1 : 0); $abook['abook_hidden'] = (($abook['abook_flags'] & 0x0004) ? 1 : 0); $abook['abook_archived'] = (($abook['abook_flags'] & 0x0008) ? 1 : 0); $abook['abook_pending'] = (($abook['abook_flags'] & 0x0010) ? 1 : 0); $abook['abook_unconnected'] = (($abook['abook_flags'] & 0x0020) ? 1 : 0); $abook['abook_self'] = (($abook['abook_flags'] & 0x0080) ? 1 : 0); $abook['abook_feed'] = (($abook['abook_flags'] & 0x0100) ? 1 : 0); } $clean = array(); if($abook['abook_xchan'] && $abook['entry_deleted']) { logger('process_channel_sync_delivery: removing abook entry for ' . $abook['abook_xchan']); $r = q("select abook_id, abook_feed from abook where abook_xchan = '%s' and abook_channel = %d and abook_self = 0 limit 1", dbesc($abook['abook_xchan']), intval($channel['channel_id']) ); if($r) { contact_remove($channel['channel_id'],$r[0]['abook_id']); if($total_friends) $total_friends --; if(intval($r[0]['abook_feed'])) $total_feeds --; } continue; } // Perform discovery if the referenced xchan hasn't ever been seen on this hub. // This relies on the undocumented behaviour that red sites send xchan info with the abook // and import_author_xchan will look them up on all federated networks if($abook['abook_xchan'] && $abook['xchan_addr']) { $h = zot_get_hublocs($abook['abook_xchan']); if(! $h) { $xhash = import_author_xchan(encode_item_xchan($abook)); if(! $xhash) { logger('process_channel_sync_delivery: import of ' . $abook['xchan_addr'] . ' failed.'); continue; } } } foreach($abook as $k => $v) { if(in_array($k,$disallowed) || (strpos($k,'abook') !== 0)) continue; $clean[$k] = $v; } if(! array_key_exists('abook_xchan',$clean)) continue; $r = q("select * from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($clean['abook_xchan']), intval($channel['channel_id']) ); // make sure we have an abook entry for this xchan on this system if(! $r) { if($max_friends !== false && $total_friends > $max_friends) { logger('process_channel_sync_delivery: total_channels service class limit exceeded'); continue; } if($max_feeds !== false && intval($clean['abook_feed']) && $total_feeds > $max_feeds) { logger('process_channel_sync_delivery: total_feeds service class limit exceeded'); continue; } q("insert into abook ( abook_xchan, abook_account, abook_channel ) values ('%s', %d, %d ) ", dbesc($clean['abook_xchan']), intval($channel['channel_account_id']), intval($channel['channel_id']) ); $total_friends ++; if(intval($clean['abook_feed'])) $total_feeds ++; } if(count($clean)) { foreach($clean as $k => $v) { if($k == 'abook_dob') $v = dbescdate($v); $r = dbq("UPDATE abook set " . dbesc($k) . " = '" . dbesc($v) . "' where abook_xchan = '" . dbesc($clean['abook_xchan']) . "' and abook_channel = " . intval($channel['channel_id'])); } } // This will set abconfig vars if the sender is using old-style fixed permissions // using the raw abook record as passed to us. New-style permissions will fall through // and be set using abconfig translate_abook_perms_inbound($channel,$abook); if($abconfig) { // @fixme does not handle sync of del_abconfig foreach($abconfig as $abc) { set_abconfig($channel['channel_id'],$abc['xchan'],$abc['cat'],$abc['k'],$abc['v']); } } } } // sync collections (privacy groups) oh joy... if(array_key_exists('collections',$arr) && is_array($arr['collections']) && count($arr['collections'])) { $x = q("select * from groups where uid = %d", intval($channel['channel_id']) ); foreach($arr['collections'] as $cl) { $found = false; if($x) { foreach($x as $y) { if($cl['collection'] == $y['hash']) { $found = true; break; } } if($found) { if(($y['gname'] != $cl['name']) || ($y['visible'] != $cl['visible']) || ($y['deleted'] != $cl['deleted'])) { q("update groups set gname = '%s', visible = %d, deleted = %d where hash = '%s' and uid = %d", dbesc($cl['name']), intval($cl['visible']), intval($cl['deleted']), dbesc($cl['hash']), intval($channel['channel_id']) ); } if(intval($cl['deleted']) && (! intval($y['deleted']))) { q("delete from group_member where gid = %d", intval($y['id']) ); } } } if(! $found) { $r = q("INSERT INTO `groups` ( hash, uid, visible, deleted, gname ) VALUES( '%s', %d, %d, %d, '%s' ) ", dbesc($cl['collection']), intval($channel['channel_id']), intval($cl['visible']), intval($cl['deleted']), dbesc($cl['name']) ); } // now look for any collections locally which weren't in the list we just received. // They need to be removed by marking deleted and removing the members. // This shouldn't happen except for clones created before this function was written. if($x) { $found_local = false; foreach($x as $y) { foreach($arr['collections'] as $cl) { if($cl['collection'] == $y['hash']) { $found_local = true; break; } } if(! $found_local) { q("delete from group_member where gid = %d", intval($y['id']) ); q("update groups set deleted = 1 where id = %d and uid = %d", intval($y['id']), intval($channel['channel_id']) ); } } } } // reload the group list with any updates $x = q("select * from groups where uid = %d", intval($channel['channel_id']) ); // now sync the members if(array_key_exists('collection_members', $arr) && is_array($arr['collection_members']) && count($arr['collection_members'])) { // first sort into groups keyed by the group hash $members = array(); foreach($arr['collection_members'] as $cm) { if(! array_key_exists($cm['collection'],$members)) $members[$cm['collection']] = array(); $members[$cm['collection']][] = $cm['member']; } // our group list is already synchronised if($x) { foreach($x as $y) { // for each group, loop on members list we just received foreach($members[$y['hash']] as $member) { $found = false; $z = q("select xchan from group_member where gid = %d and uid = %d and xchan = '%s' limit 1", intval($y['id']), intval($channel['channel_id']), dbesc($member) ); if($z) $found = true; // if somebody is in the group that wasn't before - add them if(! $found) { q("INSERT INTO `group_member` (`uid`, `gid`, `xchan`) VALUES( %d, %d, '%s' ) ", intval($channel['channel_id']), intval($y['id']), dbesc($member) ); } } // now retrieve a list of members we have on this site $m = q("select xchan from group_member where gid = %d and uid = %d", intval($y['id']), intval($channel['channel_id']) ); if($m) { foreach($m as $mm) { // if the local existing member isn't in the list we just received - remove them if(! in_array($mm['xchan'],$members[$y['hash']])) { q("delete from group_member where xchan = '%s' and gid = %d and uid = %d", dbesc($mm['xchan']), intval($y['id']), intval($channel['channel_id']) ); } } } } } } } if(array_key_exists('profile',$arr) && is_array($arr['profile']) && count($arr['profile'])) { $disallowed = array('id','aid','uid','guid'); foreach($arr['profile'] as $profile) { $x = q("select * from profile where profile_guid = '%s' and uid = %d limit 1", dbesc($profile['profile_guid']), intval($channel['channel_id']) ); if(! $x) { q("insert into profile ( profile_guid, aid, uid ) values ('%s', %d, %d)", dbesc($profile['profile_guid']), intval($channel['channel_account_id']), intval($channel['channel_id']) ); $x = q("select * from profile where profile_guid = '%s' and uid = %d limit 1", dbesc($profile['profile_guid']), intval($channel['channel_id']) ); if(! $x) continue; } $clean = array(); foreach($profile as $k => $v) { if(in_array($k,$disallowed)) continue; if($k === 'name') $clean['fullname'] = $v; elseif($k === 'with') $clean['partner'] = $v; elseif($k === 'work') $clean['employment'] = $v; elseif(array_key_exists($k,$x[0])) $clean[$k] = $v; /** * @TODO * We also need to import local photos if a custom photo is selected */ } if(count($clean)) { foreach($clean as $k => $v) { $r = dbq("UPDATE profile set `" . dbesc($k) . "` = '" . dbesc($v) . "' where profile_guid = '" . dbesc($profile['profile_guid']) . "' and uid = " . intval($channel['channel_id'])); } } } } $addon = array('channel' => $channel,'data' => $arr); call_hooks('process_channel_sync_delivery',$addon); // we should probably do this for all items, but usually we only send one. if(array_key_exists('item',$arr) && is_array($arr['item'][0])) { $DR = new Zotlabs\Zot\DReport(z_root(),$d['hash'],$d['hash'],$arr['item'][0]['message_id'],'channel sync processed'); $DR->addto_recipient($channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . App::get_hostname() . '>'); } else $DR = new Zotlabs\Zot\DReport(z_root(),$d['hash'],$d['hash'],'sync packet','channel sync delivered'); $result[] = $DR->get(); } return $result; } /** * @brief Returns path to /rpost * * @todo We probably should make rpost discoverable. * * @param array $observer * * \e string \b xchan_url * @return string */ function get_rpost_path($observer) { if(! $observer) return ''; $parsed = parse_url($observer['xchan_url']); return $parsed['scheme'] . '://' . $parsed['host'] . (($parsed['port']) ? ':' . $parsed['port'] : '') . '/rpost?f='; } /** * @brief * * @param array $x * @return boolean|string return false or a hash */ function import_author_zot($x) { $hash = make_xchan_hash($x['guid'],$x['guid_sig']); $r = q("select hubloc_url from hubloc where hubloc_guid = '%s' and hubloc_guid_sig = '%s' and hubloc_primary = 1 limit 1", dbesc($x['guid']), dbesc($x['guid_sig']) ); if ($r) { logger('import_author_zot: in cache', LOGGER_DEBUG); return $hash; } logger('import_author_zot: entry not in cache - probing: ' . print_r($x,true), LOGGER_DEBUG); $them = array('hubloc_url' => $x['url'], 'xchan_guid' => $x['guid'], 'xchan_guid_sig' => $x['guid_sig']); if (zot_refresh($them)) return $hash; return false; } /** * @brief Process a message request. * * If a site receives a comment to a post but finds they have no parent to attach it with, they * may send a 'request' packet containing the message_id of the missing parent. This is the handler * for that packet. We will create a message_list array of the entire conversation starting with * the missing parent and invoke delivery to the sender of the packet. * * include/deliver.php (for local delivery) and mod/post.php (for web delivery) detect the existence of * this 'message_list' at the destination and split it into individual messages which are * processed/delivered in order. * * Called from mod/post.php * * @param array $data * @return array */ function zot_reply_message_request($data) { $ret = array('success' => false); if (! $data['message_id']) { $ret['message'] = 'no message_id'; logger('no message_id'); json_return_and_die($ret); } $sender = $data['sender']; $sender_hash = make_xchan_hash($sender['guid'], $sender['guid_sig']); /* * Find the local channel in charge of this post (the first and only recipient of the request packet) */ $arr = $data['recipients'][0]; $recip_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']); $c = q("select * from channel left join xchan on channel_hash = xchan_hash where channel_hash = '%s' limit 1", dbesc($recip_hash) ); if (! $c) { logger('recipient channel not found.'); $ret['message'] .= 'recipient not found.' . EOL; json_return_and_die($ret); } /* * fetch the requested conversation */ $messages = zot_feed($c[0]['channel_id'],$sender_hash,array('message_id' => $data['message_id'])); if ($messages) { $env_recips = null; $r = q("select * from hubloc where hubloc_hash = '%s' and hubloc_error = 0 and hubloc_deleted = 0 group by hubloc_sitekey", dbesc($sender_hash) ); if (! $r) { logger('no hubs'); json_return_and_die($ret); } $hubs = $r; $private = ((array_key_exists('flags', $messages[0]) && in_array('private',$messages[0]['flags'])) ? true : false); if($private) $env_recips = array('guid' => $sender['guid'], 'guid_sig' => $sender['guid_sig'], 'hash' => $sender_hash); $data_packet = json_encode(array('message_list' => $messages)); foreach($hubs as $hub) { $hash = random_string(); /* * create a notify packet and drop the actual message packet in the queue for pickup */ $n = zot_build_packet($c[0],'notify',$env_recips,(($private) ? $hub['hubloc_sitekey'] : null),$hash,array('message_id' => $data['message_id'])); queue_insert(array( 'hash' => $hash, 'account_id' => $c[0]['channel_account_id'], 'channel_id' => $c[0]['channel_id'], 'posturl' => $hub['hubloc_callback'], 'notify' => $n, 'msg' => $data_packet )); /* * invoke delivery to send out the notify packet */ Zotlabs\Daemon\Master::Summon(array('Deliver', $hash)); } } $ret['success'] = true; json_return_and_die($ret); } function zotinfo($arr) { $ret = array('success' => false); $zhash = ((x($arr,'guid_hash')) ? $arr['guid_hash'] : ''); $zguid = ((x($arr,'guid')) ? $arr['guid'] : ''); $zguid_sig = ((x($arr,'guid_sig')) ? $arr['guid_sig'] : ''); $zaddr = ((x($arr,'address')) ? $arr['address'] : ''); $ztarget = ((x($arr,'target')) ? $arr['target'] : ''); $zsig = ((x($arr,'target_sig')) ? $arr['target_sig'] : ''); $zkey = ((x($arr,'key')) ? $arr['key'] : ''); $mindate = ((x($arr,'mindate')) ? $arr['mindate'] : ''); $token = ((x($arr,'token')) ? $arr['token'] : ''); $feed = ((x($arr,'feed')) ? intval($arr['feed']) : 0); if($ztarget) { if((! $zkey) || (! $zsig) || (! rsa_verify($ztarget,base64url_decode($zsig),$zkey))) { logger('zfinger: invalid target signature'); $ret['message'] = t("invalid target signature"); return($ret); } } $ztarget_hash = (($ztarget && $zsig) ? make_xchan_hash($ztarget,$zsig) : '' ); $r = null; if(strlen($zhash)) { $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_hash = '%s' limit 1", dbesc($zhash) ); } elseif(strlen($zguid) && strlen($zguid_sig)) { $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_guid = '%s' and channel_guid_sig = '%s' limit 1", dbesc($zguid), dbesc($zguid_sig) ); } elseif(strlen($zaddr)) { if(strpos($zaddr,'[system]') === false) { /* normal address lookup */ $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where ( channel_address = '%s' or xchan_addr = '%s' ) limit 1", dbesc($zaddr), dbesc($zaddr) ); } else { /** * The special address '[system]' will return a system channel if one has been defined, * Or the first valid channel we find if there are no system channels. * * This is used by magic-auth if we have no prior communications with this site - and * returns an identity on this site which we can use to create a valid hub record so that * we can exchange signed messages. The precise identity is irrelevant. It's the hub * information that we really need at the other end - and this will return it. * */ $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_system = 1 order by channel_id limit 1"); if(! $r) { $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_removed = 0 order by channel_id limit 1"); } } } else { $ret['message'] = 'Invalid request'; return($ret); } if(! $r) { $ret['message'] = 'Item not found.'; return($ret); } $e = $r[0]; $id = $e['channel_id']; $sys_channel = (intval($e['channel_system']) ? true : false); $special_channel = (($e['channel_pageflags'] & PAGE_PREMIUM) ? true : false); $adult_channel = (($e['channel_pageflags'] & PAGE_ADULT) ? true : false); $censored = (($e['channel_pageflags'] & PAGE_CENSORED) ? true : false); $searchable = (($e['channel_pageflags'] & PAGE_HIDDEN) ? false : true); $deleted = (intval($e['xchan_deleted']) ? true : false); if($deleted || $censored || $sys_channel) $searchable = false; $public_forum = false; $role = get_pconfig($e['channel_id'],'system','permissions_role'); if($role === 'forum' || $role === 'repository') { $public_forum = true; } elseif($ztarget_hash) { // check if it has characteristics of a public forum based on custom permissions. $t = q("select * from abconfig where abconfig.cat = 'my_perms' and abconfig.chan = %d and abconfig.xchan = '%s' and abconfig.k in ('tag_deliver', 'send_stream') ", intval($e['channel_id']), dbesc($ztarget_hash) ); $ch = 0; if($t) { foreach($t as $tt) { if($tt['k'] == 'tag_deliver' && $tt['v'] == 1) $ch ++; if($tt['k'] == 'send_stream' && $tt['v'] == 0) $ch ++; } if($ch == 2) $public_forum = true; } } // This is for birthdays and keywords, but must check access permissions $p = q("select * from profile where uid = %d and is_default = 1", intval($e['channel_id']) ); $profile = array(); if($p) { if(! intval($p[0]['publish'])) $searchable = false; $profile['description'] = $p[0]['pdesc']; $profile['birthday'] = $p[0]['dob']; if(($profile['birthday'] != '0000-00-00') && (($bd = z_birthday($p[0]['dob'],$e['channel_timezone'])) !== '')) $profile['next_birthday'] = $bd; if($age = age($p[0]['dob'],$e['channel_timezone'],'')) $profile['age'] = $age; $profile['gender'] = $p[0]['gender']; $profile['marital'] = $p[0]['marital']; $profile['sexual'] = $p[0]['sexual']; $profile['locale'] = $p[0]['locality']; $profile['region'] = $p[0]['region']; $profile['postcode'] = $p[0]['postal_code']; $profile['country'] = $p[0]['country_name']; $profile['about'] = $p[0]['about']; $profile['homepage'] = $p[0]['homepage']; $profile['hometown'] = $p[0]['hometown']; if($p[0]['keywords']) { $tags = array(); $k = explode(' ',$p[0]['keywords']); if($k) { foreach($k as $kk) { if(trim($kk," \t\n\r\0\x0B,")) { $tags[] = trim($kk," \t\n\r\0\x0B,"); } } } if($tags) $profile['keywords'] = $tags; } } $ret['success'] = true; // Communication details if($token) $ret['signed_token'] = base64url_encode(rsa_sign('token.' . $token,$e['channel_prvkey'])); $ret['guid'] = $e['xchan_guid']; $ret['guid_sig'] = $e['xchan_guid_sig']; $ret['key'] = $e['xchan_pubkey']; $ret['name'] = $e['xchan_name']; $ret['name_updated'] = $e['xchan_name_date']; $ret['address'] = $e['xchan_addr']; $ret['photo_mimetype'] = $e['xchan_photo_mimetype']; $ret['photo'] = $e['xchan_photo_l']; $ret['photo_updated'] = $e['xchan_photo_date']; $ret['url'] = $e['xchan_url']; $ret['connections_url']= (($e['xchan_connurl']) ? $e['xchan_connurl'] : z_root() . '/poco/' . $e['channel_address']); $ret['target'] = $ztarget; $ret['target_sig'] = $zsig; $ret['searchable'] = $searchable; $ret['adult_content'] = $adult_channel; $ret['public_forum'] = $public_forum; if($deleted) $ret['deleted'] = $deleted; if(intval($e['channel_removed'])) $ret['deleted_locally'] = true; // premium or other channel desiring some contact with potential followers before connecting. // This is a template - %s will be replaced with the follow_url we discover for the return channel. if($special_channel) $ret['connect_url'] = z_root() . '/connect/' . $e['channel_address']; // This is a template for our follow url, %s will be replaced with a webbie $ret['follow_url'] = z_root() . '/follow?f=&url=%s'; $permissions = get_all_perms($e['channel_id'],$ztarget_hash,false); if($ztarget_hash) { $permissions['connected'] = false; $b = q("select * from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($ztarget_hash), intval($e['channel_id']) ); if($b) $permissions['connected'] = true; } $ret['permissions'] = (($ztarget && $zkey) ? crypto_encapsulate(json_encode($permissions),$zkey) : $permissions); if($permissions['view_profile']) $ret['profile'] = $profile; // array of (verified) hubs this channel uses $x = zot_encode_locations($e); if($x) $ret['locations'] = $x; $ret['site'] = array(); $ret['site']['url'] = z_root(); $ret['site']['url_sig'] = base64url_encode(rsa_sign(z_root(),$e['channel_prvkey'])); $ret['site']['zot_auth'] = z_root() . '/magic'; $dirmode = get_config('system','directory_mode'); if(($dirmode === false) || ($dirmode == DIRECTORY_MODE_NORMAL)) $ret['site']['directory_mode'] = 'normal'; if($dirmode == DIRECTORY_MODE_PRIMARY) $ret['site']['directory_mode'] = 'primary'; elseif($dirmode == DIRECTORY_MODE_SECONDARY) $ret['site']['directory_mode'] = 'secondary'; elseif($dirmode == DIRECTORY_MODE_STANDALONE) $ret['site']['directory_mode'] = 'standalone'; if($dirmode != DIRECTORY_MODE_NORMAL) $ret['site']['directory_url'] = z_root() . '/dirsearch'; // hide detailed site information if you're off the grid if($dirmode != DIRECTORY_MODE_STANDALONE) { $register_policy = intval(get_config('system','register_policy')); if($register_policy == REGISTER_CLOSED) $ret['site']['register_policy'] = 'closed'; if($register_policy == REGISTER_APPROVE) $ret['site']['register_policy'] = 'approve'; if($register_policy == REGISTER_OPEN) $ret['site']['register_policy'] = 'open'; $access_policy = intval(get_config('system','access_policy')); if($access_policy == ACCESS_PRIVATE) $ret['site']['access_policy'] = 'private'; if($access_policy == ACCESS_PAID) $ret['site']['access_policy'] = 'paid'; if($access_policy == ACCESS_FREE) $ret['site']['access_policy'] = 'free'; if($access_policy == ACCESS_TIERED) $ret['site']['access_policy'] = 'tiered'; $ret['site']['accounts'] = account_total(); require_once('include/channel.php'); $ret['site']['channels'] = channel_total(); $ret['site']['version'] = Zotlabs\Lib\System::get_platform_name() . ' ' . STD_VERSION . '[' . DB_UPDATE_VERSION . ']'; $ret['site']['admin'] = get_config('system','admin_email'); $visible_plugins = array(); if(is_array(App::$plugins) && count(App::$plugins)) { $r = q("select * from addon where hidden = 0"); if($r) foreach($r as $rr) $visible_plugins[] = $rr['name']; } $ret['site']['plugins'] = $visible_plugins; $ret['site']['sitehash'] = get_config('system','location_hash'); $ret['site']['sitename'] = get_config('system','sitename'); $ret['site']['sellpage'] = get_config('system','sellpage'); $ret['site']['location'] = get_config('system','site_location'); $ret['site']['realm'] = get_directory_realm(); $ret['site']['project'] = Zotlabs\Lib\System::get_platform_name() . ' ' . Zotlabs\Lib\System::get_server_role(); } check_zotinfo($e,$x,$ret); call_hooks('zot_finger',$ret); return($ret); } function check_zotinfo($channel,$locations,&$ret) { // logger('locations: ' . print_r($locations,true),LOGGER_DATA, LOG_DEBUG); // This function will likely expand as we find more things to detect and fix. // 1. Because magic-auth is reliant on it, ensure that the system channel has a valid hubloc // Force this to be the case if anything is found to be wrong with it. // @FIXME ensure that the system channel exists in the first place and has an xchan if($channel['channel_system']) { // the sys channel must have a location (hubloc) $valid_location = false; if((count($locations) === 1) && ($locations[0]['primary']) && (! $locations[0]['deleted'])) { if((rsa_verify($locations[0]['url'],base64url_decode($locations[0]['url_sig']),$channel['channel_pubkey'])) && ($locations[0]['sitekey'] === get_config('system','pubkey')) && ($locations[0]['url'] === z_root())) $valid_location = true; else logger('sys channel: invalid url signature'); } if((! $locations) || (! $valid_location)) { logger('System channel locations are not valid. Attempting repair.'); // Don't trust any existing records. Just get rid of them, but only do this // for the sys channel as normal channels will be trickier. q("delete from hubloc where hubloc_hash = '%s'", dbesc($channel['channel_hash']) ); $r = q("insert into hubloc ( hubloc_guid, hubloc_guid_sig, hubloc_hash, hubloc_addr, hubloc_primary, hubloc_url, hubloc_url_sig, hubloc_host, hubloc_callback, hubloc_sitekey, hubloc_network ) values ( '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s' )", dbesc($channel['channel_guid']), dbesc($channel['channel_guid_sig']), dbesc($channel['channel_hash']), dbesc($channel['channel_address'] . '@' . App::get_hostname()), intval(1), dbesc(z_root()), dbesc(base64url_encode(rsa_sign(z_root(),$channel['channel_prvkey']))), dbesc(App::get_hostname()), dbesc(z_root() . '/post'), dbesc(get_config('system','pubkey')), dbesc('zot') ); if($r) { $x = zot_encode_locations($channel); if($x) { $ret['locations'] = $x; } } else { logger('Unable to store sys hub location'); } } } } function delivery_report_is_storable($dr) { if(get_config('system','disable_dreport')) return false; call_hooks('dreport_is_storable',$dr); // let plugins accept or reject - if neither, continue on if(array_key_exists('accept',$dr) && intval($dr['accept'])) return true; if(array_key_exists('reject',$dr) && intval($dr['reject'])) return false; if(! ($dr['sender'])) return false; // Is the sender one of our channels? $c = q("select channel_id from channel where channel_hash = '%s' limit 1", dbesc($dr['sender']) ); if(! $c) return false; // is the recipient one of our connections, or do we want to store every report? $r = explode(' ', $dr['recipient']); $rxchan = $r[0]; $pcf = get_pconfig($c[0]['channel_id'],'system','dreport_store_all'); if($pcf) return true; // We always add ourself as a recipient to private and relayed posts // So if a remote site says they can't find us, that's no big surprise // and just creates a lot of extra report noise if(($dr['location'] !== z_root()) && ($dr['sender'] === $rxchan) && ($dr['status'] === 'recipient_not_found')) return false; // If you have a private post with a recipient list, every single site is going to report // back a failed delivery for anybody on that list that isn't local to them. We're only // concerned about this if we have a local hubloc record which says we expected them to // have a channel on that site. $r = q("select hubloc_id from hubloc where hubloc_hash = '%s' and hubloc_url = '%s'", dbesc($rxchan), dbesc($dr['location']) ); if((! $r) && ($dr['status'] === 'recipient_not_found')) return false; $r = q("select abook_id from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($rxchan), intval($c[0]['channel_id']) ); if($r) return true; return false; } function update_hub_connected($hub,$sitekey = '') { if($sitekey) { /* * This hub has now been proven to be valid. * Any hub with the same URL and a different sitekey cannot be valid. * Get rid of them (mark them deleted). There's a good chance they were re-installs. */ q("update hubloc set hubloc_deleted = 1, hubloc_error = 1 where hubloc_url = '%s' and hubloc_sitekey != '%s' ", dbesc($hub['hubloc_url']), dbesc($sitekey) ); } else { $sitekey = $hub['sitekey']; } // $sender['sitekey'] is a new addition to the protocol to distinguish // hublocs coming from re-installed sites. Older sites will not provide // this field and we have to still mark them valid, since we can't tell // if this hubloc has the same sitekey as the packet we received. // Update our DB to show when we last communicated successfully with this hub // This will allow us to prune dead hubs from using up resources $t = datetime_convert('UTC','UTC','now - 15 minutes'); $r = q("update hubloc set hubloc_connected = '%s' where hubloc_id = %d and hubloc_sitekey = '%s' and hubloc_connected < '%s' ", dbesc(datetime_convert()), intval($hub['hubloc_id']), dbesc($sitekey), dbesc($t) ); // a dead hub came back to life - reset any tombstones we might have if(intval($hub['hubloc_error'])) { q("update hubloc set hubloc_error = 0 where hubloc_id = %d and hubloc_sitekey = '%s' ", intval($hub['hubloc_id']), dbesc($sitekey) ); if(intval($r[0]['hubloc_orphancheck'])) { q("update hubloc set hubloc_orhpancheck = 0 where hubloc_id = %d and hubloc_sitekey = '%s' ", intval($hub['hubloc_id']), dbesc($sitekey) ); } q("update xchan set xchan_orphan = 0 where xchan_orphan = 1 and xchan_hash = '%s'", dbesc($hub['hubloc_hash']) ); } return $hub['hubloc_url']; } function zot_reply_ping() { $ret = array('success'=> false); // Useful to get a health check on a remote site. // This will let us know if any important communication details // that we may have stored are no longer valid, regardless of xchan details. logger('POST: got ping send pong now back: ' . z_root() , LOGGER_DEBUG ); $ret['success'] = true; $ret['site'] = array(); $ret['site']['url'] = z_root(); $ret['site']['url_sig'] = base64url_encode(rsa_sign(z_root(),get_config('system','prvkey'))); $ret['site']['sitekey'] = get_config('system','pubkey'); json_return_and_die($ret); } function zot_reply_pickup($data) { $ret = array('success'=> false); /* * The 'pickup' message arrives with a tracking ID which is associated with a particular outq_hash * First verify that that the returned signatures verify, then check that we have an outbound queue item * with the correct hash. * If everything verifies, find any/all outbound messages in the queue for this hubloc and send them back */ if((! $data['secret']) || (! $data['secret_sig'])) { $ret['message'] = 'no verification signature'; logger('mod_zot: pickup: ' . $ret['message'], LOGGER_DEBUG); json_return_and_die($ret); } $r = q("select distinct hubloc_sitekey from hubloc where hubloc_url = '%s' and hubloc_callback = '%s' and hubloc_sitekey != '' group by hubloc_sitekey ", dbesc($data['url']), dbesc($data['callback']) ); if(! $r) { $ret['message'] = 'site not found'; logger('mod_zot: pickup: ' . $ret['message']); json_return_and_die($ret); } foreach ($r as $hubsite) { // verify the url_sig // If the server was re-installed at some point, there could be multiple hubs with the same url and callback. // Only one will have a valid key. $forgery = true; $secret_fail = true; $sitekey = $hubsite['hubloc_sitekey']; logger('mod_zot: Checking sitekey: ' . $sitekey, LOGGER_DATA, LOG_DEBUG); if(rsa_verify($data['callback'],base64url_decode($data['callback_sig']),$sitekey)) { $forgery = false; } if(rsa_verify($data['secret'],base64url_decode($data['secret_sig']),$sitekey)) { $secret_fail = false; } if((! $forgery) && (! $secret_fail)) break; } if($forgery) { $ret['message'] = 'possible site forgery'; logger('mod_zot: pickup: ' . $ret['message']); json_return_and_die($ret); } if($secret_fail) { $ret['message'] = 'secret validation failed'; logger('mod_zot: pickup: ' . $ret['message']); json_return_and_die($ret); } /* * If we made it to here, the signatures verify, but we still don't know if the tracking ID is valid. * It wouldn't be an error if the tracking ID isn't found, because we may have sent this particular * queue item with another pickup (after the tracking ID for the other pickup was verified). */ $r = q("select outq_posturl from outq where outq_hash = '%s' and outq_posturl = '%s' limit 1", dbesc($data['secret']), dbesc($data['callback']) ); if(! $r) { $ret['message'] = 'nothing to pick up'; logger('mod_zot: pickup: ' . $ret['message']); json_return_and_die($ret); } /* * Everything is good if we made it here, so find all messages that are going to this location * and send them all. */ $r = q("select * from outq where outq_posturl = '%s'", dbesc($data['callback']) ); if($r) { logger('mod_zot: successful pickup message received from ' . $data['callback'] . ' ' . count($r) . ' message(s) picked up', LOGGER_DEBUG); $ret['success'] = true; $ret['pickup'] = array(); foreach($r as $rr) { if($rr['outq_msg']) { $x = json_decode($rr['outq_msg'],true); if(! $x) continue; if(is_array($x) && array_key_exists('message_list',$x)) { foreach($x['message_list'] as $xx) { $ret['pickup'][] = array('notify' => json_decode($rr['outq_notify'],true),'message' => $xx); } } else $ret['pickup'][] = array('notify' => json_decode($rr['outq_notify'],true),'message' => $x); remove_queue_item($rr['outq_hash']); } } } $encrypted = crypto_encapsulate(json_encode($ret),$sitekey); json_return_and_die($encrypted); /* pickup: end */ } function zot_reply_auth_check($data,$encrypted_packet) { $ret = array('success' => false); /* * Requestor visits /magic/?dest=somewhere on their own site with a browser * magic redirects them to $destsite/post [with auth args....] * $destsite sends an auth_check packet to originator site * The auth_check packet is handled here by the originator's site * - the browser session is still waiting * inside $destsite/post for everything to verify * If everything checks out we'll return a token to $destsite * and then $destsite will verify the token, authenticate the browser * session and then redirect to the original destination. * If authentication fails, the redirection to the original destination * will still take place but without authentication. */ logger('mod_zot: auth_check', LOGGER_DEBUG); if (! $encrypted_packet) { logger('mod_zot: auth_check packet was not encrypted.'); $ret['message'] .= 'no packet encryption' . EOL; json_return_and_die($ret); } $arr = $data['sender']; $sender_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']); // garbage collect any old unused notifications // This was and should be 10 minutes but my hosting provider has time lag between the DB and // the web server. We should probably convert this to webserver time rather than DB time so // that the different clocks won't affect it and allow us to keep the time short. Zotlabs\Zot\Verify::purge('auth','30 MINUTE'); $y = q("select xchan_pubkey from xchan where xchan_hash = '%s' limit 1", dbesc($sender_hash) ); // We created a unique hash in mod/magic.php when we invoked remote auth, and stored it in // the verify table. It is now coming back to us as 'secret' and is signed by a channel at the other end. // First verify their signature. We will have obtained a zot-info packet from them as part of the sender // verification. if ((! $y) || (! rsa_verify($data['secret'], base64url_decode($data['secret_sig']),$y[0]['xchan_pubkey']))) { logger('mod_zot: auth_check: sender not found or secret_sig invalid.'); $ret['message'] .= 'sender not found or sig invalid ' . print_r($y,true) . EOL; json_return_and_die($ret); } // There should be exactly one recipient, the original auth requestor $ret['message'] .= 'recipients ' . print_r($recipients,true) . EOL; if ($data['recipients']) { $arr = $data['recipients'][0]; $recip_hash = make_xchan_hash($arr['guid'], $arr['guid_sig']); $c = q("select channel_id, channel_account_id, channel_prvkey from channel where channel_hash = '%s' limit 1", dbesc($recip_hash) ); if (! $c) { logger('mod_zot: auth_check: recipient channel not found.'); $ret['message'] .= 'recipient not found.' . EOL; json_return_and_die($ret); } $confirm = base64url_encode(rsa_sign($data['secret'] . $recip_hash,$c[0]['channel_prvkey'])); // This additionally checks for forged sites since we already stored the expected result in meta // and we've already verified that this is them via zot_gethub() and that their key signed our token $z = Zotlabs\Zot\Verify::match('auth',$c[0]['channel_id'],$data['secret'],$data['sender']['url']); if (! $z) { logger('mod_zot: auth_check: verification key not found.'); $ret['message'] .= 'verification key not found' . EOL; json_return_and_die($ret); } $u = q("select account_service_class from account where account_id = %d limit 1", intval($c[0]['channel_account_id']) ); logger('mod_zot: auth_check: success', LOGGER_DEBUG); $ret['success'] = true; $ret['confirm'] = $confirm; if ($u && $u[0]['account_service_class']) $ret['service_class'] = $u[0]['account_service_class']; // Set "do not track" flag if this site or this channel's profile is restricted // in some way if (intval(get_config('system','block_public'))) $ret['DNT'] = true; if (! perm_is_allowed($c[0]['channel_id'],'','view_profile')) $ret['DNT'] = true; if (get_pconfig($c[0]['channel_id'],'system','do_not_track')) $ret['DNT'] = true; if (get_pconfig($c[0]['channel_id'],'system','hide_online_status')) $ret['DNT'] = true; json_return_and_die($ret); } json_return_and_die($ret); } function zot_reply_purge($sender,$recipients) { $ret = array('success' => false); if ($recipients) { // basically this means "unfriend" foreach ($recipients as $recip) { $r = q("select channel.*,xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_guid = '%s' and channel_guid_sig = '%s' limit 1", dbesc($recip['guid']), dbesc($recip['guid_sig']) ); if ($r) { $r = q("select abook_id from abook where uid = %d and abook_xchan = '%s' limit 1", intval($r[0]['channel_id']), dbesc(make_xchan_hash($sender['guid'],$sender['guid_sig'])) ); if ($r) { contact_remove($r[0]['channel_id'],$r[0]['abook_id']); } } } $ret['success'] = true; } else { // Unfriend everybody - basically this means the channel has committed suicide $arr = $sender; $sender_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']); remove_all_xchan_resources($sender_hash); $ret['success'] = true; } json_return_and_die($ret); } function zot_reply_refresh($sender,$recipients) { $ret = array('success' => false); // remote channel info (such as permissions or photo or something) // has been updated. Grab a fresh copy and sync it. // The difference between refresh and force_refresh is that // force_refresh unconditionally creates a directory update record, // even if no changes were detected upon processing. if($recipients) { // This would be a permissions update, typically for one connection foreach ($recipients as $recip) { $r = q("select channel.*,xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_guid = '%s' and channel_guid_sig = '%s' limit 1", dbesc($recip['guid']), dbesc($recip['guid_sig']) ); $x = zot_refresh(array( 'xchan_guid' => $sender['guid'], 'xchan_guid_sig' => $sender['guid_sig'], 'hubloc_url' => $sender['url'] ), $r[0], (($msgtype === 'force_refresh') ? true : false)); } } else { // system wide refresh $x = zot_refresh(array( 'xchan_guid' => $sender['guid'], 'xchan_guid_sig' => $sender['guid_sig'], 'hubloc_url' => $sender['url'] ), null, (($msgtype === 'force_refresh') ? true : false)); } $ret['success'] = true; json_return_and_die($ret); } function zot_reply_notify($data) { $ret = array('success' => false); logger('notify received from ' . $data['sender']['url']); $async = get_config('system','queued_fetch'); if($async) { // add to receive queue // qreceive_add($data); } else { $x = zot_fetch($data); $ret['delivery_report'] = $x; } $ret['success'] = true; json_return_and_die($ret); }
HaakonME/hubzilla
include/zot.php
PHP
mit
147,068
/** * */ package org.edtoktay.dynamic.compiler; /** * @author deniz.toktay * */ public interface ExampleInterface { void addObject(String arg1, String arg2); Object getObject(String arg1); }
edtoktay/DynamicCompiler
Example/src/main/java/org/edtoktay/dynamic/compiler/ExampleInterface.java
Java
mit
200
import React, { Component } from 'react'; import { StyleSheet, Text, View, Navigator, ScrollView, ListView, } from 'react-native' import NavigationBar from 'react-native-navbar'; var REQUEST_URL = 'https://calm-garden-29993.herokuapp.com/index/groupsinfo/?'; class GroupDetails extends Component { constructor(props, context) { super(props, context); this.state = { loggedIn: true, loaded: false, rando: "a", }; this.fetchData(); } backOnePage () { this.props.navigator.pop(); } renderRide (ride) { return ( <View> <Text style={styles.title}>{ride.title}</Text> </View> ); } componentDidMount () { this.fetchData(); } toQueryString(obj) { return obj ? Object.keys(obj).sort().map(function (key) { var val = obj[key]; if (Array.isArray(val)) { return val.sort().map(function (val2) { return encodeURIComponent(key) + '=' + encodeURIComponent(val2); }).join('&'); } return encodeURIComponent(key) + '=' + encodeURIComponent(val); }).join('&') : ''; } fetchData() { console.log(this.props.group_info.pk); fetch(REQUEST_URL + this.toQueryString({"group": this.props.group_info.pk})) .then((response) => response.json()) .then((responseData) => { console.log(responseData); this.setState({ group_info: responseData, loaded: true, }); }) .done(); } render () { if (!this.state.loaded) { return (<View> <Text>Loading!</Text> </View>); } else if (this.state.loggedIn) { console.log(this.props.group_info.fields); console.log(this.state); console.log(this.state.group_info[0]); const backButton = { title: "Back", handler: () => this.backOnePage(), }; return ( <ScrollView> <NavigationBar style={{ backgroundColor: "white", }} leftButton={backButton} statusBar={{ tintColor: "white", }} /> <Text style={styles.headTitle}> Group Name: {this.state.group_info.name} </Text> <Text style={styles.headerOtherText}>Group Leader: {this.state.group_info.admin}</Text> <Text style={styles.headerOtherText}>{this.state.group_info.users} people in this group.</Text> </ScrollView> ); } else { this.props.navigator.push({id: "LoginPage", name:"Index"}) } } } var styles = StyleSheet.create({ headerOtherText : { color: 'black', fontSize: 15 , fontWeight: 'normal', fontFamily: 'Helvetica Neue', alignSelf: "center", }, headTitle: { color: 'black', fontSize: 30 , fontWeight: 'normal', fontFamily: 'Helvetica Neue', alignSelf: "center", }, header: { marginTop: 20, flex: 1, flexDirection: "column", justifyContent: "center", alignItems: "center", }, container: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: '#ff7f50', }, rightContainer: { flex: 1, }, title: { fontSize: 20, marginBottom: 8, textAlign: 'center', }, year: { textAlign: 'center', }, thumbnail: { width: 53, height: 81, }, listView: { backgroundColor: '#0000ff', paddingBottom: 200, }, }); module.exports = GroupDetails;
adnanhemani/RideApp
App/GroupDetails.js
JavaScript
mit
3,798
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me cantango_user end
stanislaw/cantango_editor
spec/dummy/app/models/user.rb
Ruby
mit
460
process.stderr.write('Test');
patrick-steele-idem/child-process-promise
test/fixtures/stderr.js
JavaScript
mit
29
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wellspring.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
ushatil/wellness-tracker
ws/manage.py
Python
mit
253
package org.squirrel; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.Timer; import org.squirrel.managers.PrisonerControllor; import org.squirrel.managers.inputManager; import org.squirrel.objects.Player; import org.squirrel.ui.Hud; import org.squirrel.world.World; public class Game extends JPanel implements ActionListener{ private static final long serialVersionUID = -8805039320208612585L; public static String name = JOptionPane.showInputDialog(null,"What is your name?","Welcome to Prison Survival", JOptionPane.QUESTION_MESSAGE); Timer gameLoop; Player player; PrisonerControllor prict; Hud hud; World world1; public Game(){ setFocusable(true); gameLoop = new Timer(10, this); gameLoop.start(); player = new Player(300, 300); prict = new PrisonerControllor(); hud = new Hud(); world1 = new World(); addKeyListener(new inputManager(player)); } public void paint(Graphics g){ super.paint(g); Graphics2D g2d = (Graphics2D) g; //Camera int offsetMaxX = 1600 - 800; int offsetMaxY = 1200 - 600; int offsetMinX = 0; int offsetMinY = 0; int camX = player.getxPos() - 800 /2; int camY = player.getyPos() - 600 /2; //if (camX > offsetMaxX){ // camX = offsetMaxX; //} //else if (camX < offsetMinX){ // camX = offsetMinX; //} //if (camY > offsetMaxY){ // camY = offsetMaxY; //} //else if (camY < offsetMinY){ // camY = offsetMinY; //} g2d.translate(-camX, -camY); // Render everything world1.draw(g2d); hud.draw(g2d); prict.draw(g2d); player.draw(g2d); g.translate(camX, camY); } @Override public void actionPerformed(ActionEvent e) { try { player.update(); hud.update(); prict.update(); world1.update(); repaint(); } catch (Exception e1) { e1.printStackTrace(); } } }
DemSquirrel/Prison-Survival
src/org/squirrel/Game.java
Java
mit
1,974
(function () { 'use strict'; angular .module('app') .service('UploadUserLogoService', UploadUserLogoService); function UploadUserLogoService($http, $log, TokenService, UserService, $rootScope) { this.uploadImage = uploadImage; //// /** * Upload Image * @description For correct uploading we must send FormData object * With 'transformRequest: angular.identity' prevents Angular to do anything on our data (like serializing it). * By setting ‘Content-Type’: undefined, the browser sets the Content-Type to multipart/form-data for us * and fills in the correct boundary. * Manually setting ‘Content-Type’: multipart/form-data will fail to fill in the boundary parameter of the request * All this for correct request typing and uploading * @param formdata * @param callback */ function uploadImage(formdata, callback) { let userToken = TokenService.get(); let request = { method: 'POST', url: '/api/user/avatar', transformRequest: angular.identity, headers: { 'Content-Type': undefined, 'Autorization': userToken }, data: formdata }; let goodResponse = function successCallback(response) { let res = response.data; if (res.success) { let currentUser = UserService.get(); currentUser.avatarUrl = res.data.avatarUrl; UserService.save(currentUser); } if (callback && typeof callback === 'function') { callback(res); } }; let badResponse = function errorCallback(response) { $log.debug('Bad, some problems ', response); if (callback && typeof callback === 'function') { callback(response); } }; $http(request).then(goodResponse, badResponse); } } })();
royalrangers-ck/rr-web-app
app/utils/upload.user.logo/upload.user.logo.service.js
JavaScript
mit
2,187
<?php include 'vendor/autoload.php'; ini_set('error_reporting', E_ALL); ini_set('display_errors', '1'); ini_set('display_startup_errors', '1');
mkosolofski/houseseats-monitor
phpunit_bootstrap.php
PHP
mit
145