code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
#!/bin/bash -ex cd "$(dirname "$0")" docker run --rm \ -v "$PWD/.:/work" \ -w "/work" \ ruby:2.5 bash -ec " gem install -N parse_a_changelog parse ./CHANGELOG.md "
conjurinc/summon-chefapi
parse-changelog.sh
Shell
mit
183
<!DOCTYPE html> <html> <head> <title></title> <meta name="description" content="" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> <script type="text/javascript" src="../../../core/uni.js"></script> <script type="text/javascript"> uni .require('kits/xhr.js') .require('core/notify.js') .within(function() { this .xhr // No callback argument, just complete, also showing how to pass // through data. // .get('get.html', { async: true, // This will pass through to `ob`, below. // here: 'there', complete: function(data, ob) { this .notify(data) .notify(ob) } }) }) </script> </head> <body> <div id="test"> </div> </body> </html>
sandro-pasquali/Uni-Framework
uni/demos/kits/xhr/get.html
HTML
mit
917
<template name="loading"> <div class="ui active inline loader"></div> </template>
lackerman/meteor-semanticui-base
client/templates/includes/loading.html
HTML
mit
83
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
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:2.0.50727.1433 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings),MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.pmDebug.My.MySettings Get Return Global.pmDebug.My.MySettings.Default End Get End Property End Module End Namespace
pmprog/pmScript
pmDebug/My Project/Settings.Designer.vb
Visual Basic
mit
2,900
#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
#ifndef _SYSAPPDB_SYSAPPDBHELPER_H_ #define _SYSAPPDB_SYSAPPDBHELPER_H_ #include <vector> #include <map> #include <string> #include "sqlite3.h" std::vector<std::string> read_text_file(std::string path); std::vector<std::string> split_str(std::string src, char c); std::string join_str(std::vector<std::string> strings, std::string connector); template<typename K, typename V> std::vector<K> map_get_keys(std::map<K, V> map); template<typename K, typename V> std::vector<V> map_get_values(std::map<K, V> map); int db_insert(sqlite3* con, std::string table, std::map<std::string, std::string> values); template<typename C> std::vector<C> db_select(sqlite3* con, std::string table, std::string coloumn, std::string where_stmt); #endif
Silveryard/Car_System
Car/LibSysAppDB/SysAppDBHelper.h
C
mit
737
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
function SendMessage(a_Player, a_Message) a_Player:SendMessageInfo(a_Message) end function SendMessageSuccess(a_Player, a_Message) a_Player:SendMessageSuccess(a_Message) end function SendMessageFailure(a_Player, a_Message) a_Player:SendMessageFailure(a_Message) end --- Kicks a player by name, with the specified reason; returns bool whether found and player's real name function KickPlayer( PlayerName, Reason ) local RealName = "" if (Reason == nil) then Reason = "You have been kicked" end local FoundPlayerCallback = function( a_Player ) a_Player:GetClientHandle():Kick(Reason) return true end if not cRoot:Get():FindAndDoWithPlayer( PlayerName, FoundPlayerCallback ) then -- Could not find player return false end return true -- Player has been kicked end function ReturnColorFromChar(char) -- Check if the char represents a color. Else return nil. if char == "0" then return cChatColor.Black elseif char == "1" then return cChatColor.Navy elseif char == "2" then return cChatColor.Green elseif char == "3" then return cChatColor.Blue elseif char == "4" then return cChatColor.Red elseif char == "5" then return cChatColor.Purple elseif char == "6" then return cChatColor.Gold elseif char == "7" then return cChatColor.LightGray elseif char == "8" then return cChatColor.Gray elseif char == "9" then return cChatColor.DarkPurple elseif char == "a" then return cChatColor.LightGreen elseif char == "b" then return cChatColor.LightBlue elseif char == "c" then return cChatColor.Rose elseif char == "d" then return cChatColor.LightPurple elseif char == "e" then return cChatColor.Yellow elseif char == "f" then return cChatColor.White elseif char == "k" then return cChatColor.Random elseif char == "l" then return cChatColor.Bold elseif char == "m" then return cChatColor.Strikethrough elseif char == "n" then return cChatColor.Underlined elseif char == "o" then return cChatColor.Italic elseif char == "r" then return cChatColor.Plain end end -- Teleports a_SrcPlayer to a player named a_DstPlayerName; if a_TellDst is true, will send a notice to the destination player function TeleportToPlayer( a_SrcPlayer, a_DstPlayerName, a_TellDst ) local teleport = function(a_DstPlayerName) if a_DstPlayerName == a_SrcPlayer then -- Asked to teleport to self? SendMessageFailure( a_SrcPlayer, "Y' can't teleport to yerself" ) else -- If destination player is not in the same world, move to the correct world if a_SrcPlayer:GetWorld():GetName() ~= a_DstPlayerName:GetWorld():GetName() then a_SrcPlayer:MoveToWorld( a_DstPlayerName:GetWorld():GetName() ) end a_SrcPlayer:TeleportToEntity( a_DstPlayerName ) SendMessageSuccess( a_SrcPlayer, "You teleported to " .. a_DstPlayerName:GetName() ) if (a_TellDst) then SendMessage( a_DstPlayerName, a_SrcPlayer:GetName().." teleported to you" ) end end end if not cRoot:Get():FindAndDoWithPlayer( a_DstPlayerName, teleport ) then SendMessageFailure( a_SrcPlayer, "Player " .. a_DstPlayerName .. " not found" ) end end function getSpawnProtectRadius(WorldName) return WorldsSpawnProtect[WorldName] end function GetWorldDifficulty(a_World) local Difficulty = WorldsWorldDifficulty[a_World:GetName()] if (Difficulty == nil) then Difficulty = 1 end return Clamp(Difficulty, 0, 3) end function SetWorldDifficulty(a_World, a_Difficulty) local Difficulty = Clamp(a_Difficulty, 0, 3) WorldsWorldDifficulty[a_World:GetName()] = Difficulty -- Update world.ini local WorldIni = cIniFile() WorldIni:ReadFile(a_World:GetIniFileName()) WorldIni:SetValue("Difficulty", "WorldDifficulty", Difficulty) WorldIni:WriteFile(a_World:GetIniFileName()) end function LoadWorldSettings(a_World) local WorldIni = cIniFile() WorldIni:ReadFile(a_World:GetIniFileName()) WorldsSpawnProtect[a_World:GetName()] = WorldIni:GetValueSetI("SpawnProtect", "ProtectRadius", 10) WorldsWorldLimit[a_World:GetName()] = WorldIni:GetValueSetI("WorldLimit", "LimitRadius", 0) WorldsWorldDifficulty[a_World:GetName()] = WorldIni:GetValueSetI("Difficulty", "WorldDifficulty", 1) WorldIni:WriteFile(a_World:GetIniFileName()) end --- Returns the cWorld object represented by the given WorldName, -- if no world of the given name is found, returns nil and informs the Player, if given, otherwise logs to console. -- If no WorldName was given, returns the default world if called without a Player, -- or the current world that the player is in if called with a Player. -- -- @param WorldName String containing the name of the world to find -- @param Player cPlayer object representing the player calling the command -- -- @return cWorld object representing the requested world, or nil if not found -- -- Called from: time.lua, weather.lua, -- function GetWorld( WorldName, Player ) if not WorldName then return Player and Player:GetWorld() or cRoot:Get():GetDefaultWorld() else local World = cRoot:Get():GetWorld(WorldName) if not World then local Message = "There is no world \"" .. WorldName .. "\"" if Player then SendMessage( Player, Message ) else LOG( Message ) end end return World end end
135yshr/Holocraft-server
world/Plugins/Core/functions.lua
Lua
mit
5,438
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 <[email protected]> * * 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
--- layout: post title: "Using the right terms: Method?" date: 2015-08-05 12:00:00 comments: true tags: [components, programming, components programming, componentsprogramming, stepanov, knuth, stroustrup, generic, genericprogramming, generic programming, genericity, concepts, math, mathematics, elements, eop, contracts, performance, c++, cpp, c, java, dotnet, c#, csharp, python, ruby, javascript, haskell, dlang, rust, golang, eiffel, templates, metaprogramming, book, fmgp] --- (REVISIONISMO) En esta serie de articulos mi intension es revisar por qué algunos programadores usamos cierta terminologia, ciertas palabras, algunas de las cuales, considero inadecuadas. En este caso quiero hablar sobre la palabra "method". Algunos colegas mios, más que nada colegas con background en Java o .Net suelen usar esta palabra, como por ejemplo: "Escribí un método que tome una fecha y retorne un string con el nombre del día". Yo me pregunto: ¿Por qué decimos "metodo" y no utilizamos otra palabra como "procedimiento", "función", etc? Cuando yo empecé a programar, casi nadie usaba la palabra "metodo" y de repente ahora es muy común. Pero, antes de continuar con mi conjetura, me gustaría repasar (muy burdamente) sobre teoría de objetos. ¿Qué es un método? Cualquier programador Java o C# (y otros lenguajes) le diría que un objeto tiene estado y comportamiento. El estado se almacena en Fields y el comportamiento shown via Métodos. O sea, un método es un procedimiento, funcion, routine, subroutine, pero que está incluido dentro de una clase en particular. >>> O sea, un método es una serie de instrucciones, a las que se les pone un nombre. Java y C# copian gran parte de su sintáxis y terminologia (glosario) de C++ (no así la semántica). Pero en C++ no se usa el termino Method, sino que al comportamiento de los objetos se los codifica usando Member Functions. (Al estado de los objetos se lo almacena en Data Members) C++ es un lenguaje que soporta el paradigma de objetos, pero desde el nacimiento de C++, este no está atado a un solo paradigma. C++ hereda de C el paradigma de programación estructurada, o sea, C++ es un lenguaje multi-paradigma, por lo tanto, permite la creacion de funciones, tanto dentro de una clase como fuera de ella. A las funciones que son creadas fuera de una clase se las suele llamar Non-Member Functions o Free Functions. Más allá de esto, el termino "Method" se ha popularizado de tal forma que si dicen "metodo" cualquier programador C++ sabe de que estás hablando. ¿Por qué Java y C# no adoptaron la misma terminologia que C++? (En lo que respecta a comportamiento de objetos) Bueno, C# borrowed a lot from Java, así que la pregunta sería, ¿Por qué Java no adoptaró la misma terminologia que C++? ( Al margen: mas alla de que C# en sus comienzos era casi identico a Java, en ciertas cuestiones toma un camino separado a Java y quizás más cercano a C++, por ejemplo: - No todos los métodos son virtuales - In C# a parent and child classes are named Base and Derived clases, respectively (like in C++, see D&E of C++), but in Java are called Super and Sub classes. ) Eso es dificil de saber, habría que charlar con los creadores del lenguaje para saber el porqué de la nomenclatura. Para saber que es un método, primero me gustaría explorar distintas fuentes para saber cual es el origen de esa palabra en el ámbito informático. ............................................................... Procedure Function Routine Subroutine Feature Method FORTRAN FORTRAN was the first high-level programming language and the first high-quality optimizing compiler. PROGRAM, FUNCTION, SUBROUTINE Statement function External function Subroutine "Method" Fortran STANDARs Committee http://www.nag.co.uk/sc22wg5/ Fortran 66 ftp://ftp.nag.co.uk/sc22wg5/ARCHIVE/Fortran66.pdf Fortran 77 ftp://ftp.nag.co.uk/sc22wg5/ARCHIVE/Fortran77.html Fortran 90 ftp://ftp.nag.co.uk/sc22wg5/N001-N1100/N692.pdf Fortran 95 ftp://ftp.nag.co.uk/sc22wg5/N1151-N1200/N1191.pdf Fortran 2003 ftp://ftp.nag.co.uk/sc22wg5/N1601-N1650/N1601.pdf Fortran 2008 (working) http://j3-fortran.org/doc/year/10/10-007r1.pdf http://www.softwarepreservation.org/projects/FORTRAN/ Algol ALGOL (short for ALGOrithmic Language)[1] is a family of imperative computer programming languages, originally developed in the mid-1950s, which greatly influenced many other languages and was the standard method for algorithm description used by the ACM in textbooks and academic sources for more than thirty years.[2] In the sense that most modern languages are "algol-like",[3] it was arguably the most successful of the four high-level programming languages with which it was roughly contemporary http://www.softwarepreservation.org/projects/ALGOL/ Simula Procedure (ALGOL) function procedure (ALGOL) Parece que en SIMULA I un objeto (de OOP) es llamado Process slp-complete.pdf - Chapter 2 - page 10 "It has its own local data and its own behaviour pattern. A system may contain several processes with a similar data structure and the same behaviour pattern. Such processes are said to belong to the same class, called an activity."" SIMULA 67 1. 3. 3 Classes A central new concept in SIMULA 67 is the "object". An object is a self-contained program (block instance) having its own local data and actions defined by a "class declaration". The class declaration defines a program (data and action) pattern, and objects conforming to that pattern are said to "belong to the same class". If no actions are specified in the class declaration, a class of pure data structures is defined. Smalltalk NCITS J20 DRAFT December, 1997 of ANSI Smalltalk Standard revision 1.9 ANSI Smalltalk Standard v1.9 199712 NCITS X3J20 draft (PDF) A Smalltalk program is a means for describing a dynamic computational process. This section defines the entities that exist in the computational environment of Smalltalk programs. A variable is a computational entity that stores a single reference (the value of the variable) to an object. A message is a request to perform a designated computation. An object is a computational entity that is capable of responding to a well defined set of messages. An object may also encapsulate some (possibly mutable) state. An object responds to a message by executing a method. Each method is identified by an associated method selector. A behavior is the set of methods used by an object to respond to messages. A method consists of a sequence of expressions. Program execution proceeds by sequentially evaluating the expressions in one of more methods. There are three types of expressions: assignments, message sends, and returns. CLOS C C++ n3936.pdf 9.3 Member functions [class.mfct] 1 Functions declared in the definition of a class, excluding those declared with a friend specifier (11.3), are called member functions of that class. A member function may be declared static in which case it is a static member function of its class (9.4); otherwise it is a non-static member function of its class (9.3.1, 9.3.2). Eiffel 1. ECMA Standard 2. BM - Object Oriented Software Construction vol.2 Eiffel - Object-Oriented Software Construction (2nd Ed) - Bertrand Meyer Representing a point in cartesian coordinates Feature: Computation or Memory This example shows the need for two kinds of feature: • Some features will be represented by space, that is to say by associating a certain piece of information with every instance of the class. They will be called attributes. For points, x and y are attributes in cartesian representation; rho and theta are attributes in polar representation. • Some features will be represented by time, that is to say by defining a certain computation (an algorithm) applicable to all instances of the class. They will be called routines. For points, rho and theta are routines in cartesian representation; x and y are routines in polar representation. A further distinction affects routines (the second of these categories). Some routines will return a result; they are called functions. Here x and y in polar representation, as well as rho and theta in cartesian representation, are functions since they return a result, of type REAL. Routines which do not return a result correspond to the commands of an ADT specification and are called procedures. For example the class POINT will include procedures translate, rotate and scale. Java Java Language Specification 8.4 Method Declarations A method declares executable code that can be invoked, passing a fixed number of values as arguments. 227 8.4 Method Declarations CLASSES 228 MethodDeclaration: {MethodModifier} MethodHeader MethodBody MethodHeader: Result MethodDeclarator [Throws] TypeParameters {Annotation} Result MethodDeclarator [Throws] MethodDeclarator: Identifier ( [FormalParameterList] ) [Dims] The following production from §4.3 is shown here for convenience: Dims: {Annotation} [ ] {{Annotation} [ ]} The FormalParameterList is described in §8.4.1, the MethodModifier clause in §8.4.3, the TypeParameters clause in §8.4.4, the Result clause in §8.4.5, the Throws clause in §8.4.6, and the MethodBody in §8.4.7. The Identifier in a MethodDeclarator may be used in a name to refer to the method (§6.5.7.1, §15.12). It is a compile-time error for the body of a class to declare as members two methods with override-equivalent signatures (§8.4.2). The scope and shadowing of a method declaration is specified in §6.3 and §6.4. The declaration of a method that returns an array is allowed to place some or all of the bracket pairs that denote the array type after the formal parameter list. This syntax is supported for compatibility with early versions of the Java programming language. It is very strongly recommended that this syntax is not used in new code. Java Tutorials Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming. https://docs.oracle.com/javase/tutorial/java/concepts/object.html C# C# Specification C# ECMA Standard (ISO Standard) 8.7.3 Methods A method is a member that implements a computation or action that can be performed by an object or class. Methods have a (possibly empty) list of formal parameters, a return value (unless the method’s return-type is void), and are either static or non-static. Static methods are accessed through the class. Non-static methods, which are also called instance methods, are accessed through instances of the class. A generic method (§25.6) has a list of one or more type parameters. The example Python APPENDIX A - GLOSSARY method A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self). See function and nested scope. function A series of statements which returns some value to a caller. It can also be passed zero or more arguments which may be used in the execution of the body. See also parameter, method, and the Function definitions section. 6.1 Expression statements procedure (a function that returns no meaningful result; in Python, procedures return the value None). Knuth - The Art of Computer Programming - Concrete Mathematics Elements of Programming Dijstra ? Wirth ? RAE Britsh Mathematics "asymptotic methods" "repertoire method" general method Real Academia Espanola método. (Del lat. methŏdus, y este del gr. μέθοδος). 1. m. Modo de decir o hacer con orden. 2. m. Modo de obrar o proceder, hábito o costumbre que cada uno tiene y observa. 3. m. Obra que enseña los elementos de una ciencia o arte. 4. m. Fil. Procedimiento que se sigue en las ciencias para hallar la verdad y enseñarla. ............................................................... {% highlight cpp %} class employee { id: natural32 other: natural32 } class test { a: natural32 := 0x88FF7799 employees: array<employee> := { {0xA1B2C3D4, 0x11223344}, {0x92817348, 0x96161728}, {0x61592308, 0xa8857472 } } b: natural32 := 0x12345678 } //program entry-point main() { tc := test{} // analyze memory here! } {% endhighlight %} The program consists of a main function (entry-point) in which is created an object of type "test". The test class has three data members (or Fields, in order to use Java/C# jargons): - a: it is 32-bits natural number (like C/C++'s uint32_t). It is set to 88FF7799 (base16) - employees: it is a sequence of elements of type "employee". The employees sequence is filled with three elements. - b: it is 32-bits natural number. It is set to 12345678 (base16) The employee class has two data members: - id: it is 32-bits natural number - other: it is 32-bits natural number Note: "array" is a data structure that stores elements contiguosly in memory. The size of the sequence is dynamic, it is resizable. Equivalents: C++ std::vector, .Net List<T>, Java ArrayList<T> For example it is not necessary runtime polymorphism neither runtime type introspection (aka Reflection). For simplicity all the data members are public. Now, let's code in real programming languages: C++ code {% highlight cpp %} #include <vector> using namespace std; struct employee { uint32_t id; uint32_t other; }; struct test { uint32_t a {0x88FF7799}; vector<employee> employees { {0xA1B2C3D4, 0x11223344}, {0x92817348, 0x96161728}, {0x61592308, 0xa8857472}}; uint32_t b {0x12345678}; }; int main(int argc, char const* argv[]) { test t; // analyze memory here! return 0; } {% endhighlight %} Java code: {% highlight cpp %} import java.util.ArrayList; class Employee { public int id; public int other; public Employee(int id, int other) { this.id = id; this.other = other; } } class Test { public int a = 0x88FF7799; public ArrayList<Employee> employees = new ArrayList<Employee>(); public int b = 0x12345678; public Test() { employees.add(new Employee(0xA1B2C3D4, 0x11223344)); employees.add(new Employee(0x92817348, 0x96161728)); employees.add(new Employee(0x61592308, 0xa8857472)); } } public class MainClass { public static void main(String args[]) { Test t = new Test(); // analyze memory here! } } {% endhighlight %} C# code {% highlight cpp %} using System; using System.Collections.Generic; internal class Employee { public uint Id; public uint Other; public Employee(uint id, uint other) { Id = id; Other = other; } } internal class Test { public uint A = 0x88FF7799; public List<Employee> Employees = new List<Employee> { new Employee(0xA1B2C3D4, 0x11223344), new Employee(0x92817348, 0x96161728), new Employee(0x61592308, 0xa8857472) }; public uint B = 0x12345678; } class Program { static void Main(string[] args) { var t = new Test(); // analyze memory here! } } {% endhighlight %} I tried to write idiomatic code (as possible) in each of the languages. I am not trying to be OO-purist. I just tried to write the simplest code to later analyze the memory more easily. Disclaimer: .... References: .Net BCL System.Array class specification: https://msdn.microsoft.com/en-us/library/system.array%28v=vs.110%29.aspx .Net BCL System.Array class source code: http://referencesource.microsoft.com/#mscorlib/system/array.cs,1f52f2a267c6dbe7 .Net BCL System.Collections.Generic.List<T> class specification: https://msdn.microsoft.com/en-us/library/6sh2ey19%28v=vs.110%29.aspx .Net BCL System.Collections.Generic.List<T> class source code: http://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,cf7f4095e4de7646 Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects https://msdn.microsoft.com/en-us/magazine/cc163791.aspx Java ARTICLES https://www.yourkit.com/docs/kb/sizes.jsp https://wikis.oracle.com/display/HotSpotInternals/CompressedOops http://www.docjar.com/docs/api/sun/misc/Unsafe.html http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/ http://java-performance.info/memory-introspection-using-sun-misc-unsafe-and-reflection/
fpelliccioni/fpelliccioni.github.io
_posts_temp/2015-08-05-using-the-right-terms-method.md
Markdown
mit
17,362
/*"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
<!DOCTYPE html> <html lang="en" ng-app="bookmarkApp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Bookmark</title> <link type="text/css" href="app/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link type="text/css" href="app/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet"> <link href="app/css/bootstrap-combined.min.css" rel="stylesheet"> <link type="text/css" href="app/css/theme.css" rel="stylesheet"> <link type="text/css" href="app/css/ng-table.css" rel="stylesheet"> <link type="text/css" href="app/images/icons/css/font-awesome.css" rel="stylesheet"> <link type="text/css" href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600' rel='stylesheet'> </head> <body > <!-- /navbar --> <div data-ng-view=""></div> <script src="app/scripts/jquery-1.9.1.min.js" type="text/javascript"></script> <script src="app/scripts/jquery-ui-1.10.1.custom.min.js" type="text/javascript"></script> <script src="app/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <script src="app/scripts/angular.min.js"></script> <script src="app/scripts/angular-route.js"></script> <script src="app/scripts/angular-resource.min.js"></script> <script src="app/scripts/angular-resource.min.js.map"></script> <script src="app/scripts/angular-cookies.min.js"></script> <script src="app/app.js"></script> <script src="app/scripts/ng-table.js" type="text/javascript"></script> <script src="app/bootstrap/js/ui-bootstrap-tpls-0.11.2.js"></script> <script src="app/directives/commonDirective.js"></script> <script src="app/controllers/resourceController.js"></script> <script src="app/controllers/resourceGroupController.js"></script> <script src="app/services/resourcegroupService.js"></script> <script src="app/services/resourceService.js"></script> <script src="app/services/loginService.js"></script> <script src="app/controllers/userController.js"></script> <script src="app/services/userservice.js"></script> <script src="app/services/servicehelper.js"></script> </body>
AccelNA/ng-aws-dynamo
index.html
HTML
mit
2,164
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
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "WFBTLEServiceProcessor.h" @class NSData, WFNordicDFUControlPointCh, WFNordicDFUPacketCh; @interface WFBTLENordicDFUService : WFBTLEServiceProcessor { id <WFNordicDFUDelegate> delegate; WFNordicDFUControlPointCh *dfuControlPointCh; WFNordicDFUPacketCh *dfuPacketCh; BOOL bDFUInProgress; BOOL bStartTransferOnACK; BOOL bFinishOnACK; BOOL bWaitingForReceiveImageACK; unsigned long ulImageSize; unsigned long ulBytesSent; NSData *firmwareData; double startTime; unsigned short usCRC; unsigned short usProductId; unsigned int packetIntervalTime; unsigned char ucMaxRetries; unsigned char ucRetryCount; BOOL bTransferThreadRunning; BOOL bBlockTransferThread; BOOL bTransferCheckPassed; BOOL bAbortImageTransfer; } @property(retain, nonatomic) id <WFNordicDFUDelegate> delegate; // @synthesize delegate; - (void)setMaxRetries:(unsigned char)arg1; - (void)setPacketIntervalTime:(unsigned int)arg1; - (BOOL)sendHardReset; - (BOOL)sendExitDFU; - (BOOL)sendFirmware:(id)arg1; - (void)sendFirmwareImage_TM; - (void)sendFirmwareImage; - (void)sendDFUInitParams; - (BOOL)sendStartDFU; - (void)restartTransfer; - (void)delegateFinish:(unsigned char)arg1; - (void)delegateUpdateBytesSent:(unsigned long)arg1; - (void)delegateValidateFirmwareResponse:(unsigned char)arg1; - (void)delegateReceiveFirmwareImageResponse:(unsigned char)arg1; - (void)delegateInitDFUParamsResponse:(unsigned char)arg1; - (void)delegateStartDFUResponse:(unsigned char)arg1 imageSize:(unsigned long)arg2; - (void)reset; - (id)getData; - (BOOL)startUpdatingForService:(id)arg1 onPeripheral:(id)arg2; - (void)peripheral:(id)arg1 didWriteValueForCharacteristic:(id)arg2 error:(id)arg3; - (void)peripheral:(id)arg1 didUpdateValueForCharacteristic:(id)arg2 error:(id)arg3; - (void)peripheral:(id)arg1 didUpdateNotificationStateForCharacteristic:(id)arg2 error:(id)arg3; - (void)dealloc; - (id)init; @end
JChanceHud/GearIndicator
Fitness/WFBTLENordicDFUService.h
C
mit
2,091
/** * @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
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <pthread.h> #include <errno.h> #include "semaphore.h" typedef struct lock { Semaphore *sem; } Lock; Lock *make_lock () { Lock *lock = (Lock *) malloc (sizeof(Lock)); lock->sem = make_semaphore(1); return lock; } void lock_acquire (Lock *lock) { semaphore_wait(lock->sem); } void lock_release (Lock *lock) { semaphore_signal(lock->sem); }
AllenDowney/ExercisesInC
examples/lock/semlock.c
C
mit
445
<section id="main"> <a href="./#/mocks"><- Back to mocks list</a> <nav id="secondary" class="main-nav"> <div class="mock-picture"> <div class="avatar"> <img ng-show="mock" src="img/mocks/{{mock.Mock.mockId}}.png" /> <img ng-show="mock" src="img/flags/{{mock.Mock.nationality}}.png" /><br/> {{mock.mock.givenName}} {{mock.mock.familyName}} </div> </div> <div class="mock-status"> Country: {{mock.mock.nationality}} <br/> Team: {{mock.Constructors[0].name}}<br/> Birth: {{mock.mock.dateOfBirth}}<br/> <a href="{{mock.Mock.url}}" target="_blank">Biography</a> </div> </nav> <div class="main-content"> <table class="result-table"> <thead> <tr><th colspan="5">Formula 1 2013 Results</th></tr> </thead> <tbody> <tr> <td>Round</td> <td>Grand Prix</td> <td>Team</td> <td>Grid</td> <td>Race</td> </tr> <tr ng-repeat="race in races"> <td>{{race.round}}</td> <td><img src="img/flags/{{race.Circuit.Location.country}}.png" />{{race.raceName}}</td> <td>{{race.Results[0].Constructor.name}}</td> <td>{{race.Results[0].grid}}</td> <td>{{race.Results[0].position}}</td> </tr> </tbody> </table> </div> </section>
yonred/MockApp
app/partials/result.html
HTML
mit
1,318
/*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
--- title: Workshop Title layout: workshop --- # Introduction to REDCap -------- --------- Please have a REDCap account if you want to follow along. - **REDCap**: [login here](https://edc.camhx.ca/redcap/) --------- ***Demographics Form*** - Record ID - Date of assessment - Initials - DOB - Handedness - Sex - Race - White. - Black or African American. - American Indian or Alaska Native. - Asian. - Native Hawaiian or Other Pacific Islander. - Other, not specified above. - Mixed, more than 1 Race. - Unknown or Not Reported (participants always have the right to not identify with any category) - Ethnicity - Not Hispanic or Latino - Hispanic, of Spanish Origin or Latino (e.g. Cuban, Mexican, Puerto Rican, South American) - Unknown or Not Reported (participants always have the right to not identify with any category) - Comments --------- ***Example instrument for us to program*** 1. On most days, I feel happy 2. My temperament is similar to that of my peers 3. I usually find it hard to get out of bed 4. I often cry for no reason 5. Overall, I lead a good life --------- ***Example instrument for us to upload*** [SANS.xlsx](/compucool/workshops/data/SANS.xlsx) --------- ***Example data for us to upload*** [SANS_data.csv](/compucool/workshops/data/SANS_data.csv)
CAMH-SCWG/compucool-oct-2016
workshops/redcap.md
Markdown
mit
1,411
<html> <head> <title>im a title</title> <META http-equiv='x-ua-compatible' content="IE=edge,chrome=1" /> <script> junk </script> </head> <body>im some body text</body> </html>
jinutm/silvfinal
vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.6.9.171/test/rum/x_ua_meta_tag_with_spaces.source.html
HTML
mit
209
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>React Webpack Boilerplate</title> </head> <body> <div id="root"></div> <script src="/bundle.js"></script> </body> </html>
Lando-L/react-webpack-boilerplate
dist/index.html
HTML
mit
207
<?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
#!/usr/bin/env bash PIDFILE="$HOME/.brianbondy_nodejs.pid" if [ -e "${PIDFILE}" ] && (ps -u $USER -f | grep "[ ]$(cat ${PIDFILE})[ ]"); then echo "Already running." exit 99 fi PATH=/home/tweetpig/webapps/brianbondy_node/bin:$PATH LD_LIBRARY_PATH=/home/tweetpig/lib/libgif NODE_ENV=production PORT=32757 /home/tweetpig/webapps/brianbondy_node/bin/node --harmony --max-old-space-size=200 /home/tweetpig/webapps/brianbondy_node/dist/server.js --brianbondy_node > $HOME/.brianbondy_nodejs.log & echo $! > "${PIDFILE}" chmod 644 "${PIDFILE}"
bbondy/brianbondy.node
webfaction/watchdog.sh
Shell
mit
545
/* * 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
# Strict Mode To enable strict mode, simply pass in `strict: true` when creating a Vuex store: ```js const store = createStore({ // ... strict: true }) ``` In strict mode, whenever Vuex state is mutated outside of mutation handlers, an error will be thrown. This ensures that all state mutations can be explicitly tracked by debugging tools. ## Development vs. Production **Do not enable strict mode when deploying for production!** Strict mode runs a synchronous deep watcher on the state tree for detecting inappropriate mutations, and it can be quite expensive when you make large amount of mutations to the state. Make sure to turn it off in production to avoid the performance cost. Similar to plugins, we can let the build tools handle that: ```js const store = createStore({ // ... strict: process.env.NODE_ENV !== 'production' }) ```
vuejs/vuex
docs/guide/strict.md
Markdown
mit
857
/** * 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
/* * Template Name: devAid - Responsive Website Template for developers * Version: 1.1 * Author: Xiaoying Riley * Twitter: @3rdwave_themes * License: Creative Commons Attribution 3.0 License * Website: http://themes.3rdwavemedia.com/ */ /* style-4.css */ /* ======= Base ======= */ body { font-family: 'Lato', arial, sans-serif; color: #444; font-size: 16px; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } h1, h2, h3, h4, h5, h6 { font-family: 'Montserrat', sans-serif; font-weight: 700; color: #50c8c9; } a { color: #50c8c9; -webkit-transition: all 0.4s ease-in-out; -moz-transition: all 0.4s ease-in-out; -ms-transition: all 0.4s ease-in-out; -o-transition: all 0.4s ease-in-out; } a:hover { text-decoration: underline; color: #36afb0; } .btn, a.btn { -webkit-transition: all 0.4s ease-in-out; -moz-transition: all 0.4s ease-in-out; -ms-transition: all 0.4s ease-in-out; -o-transition: all 0.4s ease-in-out; font-family: 'Montserrat', arial, sans-serif; padding: 8px 16px; font-weight: bold; } .btn .fa, a.btn .fa { margin-right: 5px; } .btn:focus, a.btn:focus { color: #fff; } a.btn-cta-primary, .btn-cta-primary { background: #1e6162; border: 1px solid #1e6162; color: #fff; font-weight: 600; text-transform: uppercase; } a.btn-cta-primary:hover, .btn-cta-primary:hover { background: #184e4e; border: 1px solid #184e4e; color: #fff; } a.btn-cta-secondary, .btn-cta-secondary { background: #ffbe57; border: 1px solid #ffbe57; color: #fff; font-weight: 600; text-transform: uppercase; } a.btn-cta-secondary:hover, .btn-cta-secondary:hover { background: #ffb43e; border: 1px solid #ffb43e; color: #fff; } .text-highlight { color: #1e6162; } .offset-header { padding-top: 90px; } pre code { font-size: 16px; } /* ======= Header ======= */ .header { padding: 10px 0; background: #50c8c9; color: #fff; position: fixed; width: 100%; } .header.navbar-fixed-top { background: #fff; z-index: 9999; -webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.4); -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.4); box-shadow: 0 0 4px rgba(0, 0, 0, 0.4); } .header.navbar-fixed-top .logo a { color: #50c8c9; } .header.navbar-fixed-top .main-nav .nav .nav-item a { color: #666; } .header .logo { margin: 0; font-size: 26px; padding-top: 10px; } .header .logo a { color: #fff; } .header .logo a:hover { text-decoration: none; } .header .main-nav button { background: #1e6162; color: #fff !important; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; } .header .main-nav button:focus { outline: none; } .header .main-nav button .icon-bar { background-color: #fff; } .header .main-nav .navbar-collapse { padding: 0; } .header .main-nav .nav .nav-item { font-weight: normal; margin-right: 30px; font-family: 'Montserrat', sans-serif; } .header .main-nav .nav .nav-item.active a { color: #50c8c9; background: none; } .header .main-nav .nav .nav-item a { color: #2a8889; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none; font-size: 14px; padding: 15px 10px; } .header .main-nav .nav .nav-item a:hover { color: #1e6162; background: none; } .header .main-nav .nav .nav-item a:focus { outline: none; background: none; } .header .main-nav .nav .nav-item a:active { outline: none; background: none; } .header .main-nav .nav .nav-item.active { color: #50c8c9; } .header .main-nav .nav .nav-item.last { margin-right: 0; } /* ======= Promo Section ======= */ .promo { background: #50c8c9; color: #fff; padding-top: 150px; } .promo .title { font-size: 98px; color: #1e6162; margin-top: 0; } .promo .title .highlight { color: #ffbe57; } .promo .intro { font-size: 28px; max-width: 680px; margin: 0 auto; margin-bottom: 30px; } .promo .btns .btn { margin-right: 15px; font-size: 18px; padding: 8px 30px; } .promo .meta { margin-top: 120px; margin-bottom: 30px; color: #2a8889; } .promo .meta li { margin-right: 15px; } .promo .meta a { color: #2a8889; } .promo .meta a:hover { color: #1e6162; } .promo .social-media { background: #309b9c; padding: 10px 0; margin: 0 auto; } .promo .social-media li { margin-top: 15px; } .promo .social-media li.facebook-like { margin-top: 0; position: relative; top: -5px; } /* ======= Page Section ======= */ .about { padding: 80px 0; background: #f5f5f5; } .about .title { color: #1e6162; margin-top: 0; margin-bottom: 60px; } .about .intro { max-width: 800px; margin: 0 auto; margin-bottom: 60px; } .about .item { position: relative; margin-bottom: 30px; } .about .item .icon-holder { position: absolute; left: 30px; top: 0; } .about .item .icon-holder .fa { font-size: 24px; color: #1e6162; } .about .item .content { padding-left: 60px; } .about .item .content .sub-title { margin-top: 0; color: #1e6162; font-size: 18px; } /* ======= Features Section ======= */ .features { padding: 80px 0; background: #50c8c9; color: #fff; } .features .title { color: #1e6162; margin-top: 0; margin-bottom: 30px; } .features a { color: #1e6162; } .features a:hover { color: #123b3b; } .features .feature-list li { margin-bottom: 10px; color: #1e6162; } .features .feature-list li .fa { margin-right: 5px; color: #fff; } /* ======= Docs Section ======= */ .docs { padding: 80px 0; background: #f5f5f5; } .docs .title { color: #1e6162; margin-top: 0; margin-bottom: 30px; } .docs .docs-inner { max-width: 800px; background: #fff; padding: 30px; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; margin: 0 auto; } .docs .block { margin-bottom: 60px; } .docs .code-block { margin: 30px inherit; } .docs .code-block pre[class*="language-"] { -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; } /* ======= License Section ======= */ .license { padding: 80px 0; background: #f5f5f5; } .license .title { margin-top: 0; margin-bottom: 60px; color: #1e6162; } .license .license-inner { max-width: 800px; background: #fff; padding: 30px; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; margin: 0 auto; } .license .info { max-width: 760px; margin: 0 auto; } .license .cta-container { max-width: 540px; margin: 0 auto; margin-top: 60px; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; } .license .cta-container .speech-bubble { background: #ecf9f9; color: #1e6162; padding: 30px; margin-bottom: 30px; position: relative; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; } .license .cta-container .speech-bubble:after { position: absolute; left: 50%; bottom: -10px; margin-left: -10px; content: ""; display: inline-block; width: 0; height: 0; border-left: 10px solid transparent; border-right: 10px solid transparent; border-top: 10px solid #ecf9f9; } .license .cta-container .icon-holder { margin-bottom: 15px; } .license .cta-container .icon-holder .fa { font-size: 56px; } .license .cta-container .intro { margin-bottom: 30px; } /* ======= Contact Section ======= */ .contact { padding: 80px 0; background: #50c8c9; color: #fff; } .contact .contact-inner { max-width: 760px; margin: 0 auto; } .contact .title { color: #1e6162; margin-top: 0; margin-bottom: 30px; } .contact .intro { margin-bottom: 60px; } .contact a { color: #1e6162; } .contact a:hover { color: #123b3b; } .contact .author-message { position: relative; margin-bottom: 60px; } .contact .author-message .profile { position: absolute; left: 30px; top: 15px; width: 100px; height: 100px; } .contact .author-message .profile img { -webkit-border-radius: 50%; -moz-border-radius: 50%; -ms-border-radius: 50%; -o-border-radius: 50%; border-radius: 50%; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; } .contact .author-message .speech-bubble { margin-left: 155px; background: #44c4c5; color: #1e6162; padding: 30px; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; position: relative; } .contact .author-message .speech-bubble .sub-title { color: #1e6162; font-size: 16px; margin-top: 0; margin-bottom: 30px; } .contact .author-message .speech-bubble a { color: #fff; } .contact .author-message .speech-bubble:after { position: absolute; left: -10px; top: 60px; content: ""; display: inline-block; width: 0; height: 0; border-top: 10px solid transparent; border-bottom: 10px solid transparent; border-right: 10px solid #44c4c5; } .contact .author-message .speech-bubble .source { margin-top: 30px; } .contact .author-message .speech-bubble .source a { color: #1e6162; } .contact .author-message .speech-bubble .source .title { color: #309b9c; } .contact .info .sub-title { color: #36afb0; margin-bottom: 30px; margin-top: 0; } .contact .social-icons { list-style: none; padding: 10px 0; margin-bottom: 0; display: inline-block; margin: 0 auto; } .contact .social-icons li { float: left; } .contact .social-icons li.last { margin-right: 0; } .contact .social-icons a { display: inline-block; background: #309b9c; width: 48px; height: 48px; text-align: center; padding-top: 12px; -webkit-border-radius: 50%; -moz-border-radius: 50%; -ms-border-radius: 50%; -o-border-radius: 50%; border-radius: 50%; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; margin-right: 8px; float: left; } .contact .social-icons a:hover { background: #ffaa24; } .contact .social-icons a .fa { color: #fff; } .contact .social-icons a .fa:before { font-size: 26px; text-align: center; padding: 0; } /* ======= Footer ======= */ .footer { padding: 15px 0; background: #123b3b; color: #fff; } .footer .copyright { -webkit-opacity: 0.8; -moz-opacity: 0.8; opacity: 0.8; } .footer .fa-heart { color: #fb866a; } /* Extra small devices (phones, less than 768px) */ @media (max-width: 767px) { .header .main-nav button { margin-right: 0; } .header .main-nav .navbar-collapse { padding-left: 15px; padding-right: 15px; } .promo .btns .btn { margin-right: 0; clear: both; display: block; margin-bottom: 30px; } .promo .title { font-size: 66px; } .promo .meta { margin-top: 60px; } .promo .meta li { float: none; display: block; margin-bottom: 5px; } .contact .author-message { text-align: center; } .contact .author-message .profile { position: static; margin: 0 auto; margin-bottom: 30px; } .contact .author-message .speech-bubble { margin-left: 0; } .contact .author-message .speech-bubble:after { display: none; } .contact .social-icons a { width: 36px; height: 36px; padding-top: 7px; margin-right: 2px; } .contact .social-icons a .fa:before { font-size: 18px; } } /* Small devices (tablets, 768px and up) */ /* Medium devices (desktops, 992px and up) */ /* Large devices (large desktops, 1200px and up) */
argeweb/start
themes/default/css/styles-4.css
CSS
mit
12,370
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([email protected]_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
<!doctype html> <html> <head> <meta charset="utf-8" /> <meta content="IE=edge;chrome=1" http-equiv="X-UA-Compatible" /> <title>dognews</title> <meta content="width=device-width, initial-scale=1" name="viewport" /> <link rel="alternate" type="application/atom+xml" title="Atom Feed" href="/feed.xml" /><!--[if lt IE 9]><script src="../../js/ie8.js" type="text/javascript"></script><![endif]--><link href="../../css/all.css" media="screen" rel="stylesheet" type="text/css" /><script type="text/javascript"> (function(d,e,j,h,f,c,b){d.GoogleAnalyticsObject=f;d[f]=d[f]||function(){(d[f].q=d[f].q||[]).push(arguments)},d[f].l=1*new Date();c=e.createElement(j),b=e.getElementsByTagName(j)[0];c.async=1;c.src=h;b.parentNode.insertBefore(c,b)})(window,document,"script","//www.google-analytics.com/analytics.js","ga");ga("create","UA-63279904-1", location.hostname);ga("send","pageview"); </script> <link href="/favicon.png" rel="icon" type="image/png" /> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button class="navbar-toggle collapsed" data-target=".navbar-ex1-collapse" data-toggle="collapse" type="button"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button><a class="navbar-brand" href="/">dognews</a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav"> <li> <a href="/menu1.html"> Über Uns </a> </li> <li> <a href="/menu2.html"> Newsletter! </a> </li> <li class="dropdown"> <a aria-expanded="false" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button">Categories <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li> <a href="/tags/businessidee.html">businessidee (38)</a> </li> <li> <a href="/tags/deutschland.html">deutschland (596)</a> </li> <li> <a href="/tags/erziehung.html">erziehung (35)</a> </li> <li> <a href="/tags/fotografie.html">fotografie (5)</a> </li> <li> <a href="/tags/freizeit.html">freizeit (83)</a> </li> <li> <a href="/tags/gesetz.html">gesetz (38)</a> </li> <li> <a href="/tags/gesundheit.html">gesundheit (116)</a> </li> <li> <a href="/tags/herdenhunde.html">herdenhunde (10)</a> </li> <li> <a href="/tags/hundesachkunde.html">hundesachkunde (13)</a> </li> <li> <a href="/tags/hundesport.html">hundesport (12)</a> </li> <li> <a href="/tags/kinder.html">kinder (9)</a> </li> <li> <a href="/tags/kurioses.html">kurioses (29)</a> </li> <li> <a href="/tags/oesterreich.html">oesterreich (63)</a> </li> <li> <a href="/tags/rassen.html">rassen (8)</a> </li> <li> <a href="/tags/ratgeber.html">ratgeber (161)</a> </li> <li> <a href="/tags/rettungshunde.html">rettungshunde (3)</a> </li> <li> <a href="/tags/schweiz.html">schweiz (99)</a> </li> <li> <a href="/tags/senioren.html">senioren (10)</a> </li> <li> <a href="/tags/stars.html">stars (11)</a> </li> <li> <a href="/tags/urlaub.html">urlaub (39)</a> </li> <li> <a href="/tags/veranstaltung.html">veranstaltung (1)</a> </li> <li> <a href="/tags/wandern.html">wandern (17)</a> </li> <li> <a href="/tags/wissen.html">wissen (200)</a> </li> </ul> </li> <li class="dropdown"> <a aria-expanded="false" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button">By Year <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li> <a href="/2017.html">2017 (8)</a> </li> <li> <a href="/2016.html">2016 (55)</a> </li> <li> <a href="/2015.html">2015 (458)</a> </li> <li> <a href="/2014.html">2014 (273)</a> </li> </ul> </li> <ul class="list-unstyled list-inline nav navbar-nav navbar-right"></ul> <li><a href="https://twitter.com/cbdognews"> <i class="fa fa-lg fa-inverse fa-twitter-square"></i></a> </li> </ul> </div> </div> </nav> <div class="container"> <div class="row"> <div class="col-lg-9 col-md-9"> <h1> Archive for Jan 9 2014 </h1> <ul> <h2> <a href="/2014/01/09/gelbes-tuch-fass-mich-nicht-an.html">Gelbes Tuch: 'Fass mich nicht an!'</a> </h2> <p> <small class="label label-default">ratgeber</small> <small class="label label-default">deutschland</small> </p> <hr /> <p> <span class="glyphicon glyphicon-time"></span> Posted on Jan 9 </p> <hr /> <div class="row"> <div class="article"> <p><dummy> Wenn Kristin Friedrich mit ihrem Schäferhund Wanko unterwegs ist, trägt er jetzt stolz ein gelbes Halstuch. “Es signalisiert, dass der Hund nicht angefasst und nicht bedrängt werden möchte”, erklärt die Beeskower Hundetrainerin und Tierbetreuerin...</dummy></p> </div> </div><a class="btn btn-primary" href="/2014/01/09/gelbes-tuch-fass-mich-nicht-an.html">Read More<span class="glyphicon glyphicon-chevron-right"></span></a> <hr /> <h2> <a href="/2014/01/09/ehemaliger-ubs-handler-gab-finanzkarriere-auf-fur-dies.html">Ehemaliger UBS-Händler gab Finanzkarriere auf – für dies</a> </h2> <p> <small class="label label-default">schweiz</small> <small class="label label-default">businessidee</small> </p> <hr /> <p> <span class="glyphicon glyphicon-time"></span> Posted on Jan 9 </p> <hr /> <div class="row"> <div class="article"> <p><dummy> Ex-UBS-Händler gab Finanzkarriere auf – für ein Hunde-Spa <a href="http://www.finews.ch/news/banken/17027-mitch-marrow-ubs-hunde-spa-wellness-spot-experience-stamford-hedge-funds">Link</a></p> </div> </div><a class="btn btn-primary" href="/2014/01/09/ehemaliger-ubs-handler-gab-finanzkarriere-auf-fur-dies.html">Read More<span class="glyphicon glyphicon-chevron-right"></span></a> <hr /> </ul> <hr /> <aside> <h3> Recent Articles </h3> <ol> <li> <a href="/2017/12/05/nun-ist-es-raus-hunde-sind-kluger-als-katzen.html">Nun ist es raus: Hunde sind klüger als Katzen</a> <span>Dec 5</span> </li> <li> <a href="/2017/07/27/die-macht-der-geruche.html">Die Macht der Gerüche</a> <span>Jul 27</span> </li> <li> <a href="/2017/06/21/vorsicht-giftig-diese-lebensmittel-sollten-hunde-nicht-fressen.html">Vorsicht giftig! Diese Lebensmittel sollten Hunde nicht fressen</a> <span>Jun 21</span> </li> <li> <a href="/2017/03/27/studie-schaferhunde-konnen-brustkrebs-diagnostizieren.html">Studie: Schäferhunde können Brustkrebs diagnostizieren</a> <span>Mar 27</span> </li> <li> <a href="/2017/03/27/atopische-dermatitis-was-tun-wenn-es-juckt-und-kratzt-allergien-belasten-das-woh.html">Atopische Dermatitis: Was tun, wenn es juckt und kratzt? / Allergien belasten das Wohlbefinden ...</a> <span>Mar 27</span> </li> <li> <a href="/2017/02/27/tiermedizin-epilepsie-gen-entdeckt.html">Tiermedizin - Epilepsie-Gen entdeckt</a> <span>Feb 27</span> </li> <li> <a href="/2017/01/17/auch-haustiere-frieren-so-kommt-bello-durch-den-winter.html">Auch Haustiere frieren | So kommt Bello durch den Winter</a> <span>Jan 17</span> </li> <li> <a href="/2017/01/17/hunde-sind-bei-minusgraden-schnell-unterkuhlt.html">Hunde sind bei Minusgraden schnell unterkühlt</a> <span>Jan 17</span> </li> <li> <a href="/2016/12/08/venedig-wo-die-gondeln-hunde-tragen.html">Venedig: Wo die Gondeln Hunde tragen</a> <span>Dec 8</span> </li> <li> <a href="/2016/11/01/hunde-heulten-halbe-stunde-vor-erdbeben.html">Hunde heulten halbe Stunde vor Erdbeben</a> <span>Nov 1</span> </li> </ol> </aside> <hr> <p class="text-center"> ©2018 <a href="/">dognews</a> - <a href="/footer1.html">Disclaimer</a><br /><span class="small">Powered by<a href="https://cloudburo.net/docs/products.html"> Cloudburo Curation Engine</a></span> </p> </hr> </div> <div class="col-lg-3 col-md-3"> <div class="well"> <h4> Categories </h4> <ul class="list-unstyled"> <li> <a href="/tags/businessidee.html">businessidee</a> (38) </li> <li> <a href="/tags/deutschland.html">deutschland</a> (596) </li> <li> <a href="/tags/erziehung.html">erziehung</a> (35) </li> <li> <a href="/tags/fotografie.html">fotografie</a> (5) </li> <li> <a href="/tags/freizeit.html">freizeit</a> (83) </li> <li> <a href="/tags/gesetz.html">gesetz</a> (38) </li> <li> <a href="/tags/gesundheit.html">gesundheit</a> (116) </li> <li> <a href="/tags/herdenhunde.html">herdenhunde</a> (10) </li> <li> <a href="/tags/hundesachkunde.html">hundesachkunde</a> (13) </li> <li> <a href="/tags/hundesport.html">hundesport</a> (12) </li> <li> <a href="/tags/kinder.html">kinder</a> (9) </li> <li> <a href="/tags/kurioses.html">kurioses</a> (29) </li> <li> <a href="/tags/oesterreich.html">oesterreich</a> (63) </li> <li> <a href="/tags/rassen.html">rassen</a> (8) </li> <li> <a href="/tags/ratgeber.html">ratgeber</a> (161) </li> <li> <a href="/tags/rettungshunde.html">rettungshunde</a> (3) </li> <li> <a href="/tags/schweiz.html">schweiz</a> (99) </li> <li> <a href="/tags/senioren.html">senioren</a> (10) </li> <li> <a href="/tags/stars.html">stars</a> (11) </li> <li> <a href="/tags/urlaub.html">urlaub</a> (39) </li> <li> <a href="/tags/veranstaltung.html">veranstaltung</a> (1) </li> <li> <a href="/tags/wandern.html">wandern</a> (17) </li> <li> <a href="/tags/wissen.html">wissen</a> (200) </li> </ul> </div> <div class="well"> <h4> By year </h4> <ol> <li> <a href="/2017.html">2017</a> (8) </li> <li> <a href="/2016.html">2016</a> (55) </li> <li> <a href="/2015.html">2015</a> (458) </li> <li> <a href="/2014.html">2014</a> (273) </li> </ol> </div> </div> </div> </div> <script src="../../js/all.js" type="text/javascript"></script> </body> </html>
acloudburo/dognews
2014/01/09.html
HTML
mit
13,592
geoserver ========= PostGI server and probably more for the Cologne Open Data community. The goal is to provide a unified, dynamic geodata access point for some important geographical datasets. At some point, there might be a tile server or some other visualization layer as well. We'll see. ## Contents ### `postgis` Scripts to set up a PostGIS environment and import geo data into the system.
KoelnAPI/geoserver
README.md
Markdown
mit
401
// // EBBannerView+Categories.h // demo // // Created by [email protected] on 2017/10/20. // Copyright © 2017年 [email protected]. All rights reserved. // #import "EBBannerView.h" #define WEAK_SELF(weakSelf) __weak __typeof(&*self)weakSelf = self; #define ScreenWidth [UIScreen mainScreen].bounds.size.width #define ScreenHeight [UIScreen mainScreen].bounds.size.height @interface EBBannerView (EBCategory) +(UIImage*)defaultIcon; +(NSString*)defaultTitle; +(NSString*)defaultDate; +(NSTimeInterval)defaultAnimationTime; +(NSTimeInterval)defaultStayTime; +(UInt32)defaultSoundID; @end @interface NSTimer (EBCategory) + (NSTimer *)eb_scheduledTimerWithTimeInterval:(NSTimeInterval)interval block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats; @end @interface UIImage (EBBannerViewCategory) +(UIColor *)colorAtPoint:(CGPoint)point; @end
pikacode/EBBannerView
EBBannerView/Classes/EBBannerView+Categories.h
C
mit
857
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
#CodeQuiz _CodeQuiz is a game made with Kivy framework._ _He is a Quiz consists of four options, Ruby, Python, Javascript and C#._ _Where he will approach curiosities and specificities of each language._ ##Install and Run 1.Clone this repo ``` git clone [email protected]:GuiCarneiro/CodeQuiz.git ``` 2.Install Kivy on your computer, take a look at their site [Kivy](http://kivy.org) 3.Then run python main.py ##To Play 1. Use the distribution release 2. Double click over the CodeQuiz.exe OBS: _Before playing I recommend you to Update the Quiz_ _Use the menu update_ ##Collaborate 1. Fork it 2. Create your branch ``` git checkout -b name-your-feature ``` 3. Commit it ``` git commit -m 'the differece' ``` 4. Push it ``` git push origin name-your-feature ``` 5. Create a Pull Request ##License This projected is licensed under the terms of the MIT license.
GuiCarneiro/CodeQuiz
readme.md
Markdown
mit
887
/** * @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
# Fire Keeper ## Introduction Fire Keeper is a bot designed for the *Praise the Place* Dark Souls Discord server. Please do not use this bot in your server without adapation of the code, or else things will not work correctly.
Svetroid/Fire-Keeper
README.md
Markdown
mit
228
--- title: Prepare paperwork contexts: office365,microsoft365 source: Microsoft public sites translation: en tools: --- To kick off the employee onboarding checklist, you need to__ prepare the relevant paperwork and information__prior to the employee's first day\. Start by __recording__ the employee's __basic information__ in the__ form fields__below\. __Employee First Name__ __Employee Last Name__ __Date of Hire__ Date will be set here __Employee Contact Details__ __Employee Extra Information__ This part of the process is called__ transactional onboarding__ and focuses on completing all the necessary__forms and documents__ so your new employee can __legally start working__\. Some of the forms you need to prepare are: - 1 - W\-4 - 2 - I\-9 - 3 - Insurance forms - 4 - Direct deposit forms - 5 - The non\-disclosure agreement However, there are more forms you might need, __specific to your company__\. Good software to use is [Applicant PRO](http://www.applicantpro.com/) which operates like __CRM for onboarding __including all the necessary forms and documents and stores them in an__ online database__\. \(Source: [applicantpro\.com](http://www.applicantpro.com/products/onboarding/)\)
Hexatown/docs
generic/usecases/onboard/02-prepare-paperwork/index.md
Markdown
mit
1,214
# Doxx [![Build Status](https://travis-ci.org/FGRibreau/doxx.png)](https://travis-ci.org/FGRibreau/doxx) [![Gittip](http://badgr.co/gittip/fgribreau.png)](https://www.gittip.com/fgribreau/) [![Deps](https://david-dm.org/FGRibreau/doxx.png)](https://david-dm.org/FGRibreau/doxx) Use [dox](https://github.com/visionmedia/dox) to automatically generate beautiful html documentation. **Doxx is a total refactoring of [dox-foundation](https://github.com/punkave/dox-foundation/)**. Outputted HTML is by default based on templates and css from [Twitter Bootstrap](twitter.github.com/bootstrap/) and syntax highlighting is done by [Prism.js](http://prismjs.com/). Doxx was tested with **JavaScript** as well as generated JavaScript from **CoffeeScript**. ## Demo * [doxx/docs/compile.js](http://fgribreau.github.com/doxx/docs/compile.js.html) * [doxx/docs/dir.js](http://fgribreau.github.com/doxx/docs/dir.js.html) * [doxx/docs/parser.js](http://fgribreau.github.com/doxx/docs/parser.js.html) ## Usage JavaScript JavaDoc style ```javascript /** * Create an array of all the right files in the source dir * @param {String} source path * @param {Object} options * @param {Function} callback * @jsFiddle A jsFiddle embed URL * @return {Array} an array of string path */ function collectFiles(source, options, callback) { ... } ``` CoffeeScript JavaDoc style ```coffeescript ###* * Create an array of all the right files in the source dir * @param {String} source path * @param {Object} options * @param {Function} callback * @jsFiddle A jsFiddle embed URL * @return {Array} an array of string path ### collectFiles = (source, options, callback) -> ... ``` ## Installation Install the module with: `npm install doxx -g` ## CLI ``` $ doxx --help Usage: doxx [options] Options: -h, --help output usage information -V, --version output the version number -r, --raw output "raw" comments, leaving the markdown intact -d, --debug output parsed comments for debugging -t, --title <string> The title for the page produced -s, --source <source> The folder which should get parsed -i, --ignore <directories> Comma seperated list of directories to ignore. Default: test,public,static,views,templates -T, --target <target> The folder which will contain the results. Default: <process.cwd()>/docs -e, --target_extension <target_extension> Target files extension. Default: html --template <jade template> The jade template file to use Examples: # parse a whole folder $ doxx --source lib --target docs # parse a whole folder and use a specific template $ doxx --template ./view/myowntpl.jade --source lib --target docs ``` ## Contributing In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [grunt](https://github.com/cowboy/grunt). ## Release History * *0.0.1* - (dox-foundation) Initial release * *0.2.0* - (dox-foundation) Readable output * *0.3.0* - (dox-foundation) Support for folder parsing * *0.4.0* - (dox-foundation) Improved project navigation, major refactor of folder code * *0.5.0* - Initial release of doxx * *0.7.0* - Merge pull requests #16 #17 #19 #20 * *0.7.1* - Merge pull request #25 - Add target_extension option * *0.7.2* - Upgrade dox to ~0.4.4 * *0.7.4* - Merge pull requests #29 #30 ## Donate [Donate Bitcoins](https://coinbase.com/checkouts/fc3041b9d8116e0b98e7d243c4727a30) ## License Copyright (c) 2013 Francois-Guillaume Ribreau MIT License
RogerNoble/doxx
README.md
Markdown
mit
3,834
<div class="title"> <img class="icon" src="./res/img/interface.svg" /> <p class="interface">IStudentInfo.IYear</p> </div> <p> Describes school year. Contains year id and register id which are needed in order to use the the API. </p> <br /> <p class="section-title">Fields</p> <p>name: <span class="class">string</span> - school year display name, for ex. 2017/2018</p> <p>id: <span class="class">number</span> - year id</p> <p>registerId: <span class="class">number</span> - register id</p>
legion44/idziennik-api
docs/res/fragments/istudentinfo-iyear.html
HTML
mit
504
// 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
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>W28677_text</title> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <div style="margin-left: auto; margin-right: auto; width: 800px; overflow: hidden;"> <div style="float: left;"> <a href="page9.html">&laquo;</a> </div> <div style="float: right;"> </div> </div> <hr/> <div style="position: absolute; margin-left: 219px; margin-top: 1017px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 302px; margin-top: 1815px;"> <p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 220px; margin-top: 2090px;"> <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Choke manifold minimum 3” 5k </p> </div> <div style="position: absolute; margin-left: 577px; margin-top: 54px;"> <p class="styleSans58.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">11” SK psi BOP stack <br/>High Pressure <br/>. . rotating Fill-up line head <br/>- Drillingcmka _ — — <br/>Annular <br/> <br/>Preventer <br/> <br/>I Variable rams - Blind rams - <br/> m Kill line minimum 2" <br/>Drilling Spool <br/>' Spacer spool <br/>4‘ 5000 psi casing head </p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 55px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 165px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 330px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 495px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 660px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 825px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 1155px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 1320px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 1760px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 1925px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 990px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> <div style="position: absolute; margin-left: 2502px; margin-top: 1485px;"> <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> </body> </html>
datamade/elpc_bakken
ocr_extracted/W28677_text/page10.html
HTML
mit
4,191
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
# README SportzBall is a community driven application used to bring people together for intramural sports. From football to quidditch we want you to SPORTZ! To set up repository on your local machine clone and set up database (instructions below) Rails 5.0.1 Ruby ~> 2.3.0 * Configuration * Database creation and initialization `rails db:seed` * To run tests ask Stephen * Deployment instructions to come * API setup to come Contributers - FinGrayson - Jefferson-Faseler
FInGrayson/sportzball
README.md
Markdown
mit
479
#!/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
/* jqModal base Styling courtesy of; Brice Burgess <[email protected]> */ /* The Window's CSS z-index value is respected (takes priority). If none is supplied, the Window's z-index value will be set to 3000 by default (via jqModal.js). */ .jqmWrap { display: none; position: fixed; top: 20%; left: 50%; margin-left: -175px; width: 350px; background: #555; background: rgba(0,0,0,0.3); border-radius: 5px; } .jqmInner { background: #fff; color: #333; border-radius: 3px; margin: 6px; padding: 13px; font:100% Arial,sans-serif; } .jqmInner h1,h2,h3 { margin: 0; padding: 0; } .jqmInner h1 { font-size: 20px; font-weight: 700; } .jqmInner h2 { font-size: 12px; color: #888; font-weight: 400; padding: 6px 0 0; } .jqmInner h3 { font-size: 14px; font-weight: 700; margin-top: 10px; padding-top: 13px; border-top: 1px solid #ddd; } .jqmInner h3 a { color: #47c; text-decoration: none; } .jqmInner h3 a:hover { color: #47c; text-decoration: underline; } .jqmOverlay { background-color: #000; } /* Background iframe styling for IE6. Prevents ActiveX bleed-through (<select> form elements, etc.) */ * iframe.jqm {position:absolute;top:0;left:0;z-index:-1; width: expression(this.parentNode.offsetWidth+'px'); height: expression(this.parentNode.offsetHeight+'px'); } /* Fixed posistioning emulation for IE6 Star selector used to hide definition from browsers other than IE6 For valid CSS, use a conditional include instead */ * html .jqmWindow { position: absolute; top: expression((document.documentElement.scrollTop || document.body.scrollTop) + Math.round(17 * (document.documentElement.offsetHeight || document.body.clientHeight) / 100) + 'px'); }
6/browser-deprecator
assets/css/deprecator.css
CSS
mit
1,759
(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
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>simple-io: 27 s 🏆</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.9.0 / simple-io - 1.3.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> simple-io <small> 1.3.0 <span class="label label-success">27 s 🏆</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-01-04 03:17:13 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-04 03:17:13 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 1 Virtual package relying on perl coq 8.9.0 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Li-yao Xia &lt;[email protected]&gt;&quot; authors: &quot;Li-yao Xia&quot; homepage: &quot;https://github.com/Lysxia/coq-simple-io&quot; bug-reports: &quot;https://github.com/Lysxia/coq-simple-io/issues&quot; license: &quot;MIT&quot; dev-repo: &quot;git+https://github.com/Lysxia/coq-simple-io.git&quot; build: [make &quot;build&quot;] run-test: [make &quot;test&quot;] install: [make &quot;install&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.13~&quot;} &quot;coq-ext-lib&quot; &quot;ocamlbuild&quot; {with-test} ] tags: [ &quot;date:2020-03-08&quot; &quot;logpath:SimpleIO&quot; &quot;keyword:extraction&quot; &quot;keyword:effects&quot; ] synopsis: &quot;IO monad for Coq&quot; description: &quot;&quot;&quot; This library provides tools to implement IO programs directly in Coq, in a similar style to Haskell. Facilities for formal verification are not included. IO is defined as a parameter with a purely functional interface in Coq, to be extracted to OCaml. Some wrappers for the basic types and functions in the OCaml Pervasives module are provided. Users are free to define their own APIs on top of this IO type.&quot;&quot;&quot; url { src: &quot;https://github.com/Lysxia/coq-simple-io/archive/1.3.0.tar.gz&quot; checksum: &quot;sha512=bcf7746e7877c4672e509e8c80db28b93cffbb064e114cf4df4465d9be3d55274c84a7406b38eaf510deda8a2574e42f3b40c8f716841bd92557e7b59d86e7cb&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-simple-io.1.3.0 coq.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-simple-io.1.3.0 coq.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>1 m 13 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-simple-io.1.3.0 coq.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>27 s</dd> </dl> <h2>Installation size</h2> <p>Total: 478 K</p> <ul> <li>50 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unix.vo</code></li> <li>43 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Stdlib.vo</code></li> <li>28 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_UnsafeNat.vo</code></li> <li>28 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_RawChar.vo</code></li> <li>28 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_String.vo</code></li> <li>26 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Bytes.vo</code></li> <li>26 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unsafe.vo</code></li> <li>26 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Float.vo</code></li> <li>25 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Random.vo</code></li> <li>25 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Sys.vo</code></li> <li>25 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/SimpleIO.vo</code></li> <li>25 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_StdlibAxioms.vo</code></li> <li>16 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Stdlib.glob</code></li> <li>15 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unix.glob</code></li> <li>14 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Monad.vo</code></li> <li>13 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unix.v</code></li> <li>11 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Stdlib.v</code></li> <li>10 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Monad.glob</code></li> <li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_UnsafeNat.glob</code></li> <li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Monad.v</code></li> <li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Exceptions.vo</code></li> <li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_String.glob</code></li> <li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_RawChar.glob</code></li> <li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_String.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_RawChar.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Float.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unsafe.glob</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unsafe.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Bytes.glob</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Bytes.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Float.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_UnsafeNat.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Exceptions.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Random.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Exceptions.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Random.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Sys.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Sys.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_StdlibAxioms.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/SimpleIO.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/SimpleIO.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_StdlibAxioms.v</code></li> </ul> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq-simple-io.1.3.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.05.0-2.0.1/released/8.9.0/simple-io/1.3.0.html
HTML
mit
11,880
class Sprite(object): def __init__(self, xPos, yPos): self.x = xPos self.y = yPos self.th = 32 self.tw = 32 def checkCollision(self, otherSprite): if (self.x < otherSprite.x + otherSprite.tw and otherSprite.x < self.x + self.tw and self.y < otherSprite.y + otherSprite.th and otherSprite.y < self.y + self.th): return True else: return False class Actor(Sprite): def __init__(self, xPos, yPos): super(Actor, self).__init__(xPos, yPos) self.speed = 5 self.dy = 0 self.d = 3 self.dir = "right" # self.newdir = "right" self.state = "standing" self.walkR = [] self.walkL = [] def loadPics(self): self.standing = loadImage("gripe_stand.png") self.falling = loadImage("grfalling.png") for i in range(8): imageName = "gr" + str(i) + ".png" self.walkR.append(loadImage(imageName)) for i in range(8): imageName = "gl" + str(i) + ".png" self.walkL.append(loadImage(imageName)) def checkWall(self, wall): if wall.state == "hidden": if (self.x >= wall.x - self.d and (self.x + 32 <= wall.x + 32 + self.d)): return False def move(self): if self.dir == "right": if self.state == "walking": self.im = self.walkR[frameCount % 8] self.dx = self.speed elif self.state == "standing": self.im = self.standing self.dx = 0 elif self.state == "falling": self.im = self.falling self.dx = 0 self.dy = 5 elif self.dir == "left": if self.state == "walking": self.im = self.walkL[frameCount % 8] self.dx = -self.speed elif self.state == "standing": self.im = self.standing self.dx = 0 elif self.state == "falling": self.im = self.falling self.dx = 0 self.dy = 5 else: self.dx = 0 self.x += self.dx self.y += self.dy if self.x <= 0: self.x = 0 if self.x >= 640 - self.tw: self.x = 640 -self.tw def display(self): image(self.im, self.x, self.y) class Block(Sprite): def __init__(self, xPos, yPos): super(Block, self).__init__(xPos, yPos) self.state = "visible" def loadPics(self): self.im = loadImage("block.png") def display(self): if self.state == "visible": image(self.im, self.x, self.y)
kantel/processingpy
sketches/Apple_Invaders/sprites.py
Python
mit
2,805
<?php /** * This file is part of the Carrot framework. * * Copyright (c) 2011 Ricky Christie <[email protected]>. * * Licensed under the MIT License. * */ /** * Docs storage. * * Represents a documents storage and provides ways to access * the documents inside the storage. This class reads folders and * .html files inside a directory and creates a hierarchical docs * structure from it. * * @author Ricky Christie <[email protected]> * @license http://www.opensource.org/licenses/mit-license.php MIT License * */ namespace Carrot\Docs; use Exception, InvalidArgumentException, DirectoryIterator; class Storage { /** * @var string The directory that contains the document files, * without trailing directory separator. */ protected $rootDirectory; /** * Constructor. * * If no path was given, the root directory will default to: * * <code> * __DIR__ . DIRECTORY_SEPARATOR . 'Files' * </code> * * The directory contains documentation files in HTML format and * can contain as many folders as you need. You can provide * 'section.html' file on each directory to be loaded when that * section is requested. * * @param string $rootDirectory The directory that contains the * document files. * */ public function __construct($rootDirectory = NULL) { if ($rootDirectory == NULL) { $rootDirectory = __DIR__ . DIRECTORY_SEPARATOR . 'Files'; } $this->setRootDirectory($rootDirectory); } /** * Set the directory that contains the document files. * * @throws InvalidArgumentException If the root directory given * is not a valid path or it's not a directory. * @param string $rootDirectory The directory that contains the * document files. * */ protected function setRootDirectory($rootDirectory) { $rootDirectoryAbsolute = realpath($rootDirectory); if ($rootDirectoryAbsolute == FALSE) { throw new InvalidArgumentException("Storage error in instantiation. The given path '{$rootDirectory}' does not exist."); } if (is_dir($rootDirectoryAbsolute) == FALSE) { throw new InvalidArgumentException("Storage error in instantiation. The given path '{$rootDirectory}' is not directory."); } $this->rootDirectory = $rootDirectoryAbsolute; } /** * Get an instance of page from the given hierarchical path. * * The path array contains the hierarchical path to the * documentation. The array contains item IDs. Example: * * <code> * $path = array( * '1-introduction', * '1-calculator-tutorial', * '1-creating-your-controller' * ); * </code> * * @param array $pagePathArray The hierarchical path to the * documentation page to retrieve. * @return Page|FALSE The documentation page, or FALSE if failed. * */ public function getPage(array $pagePathArray) { if (empty($pagePathArray)) { return $this->getIndexPage(); } $pageInfo = $this->getPageInfo($pagePathArray); if (!is_array($pageInfo)) { return FALSE; } return new Page( $pageInfo['title'], $pageInfo['content'], $pageInfo['parentSections'], $pageInfo['navigation'] ); } /** * Get the page containing the index to be returned. * * Will try to load the contents of the 'section.html' file in * the route, if it fails, will simply return an empty body with * the root navigation. * * @return Page * */ public function getIndexPage() { $parentSections = array(); $navigation = $this->getNavigationItemsFromDirectory($this->rootDirectory, array()); $title = ''; $content = $this->getSectionIndexContent($this->rootDirectory); return new Page( $title, $content, $parentSections, $navigation ); } /** * Get information about the page from the given hierarchical * path. * * Assumes the array is not empty. The structure of the array * returned is as follows: * * <code> * $pageInfo = array( * 'parentSections' => $parentSections, * 'navigation' => $navigation, * 'title' => $title, * 'content' => $content * ); * </code> * * The array $parentSections contains the page's parent sections. * Each section is represented by a {@see NavigationItem} * instance: * * <code> * $parentSections = array( * 0 => $sectionA, * 1 => $sectionB, * 2 => $sectionC * ... * ); * </code> * * The array $navigation contains the list of accessible items * for the current open section, be it a page or another section, * but with the item ID as the indexes: * * <code> * $navigation = array( * '1-introduction' => $navItemA, * '2-autoloading' => $navItemB, * '3-dependency-injection' => $navItemC, * ... * ); * </code> * * @param array $pagePathArray The hierarchical path to the * documentation page to retrieve. * */ protected function getPageInfo(array $pagePathArray) { $parentSections = array(); $navigation = array(); $title = ''; $content = ''; $directory = $this->rootDirectory; $segmentsTraversed = array(); $highestLevel = count($pagePathArray) - 1; foreach ($pagePathArray as $level => $itemID) { $isHighestLevel = ($level == $highestLevel); $availableItems = $this->getNavigationItemsFromDirectory( $directory, $segmentsTraversed ); if (!array_key_exists($itemID, $availableItems)) { return FALSE; } $navItem = $availableItems[$itemID]; if ($isHighestLevel) { if ($navItem->isSection()) { $parentSections[] = $navItem; $segmentsTraversed[] = $itemID; $directory = $navItem->getRealPath(); $navigation = $this->getNavigationItemsFromDirectory( $directory, $segmentsTraversed ); $content = $this->getSectionIndexContent($directory); } else { $navigation = $availableItems; $navigation[$itemID]->markAsCurrent(); $content = $this->getFileContent($navItem->getRealPath()); } return array( 'parentSections' => $parentSections, 'navigation' => $navigation, 'title' => $navItem->getTitle(), 'content' => $content ); } $parentSections[] = $navItem; $segmentsTraversed[] = $itemID; $directory = $navItem->getRealPath(); } } /** * Get the list of navigational items from the given directory. * * Iterates through the given directory and creates instances of * {@see NavigationItem} from its contents. Uses the given root * path segments to construct routing argument arrays of each * NavigationItem instance. * * The root path segments array structure: * * <code> * $rootPathSegments = array( * '1-Introduction', * '1-Calculator-Tutorial' * ); * </code> * * Returns an array containing instances of NavigationItem: * * <code> * $navigationItems = array( * $navItemA, * $navItemB, * $navItemC, * ... * ); * </code> * * @param string $directory Absolute path to the directory to * search the files from. * @param array $rootPathSegments The root path segments leading * to the given directory, to be used in constructing * routing arguments on each NavigationItem instances. * @return array Array containing instances of * {@see NavigationItem}. Returns an empty array if it * fails to retrieve data from the directory. * */ protected function getNavigationItemsFromDirectory($directory, array $rootPathSegments) { $items = array(); try { $iterator = new DirectoryIterator($directory); } catch (Exception $exception) { return $items; } foreach ($iterator as $key => $content) { $navItem = NULL; if ($content->isFile()) { $fileName = $content->getFilename(); $realPath = $content->getPathname(); $navItem = $this->getNavigationItemFromFile( $fileName, $realPath, $rootPathSegments ); } if ($content->isDir() AND $content->isDot() == FALSE) { $fileName = $content->getFilename(); $realPath = $content->getPathname(); $navItem = $this->getNavigationItemFromDirectory( $fileName, $realPath, $rootPathSegments ); } if ($navItem instanceof NavigationItem) { $items[$navItem->getItemID()] = $navItem; } } return $items; } /** * Get a {@see NavigationItem} instance from the given file name * and file path. * * Only accepts '.html' files with the following pattern as the * file name: * * <code> * 1. File Name.html * A. File Name.html * a. File Name.html * </code> * * @see getNavigationItemsFromDirectory() * @param string $fileName The name of the file. * @param string $realPath The real path to the file. * @param array $rootPathSegments The root path segments leading * to the given file, to be used in constructing routing * arguments array. * @return NavigationItem * */ protected function getNavigationItemFromFile($fileName, $realPath, array $rootPathSegments) { $fileNamePattern = '/^([A-Za-z0-9]+\\. (.+))\.html$/uD'; $replaceDotAndSpacesPattern = '/[\\. ]+/u'; if (preg_match($fileNamePattern, $fileName, $matches)) { $title = $matches[2]; $itemID = preg_replace($replaceDotAndSpacesPattern, '-', $matches[1]); $routingArgs = $rootPathSegments; $routingArgs[] = $itemID; return new NavigationItem( $title, 'doc', $routingArgs, $realPath ); } } /** * Get a {@see NavigationItem} instance from the given directory. * * All directory names are accepted. * * @see getNavigationItemsFromDirectory() * @param string $fileName The name of the file. * @param string $realPath The real path to the file. * @param array $rootPathSegments The root path segments leading * to the given file, to be used in constructing routing * arguments array. * @return NavigationItem * */ protected function getNavigationItemFromDirectory($directoryName, $realPath, array $rootPathSegments) { $directoryPattern = '/^([A-Za-z0-9]+\\. (.+))$/uD'; $replaceDotAndSpacesPattern = '/[\\. ]+/u'; if (preg_match($directoryPattern, $directoryName, $matches)) { $title = $matches[2]; $itemID = preg_replace($replaceDotAndSpacesPattern, '-', $matches[1]); $routingArgs = $rootPathSegments; $routingArgs[] = $itemID; return new NavigationItem( $title, 'section', $routingArgs, $realPath ); } } /** * Get the content for section index. * * Will try to get an 'section.html' file on the given directory. * If none found, an empty string will be returned instead. * * @param string $directory The physical counterpart of the * section whose index content we wanted to get, without * trailing directory separator. * @return string * */ protected function getSectionIndexContent($directory) { $filePath = $directory . DIRECTORY_SEPARATOR . 'section.html'; return $this->getFilecontent($filePath); } /** * Get the content from the give file. * * If the file doesn't exist, will return an empty string * instead. * * @param string $filePath Path to the file to get. * */ protected function getFileContent($filePath) { if (!file_exists($filePath)) { return ''; } return file_get_contents($filePath); } }
rickchristie/carrot-old
library/Carrot/Docs/Storage.php
PHP
mit
13,874
<div class="panel panel-primary"> <div ng-show="error" class="alert alert-danger">{{ error }}</div> <div class="panel-heading"> <p class="panel-title">Neuer Gig</p> </div> <div class="panel-body"> <form name="addGig" class="form-horizontal" ng-submit="insertGig(gig)"> <fieldset> <div class="form-group"> <label for="date" class="control-label col-lg-2">Datum:</label> <div class="col-lg-4"> <input type="date" class="form-control" name="date" ng-model="gig.date" placeholder="yyyy-MM-dd" min="2008-01-01" max="2100-12-31" required /> </div> </div> <div class="form-group"> <label for="title" class="control-label col-lg-2">Titel:</label> <div class="col-lg-4"> <input type="text" class="form-control" name="title" ng-model="gig.title" required /> </div> </div> <div class="form-group"> <label for="loc" class="control-label col-lg-2">Location:</label> <div class="col-lg-4"> <input type="text" class="form-control" name="loc" ng-model="gig.loc" /> </div> </div> <div class="form-group"> <label for="status" class="control-label col-lg-2">Status:</label> <div class="col-lg-4"> <select class="form-control" id="status" ng-model="status"> <option>Angefragt</option> <option>Gebucht</option> </select> </div> </div> <div class="form-group"> <label for="contact" class="control-label col-lg-2">Kontakt:</label> <div class="col-lg-4"> <input type="text" class="form-control" name="contact" ng-model="gig.contact" /> </div> </div> <div class="form-group"> <label for="notes" class="control-label col-lg-2">Info:</label> <div class="col-lg-4"> <input type="text" class="form-control" name="notes" ng-model="gig.notes" /> </div> </div> <div class="form-group"> <div class="col-lg-10 col-lg-offset-2"> <button class="btn btn-default" ng-click="back()">Abbrechen</button> <button type="submit" class="btn btn-primary">Speichern</button> </div> </div> </fieldset> </form> </div> </div>
DennisSchwartz/RTBackend
app/partials/modules/admin/gigs.add.html
HTML
mit
2,116
class CreateTeams < ActiveRecord::Migration def self.up create_table :teams do |t| t.string :name t.string :abbreviation t.string :hometown t.timestamps end end def self.down drop_table :teams end end
wndxlori/wndx-multiselect
spec/rails2/app_root/db/migrate.notnow/001_create_teams.rb
Ruby
mit
246
/***************************************************************************** * x264: h264 encoder ***************************************************************************** * Copyright (C) 2005 Tuukka Toivonen <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA. *****************************************************************************/ #ifndef X264_VISUALIZE_H #define X264_VISUALIZE_H #include "common.h" void x264_visualize_init( x264_t *h ); void x264_visualize_mb( x264_t *h ); void x264_visualize_show( x264_t *h ); void x264_visualize_close( x264_t *h ); #endif
tudinfse/fex
src/parsec/x264/src/visualize.h
C
mit
1,272
angular.module('tips.tips').controller('TipsController', ['$scope', '$routeParams', '$location', 'Global', 'Tips', function ($scope, $routeParams, $location, Global, Tips) { $scope.global = Global; $scope.createTip = function () { var tips = new Tips({ text: this.text, likes: this.likes, category: this.category }); tips.$save(function (response) { $location.path("/"); }); this.title = ""; }; $scope.showTip = function () { Tips.query(function (tips) { $scope.tips = tips; tips.linkEdit = 'tips/edit/'; // show tips size function Settings (minLikes, maxLikes) { var that = this; that.size = { min: 26, max: 300 }; that.maxLikes = maxLikes; that.minLikes = tips[0].likes; that.valueOfdivision = (function(){ return (that.size.max - that.size.min)/that.maxLikes })() } function startIsotope(){ var el = $('#isotope-container'); el.isotope({ itemSelector: '.isotope-element', layoutMode: 'fitRows', sortBy: 'number', sortAscending: true, }); return el; } var maxLikes = 0; var minLikes = 0; for (var i = 0; i < tips.length; i++) { if(maxLikes <= tips[i].likes)maxLikes = tips[i].likes; if(minLikes >= tips[i].likes)minLikes = tips[i].likes; }; tips.settingsView = new Settings(minLikes, maxLikes); $scope.$watch('tips', function () { $scope.$evalAsync(function () { var isotope = startIsotope(); }); }) }); }; $scope.updateTip = function (tip) { var tip = new Tips(tip); tip.$update(tip, function(){ console.log("update updateTip: ", tip._id); }, function(){ console.warn("error updateTip:", tip._id); }); }; $scope.getTip = function () { Tips.query(function (tip) { $scope.tip = tip; console.log(tip); }); }; $scope.editTip = function(tip){ console.log("edit tip"); }; }])
Arsey/tips-of-the-day
public/js/controllers/tips.js
JavaScript
mit
2,505
--- layout: post title: Log č. 5 - Áčkové předměty v 2.semestru --- ## Průchod 1. semestrem Těšíte se na 1. semestr? Vážně?! A víte, na co se musíte připravit? <img src="/images/radost.gif" alt="CO"> <h2>VIKBA06 Informační věda 2</h2> <p><i>Oficiální popis:</i>Přímo navazuje na předmět VIKBA01 Informační věda 1. Objasňuje podstatu, smysl, základy, terminologii, dosavadní vývoj, aktuální stav a další možný vývoj vědního a studijního oboru informační věda. </p> <p><i>Názor dálkaře: </i>Přednášky se staly zajímavé a dá se i zapojit. Pro ukončení se píší průběžné testy, na které se musí nastudovat článek v angličtině. Dále se musí vytvořit medailonek nebo skupinová práce. Zatím zajímavý předmět. </p> <h2>VIKBA07 Nástroje a možnosti Internetu</h2> <p><i>Oficiální popis:</i>Cílem předmětu je porozumění možnostem práce s informacemi pomocí nástrojů, které vznikly díky celosvětově dostupné síti internet. </p> <p><i>Názor dálkaře: </i> Když už se po 1 semestru člověk těší na zbavení se transformací, dostane tohle a pokud nejste programátoři nebo jako dálkař máte mimo soukromého i pracovní život, tak se s tím soukromým na následující půl rok rozlučte. Pro tvorbu týdenních úkolu z tohoto předmětu totiž potřebujete všechen volný čas. </p> <h2>VIKBA28 Úvod do studia médií</h2> <p><i>Oficiální popis:</i> Na konci kurzu budete umět vysvětlit strukturu a dynamiku mediálních a kulturních průmyslů. </p> <p><i>Názor dálkaře: </i> Nevím, co napsat, tak nějak jsem neměla čas dojít na žádnou z hodin :-) . </p> <h2>VIKBA30 Psaní odborných textů</h2> <p><i>Oficiální popis:</i>Hlavním cílem předmětu je získat dostatečný přehled o procesu tvorby odborného textu a naučit se psát různorodé odborné texty potřebné nejen pro vysokoškolské studium. </p> <p><i>Názor dálkaře: </i>Pro ukončení musíte napsat seminárku, které předchází vypracování rešerší a projektu. Naprostou náhodou jako dálkař zjistíte pár dní před ukončením odevzdávání, že máte ještě jeden úkol k vytvoření. Takže pozor, ještě se vytváří redukovaný text, což zjistíte, když si otevřete odevzdávárny předmětu. </p> <h2>VIK_PoZ Postupová zkouška</h2> <p><i>Oficiální popis:</i>Postupová zkouška je kontrolní zkouškou završující první rok studia. Je prerekvizitou k předmětům třetího a čtvrtého semestru. </p> <p><i>Názor dálkaře: </i>Zatím mám nachystané podklady, tak těžko říct, co z toho nakonec vyleze. </p> <p></p> <p></p> <p></p> <p><u>Zdroje informací: </u></p> <p><a href="https://kisk.phil.muni.cz/cs">1. Stránky KISKu </a></p> <p><a href="http://www.phil.muni.cz/wff">2. Stránky FF MUNI </a></p>
VendyStr/vendystr.github.io
_posts/2014-3-3-prepracovani.md
Markdown
mit
2,844
# Get Single Promotion This gets an XML document with the specific promotion by the ID. ## Single Promotion Options [MadMimi's Promotion Documentation](https://madmimi.com/developer/api/promotions) should give you an idea of what you need to send to the API. This options object makes some of the methods easier. ### Method Reference `Single::setPromotionId($promotionId)` - Sets the promotion ID to retrieve ## Exceptions The following exceptions may be thrown throughout the duration of a options object. - `MadMimi\Exception\InvalidOptionException` During options object creation, a value in the array of the constructor argument that's key was not defined as a protected property of this options class
aaronsaray/madmimi-api-php
docs/promotions/single.md
Markdown
mit
719
# Laravel Favorite (Laravel 5, 6, 7, 8 Package) [![Latest Version on Packagist][ico-version]][link-packagist] [![Packagist Downloads][ico-downloads]][link-packagist] [![Software License][ico-license]](LICENSE.md) [![Build Status][ico-travis]][link-travis] **Allows Laravel Eloquent models to implement a 'favorite' or 'remember' or 'follow' feature.** ## Index - [Installation](#installation) - [Models](#models) - [Usage](#usage) - [Testing](#testing) - [Change log](#change-log) - [Contributions](#contributions) - [Pull Requests](#pull-requests) - [Security](#security) - [Credits](#credits) - [License](#license) ## Installation 1) Install the package via Composer ```bash $ composer require christiankuri/laravel-favorite ``` 2) In Laravel >=5.5 this package will automatically get registered. For older versions, update your `config/app.php` by adding an entry for the service provider. ```php 'providers' => [ // ... ChristianKuri\LaravelFavorite\FavoriteServiceProvider::class, ]; ``` 3) Publish the database from the command line: ```shell php artisan vendor:publish --provider="ChristianKuri\LaravelFavorite\FavoriteServiceProvider" ``` 4) Migrate the database from the command line: ```shell php artisan migrate ``` ## Models Your User model should import the `Traits/Favoriteability.php` trait and use it, that trait allows the user to favorite the models. (see an example below): ```php use ChristianKuri\LaravelFavorite\Traits\Favoriteability; class User extends Authenticatable { use Favoriteability; } ``` Your models should import the `Traits/Favoriteable.php` trait and use it, that trait have the methods that you'll use to allow the model be favoriteable. In all the examples I will use the Post model as the model that is 'Favoriteable', thats for example propuses only. (see an example below): ```php use ChristianKuri\LaravelFavorite\Traits\Favoriteable; class Post extends Model { use Favoriteable; } ``` That's it ... your model is now **"favoriteable"**! Now the User can favorite models that have the favoriteable trait. ## Usage The models can be favorited with and without an authenticated user (see examples below): ### Add to favorites and remove from favorites: If no param is passed in the favorite method, then the model will asume the auth user. ``` php $post = Post::find(1); $post->addFavorite(); // auth user added to favorites this post $post->removeFavorite(); // auth user removed from favorites this post $post->toggleFavorite(); // auth user toggles the favorite status from this post ``` If a param is passed in the favorite method, then the model will asume the user with that id. ``` php $post = Post::find(1); $post->addFavorite(5); // user with that id added to favorites this post $post->removeFavorite(5); // user with that id removed from favorites this post $post->toggleFavorite(5); // user with that id toggles the favorite status from this post ``` The user model can also add to favorites and remove from favrites: ``` php $user = User::first(); $post = Post::first(); $user->addFavorite($post); // The user added to favorites this post $user->removeFavorite($post); // The user removed from favorites this post $user->toggleFavorite($post); // The user toggles the favorite status from this post ``` ### Return the favorite objects for the user: A user can return the objects he marked as favorite. You just need to pass the **class** in the `favorite()` method in the `User` model. ``` php $user = Auth::user(); $user->favorite(Post::class); // returns a collection with the Posts the User marked as favorite ``` ### Return the favorites count from an object: You can return the favorites count from an object, you just need to return the `favoritesCount` attribute from the model ``` php $post = Post::find(1); $post->favoritesCount; // returns the number of users that have marked as favorite this object. ``` ### Return the users who marked this object as favorite You can return the users who marked this object, you just need to call the `favoritedBy()` method in the object ``` php $post = Post::find(1); $post->favoritedBy(); // returns a collection with the Users that marked the post as favorite. ``` ### Check if the user already favorited an object You can check if the Auth user have already favorited an object, you just need to call the `isFavorited()` method in the object ``` php $post = Post::find(1); $post->isFavorited(); // returns a boolean with true or false. ``` ## Testing The package have integrated testing, so everytime you make a pull request your code will be tested. ## Change log Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. ## Contributions Contributions are **welcome** and will be fully **credited**. We accept contributions via Pull Requests on [Github](https://github.com/ChristianKuri/laravel-favorite). ### Pull Requests - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - Check the code style with ``$ composer check-style`` and fix it with ``$ composer fix-style``. - **Add tests!** - Your patch won't be accepted if it doesn't have tests. - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. - **Create feature branches** - Don't ask us to pull from your master branch. - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. ## Security Please report any issue you find in the issues page. Pull requests are welcome. ## Credits - [Christian Kuri][link-author] - [All Contributors][link-contributors] ## License The MIT License (MIT). Please see [License File](LICENSE.md) for more information. [ico-version]: https://img.shields.io/packagist/v/ChristianKuri/laravel-favorite.svg?style=flat-square [ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square [ico-travis]: https://img.shields.io/travis/ChristianKuri/laravel-favorite/master.svg?style=flat-square [ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/ChristianKuri/laravel-favorite.svg?style=flat-square [ico-code-quality]: https://img.shields.io/scrutinizer/g/ChristianKuri/laravel-favorite.svg?style=flat-square [ico-downloads]: https://img.shields.io/packagist/dt/ChristianKuri/laravel-favorite.svg?style=flat-square [link-packagist]: https://packagist.org/packages/ChristianKuri/laravel-favorite [link-travis]: https://travis-ci.org/ChristianKuri/laravel-favorite [link-scrutinizer]: https://scrutinizer-ci.com/g/ChristianKuri/laravel-favorite/code-structure [link-code-quality]: https://scrutinizer-ci.com/g/ChristianKuri/laravel-favorite [link-downloads]: https://packagist.org/packages/ChristianKuri/laravel-favorite [link-author]: https://github.com/ChristianKuri [link-contributors]: ../../contributors
ChristianKuri/laravel-favorite
README.md
Markdown
mit
7,370
package com.xeiam.xchange.cryptotrade.dto; import java.io.IOException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.xeiam.xchange.cryptotrade.dto.CryptoTradeOrderType.CryptTradeOrderTypeDeserializer; @JsonDeserialize(using = CryptTradeOrderTypeDeserializer.class) public enum CryptoTradeOrderType { Buy, Sell; static class CryptTradeOrderTypeDeserializer extends JsonDeserializer<CryptoTradeOrderType> { @Override public CryptoTradeOrderType deserialize(final JsonParser jsonParser, final DeserializationContext ctxt) throws IOException, JsonProcessingException { final ObjectCodec oc = jsonParser.getCodec(); final JsonNode node = oc.readTree(jsonParser); final String orderType = node.asText(); return CryptoTradeOrderType.valueOf(orderType); } } }
Achterhoeker/XChange
xchange-cryptotrade/src/main/java/com/xeiam/xchange/cryptotrade/dto/CryptoTradeOrderType.java
Java
mit
1,150
module Mailplug class Plugin::Example < Mailplug::Middleware # Message Envelope Methods def return_path end def recipients end def message # returns Mail::Message end # Hash of state and inter-stack data memo[classname][key]=value def memo end # SMTP State Changes def open(remote_ip) end def helo(server_name) end def mail_from(email) end def rcpt_to(email) end def data end def data_line(line) end def data_stop end def save # false(i don't queue), true (i queued), error msg end def quit end def close end def header(name, value) end def abort(code, msg) # Stop it with reason end def continue # don't stop end def log(msg) end def status(number, message, close, waitseconds=0) end # SMTP Responses http://www.greenend.org.uk/r def service_ready # 220 end end end
afair/mailplug
lib/mailplug/plugin/example.rb
Ruby
mit
969
import apiConfig from './MovieDBConfig'; import TmdbApi from 'moviedb-api'; var api = new TmdbApi({ consume: false, apiKey: apiConfig.apiKey }); const makeAndList = (list) => { return list.map(item => item.value).join(); }; export const getGenres = (input='', callback) => { api.request('/genre/movie/list', 'GET') .then(res => { return res.genres.map(item => { return {label: item.name, value: item.id}; }) }) .then(json => callback(null, {options: json, complete: false})) .catch(err => console.log(err)); }; export const getKeywords = (input='', callback) => { api.request('/search/keyword', 'GET', {query: input}) .then(res => { return res.results.map(item => { return {label: item.name, value: item.id}; }); }) .then(json => callback(null, {options: json, complete: false})) .catch(err => console.log(err)); }; export const getActors = (input='', callback) => { api.request('/search/person', 'GET', {query: input}) .then(res => { return res.results.map(item => { return {label: item.name, value: item.id}; }); }) .then(json => callback(null, {options: json, complete: false})) .catch(err => console.log(err)); }; export const discover = (genres=null, keywords=null, actors, minYear, maxYear, page=1) => { let g = genres ? makeAndList(genres) : null; let k = keywords ? makeAndList(keywords) : null; let a = actors ? makeAndList(actors) : null; return api.request('/discover/movie', 'GET', { with_genres: g, with_keywords: k, with_cast: a, "release_date.gte": minYear, "release_date.lte": maxYear, page }) .then(res => res) }; export const getVideos = (id, language='en') => { return api.request(`/movie/${id}/videos`, 'GET', {language}) }; export const getMovieKeywords = (id, language='en') => { return api.request(`/movie/${id}/keywords`, 'GET', {language}) }; export const discoverWithVideo = (genres=null, keywords=null, actors, minYear, maxYear) => { return discover(genres, keywords, actors, minYear, maxYear) .then(res => { return Promise.all( res.results.map(item => getVideos(item.id) .then(videos => videos.results[0]) ) ).then(list => { return { ...res, results: res.results.map((item, index) => { item.youtube = list[index]; return item; }) } }) }) }; export const getDetails = (id, language='en') => { return api.request(`/movie/${id}`, 'GET', {language, append_to_response: "keywords,videos"}) };
arddor/MovieAdvisor
app/utils/api.js
JavaScript
mit
2,618
const excludedTables = ["blacklist", "musicCache", "timedEvents"]; const statPoster = require("../../modules/statPoster.js"); module.exports = async guild => { let tables = await r.tableList().run(); for(let table of tables) { let indexes = await r.table(table).indexList().run(); if(~indexes.indexOf("guildID")) r.table(table).getAll(guild.id, { index: "guildID" }).delete().run(); else r.table(table).filter({ guildID: guild.id }).delete().run(); } if(bot.config.bot.serverChannel) { let owner = bot.users.get(guild.ownerID); let botCount = guild.members.filter(member => member.bot).length; let botPercent = ((botCount / guild.memberCount) * 100).toFixed(2); let userCount = guild.memberCount - botCount; let userPercent = ((userCount / guild.memberCount) * 100).toFixed(2); let content = "❌ LEFT GUILD ❌\n"; content += `Guild: ${guild.name} (${guild.id})\n`; content += `Owner: ${owner.username}#${owner.discriminator} (${owner.id})\n`; content += `Members: ${guild.memberCount} **|** `; content += `Users: ${userCount} (${userPercent}%) **|** `; content += `Bots: ${botCount} (${botPercent}%)`; try { await bot.createMessage(bot.config.bot.serverChannel, content); } catch(err) { console.error(`Failed to send message to server log: ${err.message}`); } } statPoster(); };
minemidnight/oxyl
src/bot/listeners/on/guildDelete.js
JavaScript
mit
1,331
using System.Collections.Generic; using System.IO; using System.Reflection; using IDI.Core.Common.Extensions; namespace IDI.Core.Localization { public abstract class Package { public List<PackageItem> Items { get; private set; } = new List<PackageItem>(); public Package(string assemblyName, string packageName) { var assembly = Assembly.Load(new AssemblyName(assemblyName)); if (assembly == null) return; using (Stream stream = assembly.GetManifestResourceStream(packageName)) { if (stream == null) return; using (StreamReader reader = new StreamReader(stream)) { string json = reader.ReadToEnd(); this.Items = json.To<List<PackageItem>>(); } } } } }
idi-studio/com.idi.central.api
src/IDI.Core/Localization/Package.cs
C#
mit
905
--- layout: page title: Twoer Summit Electronics Award Ceremony date: 2016-05-24 author: Hannah Shah tags: weekly links, java status: published summary: Morbi feugiat purus a risus. banner: images/banner/leisure-02.jpg booking: startDate: 10/11/2017 endDate: 10/13/2017 ctyhocn: PHXCNHX groupCode: TSEAC published: true --- Aliquam posuere ante nec dui pulvinar, eu ultrices turpis feugiat. Nullam quis turpis nisi. Sed auctor purus sit amet orci consectetur consectetur. Ut euismod nec nisi vitae efficitur. Phasellus sit amet ipsum sed libero dapibus egestas. Proin nunc nunc, finibus in accumsan eu, rutrum vitae enim. Sed posuere, purus vel tincidunt faucibus, neque lacus rutrum libero, at tristique leo leo vel lectus. Ut eleifend lobortis libero. * Mauris et nulla in arcu viverra rhoncus * Mauris ornare metus in consequat finibus * Phasellus eget libero euismod, volutpat dolor nec, tincidunt justo. Morbi eu nulla felis. Donec pretium ex maximus, efficitur lorem non, fringilla metus. Nullam id nulla eleifend, congue velit id, laoreet ante. Donec imperdiet ut orci ullamcorper congue. Sed sed risus urna. Etiam ultrices tortor eget neque vehicula dictum. Sed eu nulla imperdiet massa porttitor malesuada fringilla non enim. Suspendisse potenti. Duis in orci ex. Praesent lectus lorem, posuere ut venenatis a, elementum et ligula. Sed aliquam erat auctor lacus convallis, et sodales arcu fermentum. Maecenas blandit augue sed quam consectetur, sit amet semper augue pretium. Proin ut tincidunt turpis. Integer est ipsum, pulvinar non tempor eget, maximus non enim. Nullam sollicitudin nisl eu nunc ultrices, et aliquet dolor commodo. Integer imperdiet dignissim accumsan. Nam nisi sapien, volutpat at ante vel, egestas volutpat turpis. Aliquam laoreet quam eget neque lobortis dictum. Nunc at nibh turpis. Fusce ac nisl urna. Morbi congue nisi iaculis lobortis venenatis. Nulla rhoncus faucibus est.
KlishGroup/prose-pogs
pogs/P/PHXCNHX/TSEAC/index.md
Markdown
mit
1,920
// // UIView+BluredSnapshot.h // CustomTransitionAndBlur // // Created by Gao Song on 11/1/15. // Copyright © 2015 Gao Song. All rights reserved. // #import <UIKit/UIKit.h> @interface UIView (BluredSnapshot) -(UIImage *)blurredSnapshot; @end
jack2gs/CustomInteractiveTransitionAndBlur
CustomTransitionAndBlur/UIView+BluredSnapshot.h
C
mit
249
-- collate4.test -- -- execsql { -- CREATE TABLE collate4t3(a COLLATE NOCASE, b COLLATE TEXT); -- INSERT INTO collate4t3 VALUES( 'a', 'a' ); -- INSERT INTO collate4t3 VALUES( 'b', 'b' ); -- INSERT INTO collate4t3 VALUES( NULL, NULL ); -- INSERT INTO collate4t3 VALUES( 'B', 'B' ); -- INSERT INTO collate4t3 VALUES( 'A', 'A' ); -- CREATE INDEX collate4i2 ON collate4t3(a COLLATE TEXT, b COLLATE NOCASE); -- } CREATE TABLE collate4t3(a COLLATE NOCASE, b COLLATE TEXT); INSERT INTO collate4t3 VALUES( 'a', 'a' ); INSERT INTO collate4t3 VALUES( 'b', 'b' ); INSERT INTO collate4t3 VALUES( NULL, NULL ); INSERT INTO collate4t3 VALUES( 'B', 'B' ); INSERT INTO collate4t3 VALUES( 'A', 'A' ); CREATE INDEX collate4i2 ON collate4t3(a COLLATE TEXT, b COLLATE NOCASE);
bkiers/sqlite-parser
src/test/resources/collate4.test_8.sql
SQL
mit
785
import { computed, get } from '@ember/object'; import { getOwner } from '@ember/application'; import { deprecate } from '@ember/debug'; export function ability(abilityName, resourceName) { deprecate( 'Using ability() computed property is deprecated. Use getters and Can service directly.', false, { for: 'ember-can', since: { enabled: '4.0.0', }, id: 'ember-can.deprecate-ability-computed', until: '5.0.0', } ); resourceName = resourceName || abilityName; return computed(resourceName, function () { let canService = getOwner(this).lookup('service:abilities'); return canService.abilityFor(abilityName, get(this, resourceName)); }).readOnly(); }
minutebase/ember-can
addon/computed.js
JavaScript
mit
721
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20140216162246) do create_table "active_admin_comments", force: true do |t| t.string "namespace" t.text "body" t.string "resource_id", null: false t.string "resource_type", null: false t.integer "author_id" t.string "author_type" t.datetime "created_at" t.datetime "updated_at" end add_index "active_admin_comments", ["author_type", "author_id"], name: "index_active_admin_comments_on_author_type_and_author_id" add_index "active_admin_comments", ["namespace"], name: "index_active_admin_comments_on_namespace" add_index "active_admin_comments", ["resource_type", "resource_id"], name: "index_active_admin_comments_on_resource_type_and_resource_id" create_table "admin_users", force: true do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.datetime "created_at" t.datetime "updated_at" end add_index "admin_users", ["email"], name: "index_admin_users_on_email", unique: true add_index "admin_users", ["reset_password_token"], name: "index_admin_users_on_reset_password_token", unique: true create_table "deposit_addresses", force: true do |t| t.integer "sponsor_id" t.integer "project_id" t.string "bitcoin_address" t.datetime "created_at" t.datetime "updated_at" t.integer "month_donations", limit: 8 t.integer "year_donations", limit: 8 end add_index "deposit_addresses", ["project_id"], name: "index_deposit_addresses_on_project_id" add_index "deposit_addresses", ["sponsor_id"], name: "index_deposit_addresses_on_sponsor_id" create_table "deposits", force: true do |t| t.integer "deposit_address_id" t.integer "amount", limit: 8 t.string "input_tx" t.integer "confirmations" t.string "output_tx" t.datetime "created_at" t.datetime "updated_at" end add_index "deposits", ["deposit_address_id"], name: "index_deposits_on_deposit_address_id" create_table "projects", force: true do |t| t.string "name" t.text "about" t.string "url" t.string "bitcoin_address" t.datetime "created_at" t.datetime "updated_at" t.string "donation_page_url" t.integer "month_donations", limit: 8 t.datetime "moderated_at" t.integer "year_donations", limit: 8 end create_table "sponsors", force: true do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.string "confirmation_token" t.datetime "confirmed_at" t.datetime "confirmation_sent_at" t.string "unconfirmed_email" t.datetime "created_at" t.datetime "updated_at" t.string "avatar" t.string "name" t.string "url" t.string "location" t.boolean "private_donations", default: false t.integer "month_donations", limit: 8 t.integer "year_donations", limit: 8 end add_index "sponsors", ["confirmation_token"], name: "index_sponsors_on_confirmation_token", unique: true add_index "sponsors", ["email"], name: "index_sponsors_on_email", unique: true add_index "sponsors", ["reset_password_token"], name: "index_sponsors_on_reset_password_token", unique: true end
tip4commit/coingiving
db/schema.rb
Ruby
mit
4,772
/* global requirejs, require */ /*jslint node: true */ 'use strict'; import Ember from 'ember'; import _keys from 'lodash/object/keys'; /* This function looks through all files that have been loaded by Ember CLI and finds the ones under /mirage/[factories, fixtures, scenarios, models]/, and exports a hash containing the names of the files as keys and the data as values. */ export default function(prefix) { let modules = ['factories', 'fixtures', 'scenarios', 'models', 'serializers']; let mirageModuleRegExp = new RegExp(`^${prefix}/mirage/(${modules.join("|")})`); let modulesMap = modules.reduce((memo, name) => { memo[name] = {}; return memo; }, {}); _keys(requirejs.entries).filter(function(key) { return mirageModuleRegExp.test(key); }).forEach(function(moduleName) { if (moduleName.match('.jshint')) { // ignore autogenerated .jshint files return; } let moduleParts = moduleName.split('/'); let moduleType = moduleParts[moduleParts.length - 2]; let moduleKey = moduleParts[moduleParts.length - 1]; Ember.assert('Subdirectories under ' + moduleType + ' are not supported', moduleParts[moduleParts.length - 3] === 'mirage'); if (moduleType === 'scenario'){ Ember.assert('Only scenario/default.js is supported at this time.', moduleKey !== 'default'); } let module = require(moduleName, null, null, true); if (!module) { throw new Error(moduleName + ' must export a ' + moduleType); } let data = module['default']; modulesMap[moduleType][moduleKey] = data; }); return modulesMap; }
ballPointPenguin/ember-cli-mirage
addon/utils/read-modules.js
JavaScript
mit
1,627
/* tslint:disable:no-unused-variable */ import { TestBed, async } from '@angular/core/testing'; import { DpsBarChartComponent } from './dps-bar-chart.component'; describe('Component: DpsBarChart', () => { it('should create an instance', () => { let component = new DpsBarChartComponent(); expect(component).toBeTruthy(); }); });
NablaT/TemplateDemo
src/app/core/charts/chart/chart.component.spec.ts
TypeScript
mit
343
<?php /** * @author tshirtecommerce - www.tshirtecommerce.com * @date: 2015-01-10 * * @copyright Copyright (C) 2015 tshirtecommerce.com. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE * */ if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> <script src="<?php echo base_url('assets/plugins/jquery-fancybox/jquery.fancybox.js'); ?>" type="text/javascript"></script> <script src="<?php echo base_url('assets/plugins/validate/validate.js'); ?>" type="text/javascript"></script> <link href="<?php echo base_url('assets/plugins/jquery-fancybox/jquery.fancybox.css'); ?>" rel="stylesheet"/> <form name="setting" class="setting-save" method="POST" action="<?php echo site_url('m_product/admin/setting/save/'.$id); ?>"> <div class="tabpanel" role="tabpanel"> <!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#tab-general" aria-controls="tab-general" role="tab" data-toggle="tab"><?php echo lang('general');?></a></li> <li role="presentation"><a href="#tab-design" aria-controls="tab-design" role="tab" data-toggle="tab"><?php echo lang('design_options'); ?></a></li> <li class="button-back pull-right"><a href="javascript:void(0)" onclick="grid.module.setting('m_product')" title="Back to list"><i class="clip-arrow-left-2"></i></a></li> </ul> <!-- Tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="tab-general"> <div class="form-group"> <label><?php echo lang('title');?><span class="symbol required"></span></label> <input type="text" class="form-control input-sm validate required" name="title" placeholder="<?php echo lang('title');?>" value="<?php echo $m_product->title; ?>" data-minlength="2" data-maxlength="200" data-msg="<?php echo lang('m_product_admin_setting_title_validate');?>"> </div> <?php $options = json_decode($m_product->options); ?> <div class="form-group"> <div class="row"> <div class="col-sm-6"> <label><?php echo lang('m_product_admin_setting_show_title');?></label> <?php $show_title = array( 'yes'=>lang('yes'), 'no'=>lang('no'), ); if(isset($options->show_title)) $default = $options->show_title; else $default = ''; echo form_dropdown('options[show_title]', $show_title, $default, 'class="form-control input-sm"'); ?> </div> <div class="col-sm-6"> <label><?php echo lang('m_product_admin_setting_count_cols_title');?></label> <?php $cols = array( '1'=>1, '2'=>2, '3'=>3, '4'=>4, '6'=>6, ); if(isset($options->cols)) $default = $options->cols; else $default = ''; echo form_dropdown('options[cols]', $cols, $default, 'class="form-control input-sm"'); ?> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-sm-6"> <label><?php echo lang('m_product_admin_setting_show_product_title');?></label> <?php $show_product = array( 'lastest'=>lang('m_product_admin_setting_lastest_title'), 'future'=>lang('m_product_admin_setting_future_title'), 'sale_price'=>lang('m_product_admin_setting_sale_title'), ); if(isset($options->show_product)) $default = $options->show_product; else $default = ''; echo form_dropdown('options[show_product]', $show_product, $default, 'class="form-control input-sm"'); ?> </div> <div class="col-sm-6"> <label><?php echo lang('m_product_admin_setting_count_product_title');?></label> <input type="text" name="options[count]" class="form-control input-sm" value="<?php if(isset($options->count) && $options->count != '') echo $options->count; else echo 8; ?>" placeholder="<?php echo lang('m_product_admin_setting_count_product_title');?>"/> </div> </div> </div> </div> <!-- design options --> <?php $params = json_decode($m_product->params, true); ?> <div role="tabpanel" class="tab-pane" id="tab-design"> <div class="design-box"> <div class="design-box-left"> <div class="box-css"> <label><?php echo lang('css');?></label> <div class="box-margin"> <label><?php echo lang('margin');?></label> <input type="text" class="box-input" name="params[margin][left]" value="<?php echo setParams($params, 'margin', 'left'); ?>" id="margin-left"> <input type="text" class="box-input" name="params[margin][right]" value="<?php echo setParams($params, 'margin', 'right'); ?>" id="margin-right"> <input type="text" class="box-input" name="params[margin][top]" value="<?php echo setParams($params, 'margin', 'top'); ?>" id="margin-top"> <input type="text" class="box-input" name="params[margin][bottom]" value="<?php echo setParams($params, 'margin', 'bottom'); ?>" id="margin-bottom"> <div class="box-border"> <label><?php echo lang('border');?></label> <input type="text" class="box-input" name="params[border][left]" value="<?php echo setParams($params, 'border', 'left'); ?>" id="border-left"> <input type="text" class="box-input" name="params[border][right]" value="<?php echo setParams($params, 'border', 'right'); ?>" id="border-right"> <input type="text" class="box-input" name="params[border][top]" value="<?php echo setParams($params, 'border', 'top'); ?>" id="border-top"> <input type="text" class="box-input" name="params[border][bottom]" value="<?php echo setParams($params, 'border', 'bottom'); ?>" id="border-bottom"> <div class="box-padding"> <label><?php echo lang('padding');?></label> <input type="text" class="box-input" name="params[padding][left]" value="<?php echo setParams($params, 'padding', 'left'); ?>" id="padding-left"> <input type="text" class="box-input" name="params[padding][right]" value="<?php echo setParams($params, 'padding', 'right'); ?>" id="padding-right"> <input type="text" class="box-input" name="params[padding][top]" value="<?php echo setParams($params, 'padding', 'top'); ?>" id="padding-top"> <input type="text" class="box-input" name="params[padding][bottom]" value="<?php echo setParams($params, 'padding', 'bottom'); ?>" id="padding-bottom"> <div class="box-elment"> </div> </div> </div> </div> </div> </div> <div class="design-box-right"> <label><?php echo lang('border');?></label> <div class="row col-md-12"> <div class="form-group pick-color"> <div class="input-group"> <input type="text" class="form-control color input-sm" name="params[borderColor]" value="<?php echo setParams($params, 'borderColor'); ?>"> <div class="input-group-addon pick-color-btn"><?php echo lang('select_color');?></div> </div> <a href="#" class="btn btn-default btn-sm pick-color-clear"><?php echo lang('clear');?></a> </div> </div> <div class="row col-md-12"> <div class="form-group"> <?php $options = array('Defaults', 'Solid','Dotted','Dashed','None','Hidden','Double','Groove','Ridge','Inset','Outset','Initial','Inherit'); ?> <select class="form-control input-sm" name="params[borderStyle]"> <?php for($i=0; $i<12; $i++){ ?> <?php $border_style = setParams($params, 'borderStyle'); if($border_style == $options[$i]) $check = 'selected="selected"'; else $check = ''; ?> <option value="<?php echo $options[$i]; ?>" <?php echo $check;?>><?php echo $options[$i]; ?></option> <?php } ?> </select> </div> </div> <label><?php echo lang('background');?></label> <div class="row col-md-12"> <div class="form-group pick-color"> <div class="input-group"> <input type="text" class="form-control color input-sm" name="params[background][color]" value="<?php echo setParams($params, 'background', 'color'); ?>"> <div class="input-group-addon pick-color-btn"><?php echo lang('select_color');?></div> </div> <a href="#" class="btn btn-default btn-sm pick-color-clear"><?php echo lang('clear');?></a> </div> </div> <div class="row col-md-12"> <div class="form-group"> <?php $image = setParams($params, 'background', 'image'); if($image != '') { echo '<div id="gird-box-bg" style="display:inline;">'; echo '<img src="'.base_url($image).'" class="pull-left box-image" style="width: 80px;" alt="" width="100" />'; }else { echo '<div id="gird-box-bg" style="display:none;">'; } ?> <a href="javascript:void(0)" class="gird-box-bg-remove" onclick="gridRemoveImg(this)"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a> </div> <input type="hidden" name="params[background][image]" id="gird-box-bg-img" value="<?php echo $image; ?>"> <a class="gird-box-image" href="javascript:void(0)" onclick="jQuery.fancybox( {href : '<?php echo site_url().'admin/media/modals/productImg/1'; ?>', type: 'iframe'} );"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span></a> </div> </div> <div class="row col-md-12"> <div class="form-group"> <?php $options = array('Defaults','Repeat','No repeat'); ?> <select class="form-control input-sm" name="params[background][style]"> <?php for($i=0; $i<3; $i++){ ?> <?php $background_style = setParams($params, 'background', 'style'); if($background_style == $options[$i]) $check = 'selected="selected"'; else $check = ''; ?> <option value="<?php echo $options[$i]; ?>" <?php echo $check; ?>><?php echo $options[$i]; ?></option> <?php } ?> </select> </div> </div> </div> </div> </div> </div> </div> </form> <script type="text/javascript"> function productImg(images) { if(images.length > 0) { var e = jQuery('#gird-box-bg'); if(e.children('img').length > 0) e.children('img').attr('src', images[0]); else e.append('<img src="'+images[0]+'" class="pull-left box-image" style="width: 80px;" alt="" width="100" />'); e.css('display', 'inline'); var str = images[0]; str = str.replace("<?php echo base_url();?>", ""); jQuery('#gird-box-bg-img').val(str); jQuery.fancybox.close(); } } function gridRemoveImg(e){ var e = jQuery('#gird-box-bg'); e.children('img').remove(); e.css('display', 'none'); jQuery('#gird-box-bg-img').val(''); } </script>
Nnamso/tbox
application/modules/m_product/views/admin/setting.php
PHP
mit
11,129
# Botfather configs [BotFather](https://telegram.me/botfather) allows you to create Telegram bots, and instanciates authentication tokens. But it does more than that. To get the same settings as FiddleGram, follow this: * Go to Botfather, use `/start` and follow the instructions to create your bot. Put the auth token in `token.js` * Set up description and about text as you please * Use /setcommands and give the following block: ``` start - [language] start a new repl session stop - stop current repl session languages - list currently supported languages version - list bot and languages versions help - display help ``` This will enable auto-completion on commands. All done! Your Fiddlegram is ready to rock.
LeonardA-L/fiddlegram
Botfather_config.md
Markdown
mit
718
<?php declare(strict_types=1); namespace AlphaVantageTest\Api; use AlphaVantage\Api\ForeignExchange; class ForeignExchangeTest extends TestCase { public function testCurrencyExchangeRate() { $actual = (new ForeignExchange($this->option))->currencyExchangeRate('BTC', 'CNY'); $this->assertIsArray($actual); $this->assertCount(1, $actual); $this->assertArrayHasKey('Realtime Currency Exchange Rate', $actual); $this->assertNotEmpty($actual['Realtime Currency Exchange Rate']); $this->assertCount(9, $actual['Realtime Currency Exchange Rate']); } }
kokspflanze/alpha-vantage-api
tests/Api/ForeignExchangeTest.php
PHP
mit
610
local u = require "lib/util" local Node = require "lib/espalier/node" local Section = require "Orbit/section" local own = require "Orbit/own" local D = setmetatable({}, { __index = Node }) D.id = "doc" D.__tostring = function (doc) local phrase = "" for _,v in ipairs(doc) do local repr = tostring(v) if repr ~= "" and repr ~= "\n" then phrase = phrase .. repr .. "\n" end end return phrase end D.__index = D D.own = own function D.dotLabel(doc) return "doc - " .. tostring(doc.linum) end function D.toMarkdown(doc) local phrase = "" for _, node in ipairs(doc) do if node.toMarkdown then phrase = phrase .. node:toMarkdown() else u.freeze("no toMarkdown method for " .. node.id) end end return phrase end local d = {} function D.parentOf(doc, level) local i = level - 1 local parent = nil while i >= 0 do parent = doc.lastOf[i] if parent then return parent else i = i - 1 end end return doc end function D.addSection(doc, section, linum, finish) assert(section.id == "section", "type of putative section is " .. section.id) assert(section.first, "no first in section at line " .. tostring(linum)) assert(type(finish) == "number", "finish is of type " .. type(finish)) if not doc.latest then doc[1] = section else if linum > 0 then doc.latest.line_last = linum - 1 doc.latest.last = finish end local atLevel = doc.latest.level if atLevel < section.level then -- add the section under the latest section doc.latest:addSection(section, linum, finish) else local parent = doc:parentOf(section.level) if parent.id == "doc" then if section.level == 1 and doc.latest.level == 1 then doc[#doc + 1] = section else doc.latest:addSection(section, linum, finish) end else parent:addSection(section, linum, finish) end end end doc.latest = section doc.lastOf[section.level] = section return doc end function D.addLine(doc, line, linum, finish) if doc.latest then doc.latest:addLine(line) doc.latest.last = finish else -- a virtual zero block doc[1] = Section(0, linum, 1, #line, doc.str) doc.latest = doc[1] doc.latest:addLine(line) doc.latest.last = finish end return doc end local function new(Doc, str) local doc = setmetatable({}, D) doc.str = str doc.first = 1 doc.last = #str doc.latest = nil doc.lines = {} doc.lastOf = {} -- for now lets set root to 'false' doc.root = false return doc:own(str) end setmetatable(D, Node) d["__call"] = new return setmetatable({}, d)
mnemnion/grym
src/Orbit/doc.lua
Lua
mit
3,039
package com.github.aureliano.evtbridge.output.file; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Set; import org.junit.Test; import com.github.aureliano.evtbridge.annotation.validation.NotNull; import com.github.aureliano.evtbridge.annotation.validation.apply.ConstraintViolation; import com.github.aureliano.evtbridge.annotation.validation.apply.ObjectValidator; import com.github.aureliano.evtbridge.core.config.OutputConfigTypes; public class FileOutputConfigTest { ObjectValidator validator = ObjectValidator.instance(); @Test public void testGetDefaults() { FileOutputConfig c = new FileOutputConfig(); assertNull(c.getFile()); assertEquals("UTF-8", c.getEncoding()); assertFalse(c.isAppend()); assertTrue(c.isUseBuffer()); } @Test public void testConfiguration() { FileOutputConfig c = new FileOutputConfig() .withAppend(true) .withEncoding("ISO-8859-1") .withFile("/there/is/not/file"); assertEquals("/there/is/not/file", c.getFile().getPath()); assertEquals("ISO-8859-1", c.getEncoding()); assertTrue(c.isAppend()); } @Test public void testClone() { FileOutputConfig c1 = new FileOutputConfig() .withAppend(true) .withUseBuffer(false) .withEncoding("ISO-8859-1") .withFile("/there/is/not/file") .putMetadata("test", "my test"); FileOutputConfig c2 = c1.clone(); assertEquals(c1.getFile(), c2.getFile()); assertEquals(c1.getEncoding(), c2.getEncoding()); assertEquals(c1.isAppend(), c2.isAppend()); assertEquals(c1.isUseBuffer(), c2.isUseBuffer()); assertEquals(c1.getMetadata("test"), c2.getMetadata("test")); } @Test public void testOutputType() { assertEquals(OutputConfigTypes.FILE_OUTPUT.name(), new FileOutputConfig().id()); } @Test public void testValidation() { FileOutputConfig c = this.createValidConfiguration(); assertTrue(this.validator.validate(c).isEmpty()); this._testValidateFile(); } private void _testValidateFile() { FileOutputConfig c = new FileOutputConfig(); Set<ConstraintViolation> violations = this.validator.validate(c); assertTrue(violations.size() == 1); assertEquals(NotNull.class, violations.iterator().next().getValidator()); } private FileOutputConfig createValidConfiguration() { return new FileOutputConfig().withFile("/path/to/file"); } }
aureliano/da-mihi-logs
evt-bridge-output/file-output/src/test/java/com/github/aureliano/evtbridge/output/file/FileOutputConfigTest.java
Java
mit
2,450
// THIS CODE IS MACHINE-GENERATED, DO NOT EDIT! package fallk.jfunktion; /** * Represents a predicate (boolean-valued function) of a {@code float}-valued and a generic argument. * This is the primitive type specialization of * {@link java.util.function.BiPredicate} for {@code float}/{@code char}. * * @see java.util.function.BiPredicate */ @FunctionalInterface public interface FloatObjectPredicate<E> { /** * Evaluates this predicate on the given arguments. * * @param v1 the {@code float} argument * @param v2 the generic argument * @return {@code true} if the input arguments match the predicate, * otherwise {@code false} */ boolean apply(float v1, E v2); }
fallk/JFunktion
src/main/java/fallk/jfunktion/FloatObjectPredicate.java
Java
mit
715