code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package node import ( "bytes" "golang.org/x/net/html" ) // Attr returns attribute of node by given key if any. func Attr(n *html.Node, key string) (string, bool) { for _, a := range n.Attr { if a.Key == key { return a.Val, true } } return "", false } // Children returns slice of nodes where each node is a child of given node and // filter function returns true for corresponding child node. func Children(n *html.Node, filter func(*html.Node) bool) []*html.Node { nodes := make([]*html.Node, 0) if filter == nil { filter = func(*html.Node) bool { return true } } for c := n.FirstChild; c != nil; c = c.NextSibling { if !filter(c) { continue } nodes = append(nodes, c) } return nodes } // JoinData returns attribute of node by given key if any. func JoinData(n ...*html.Node) string { var buf bytes.Buffer for _, m := range n { buf.WriteString(m.Data) } return buf.String() }
krasoffski/gomill
node/utils.go
GO
mit
920
using System; using NetOffice; using NetOffice.Attributes; namespace NetOffice.PublisherApi.Enums { /// <summary> /// SupportByVersion Publisher 14, 15, 16 /// </summary> [SupportByVersion("Publisher", 14,15,16)] [EntityType(EntityType.IsEnum)] public enum PbMailMergeDestination { /// <summary> /// SupportByVersion Publisher 14, 15, 16 /// </summary> /// <remarks>1</remarks> [SupportByVersion("Publisher", 14,15,16)] pbSendToPrinter = 1, /// <summary> /// SupportByVersion Publisher 14, 15, 16 /// </summary> /// <remarks>2</remarks> [SupportByVersion("Publisher", 14,15,16)] pbMergeToNewPublication = 2, /// <summary> /// SupportByVersion Publisher 14, 15, 16 /// </summary> /// <remarks>3</remarks> [SupportByVersion("Publisher", 14,15,16)] pbMergeToExistingPublication = 3, /// <summary> /// SupportByVersion Publisher 14, 15, 16 /// </summary> /// <remarks>4</remarks> [SupportByVersion("Publisher", 14,15,16)] pbSendEmail = 4 } }
NetOfficeFw/NetOffice
Source/Publisher/Enums/PbMailMergeDestination.cs
C#
mit
1,026
import * as angular from 'angular'; import { ForgotPasswordComponent } from './ForgotPasswordComponent'; import { ForgotPasswordController } from './ForgotPasswordController'; export default angular .module('users.forgotPassword', []) .component(ForgotPasswordComponent.$name, new ForgotPasswordComponent()) .controller(ForgotPasswordController.$name, ForgotPasswordController) .name;
brian-rowe/krossr
public/modules/users/forgotPassword/ForgotPasswordModule.ts
TypeScript
mit
401
# user.py is the autostart code for a ulnoiot node. # Configure your devices, sensors and local interaction here. # Always start with this to make everything from ulnoiot available. # Therefore, do not delete the following line. from ulnoiot import * # The following is just example code, adjust to your needs accordingly. # wifi and mqtt connect are done automatically, we assume for this example # the following configuration. # mqtt("ulnoiotgw", "myroom/test1") ## Use some shields # The onboard-led is always available. # With this configuration it will report under myroom/test1/blue # and can be set via sending off or on to myroom/test1/blue/test. from ulnoiot.shield.onboardled import blue blue.high() # make sure it's off (it's reversed) ## Add some other devices # Add a button with a slightly higher debounce rate, which will report # in the topic myroom/test1/button1. button("b1", d6, pullup=False, threshold=2) # Count rising signals on d2=Pin(4) and # report number counted at myroom/test1/shock1. # trigger("shock1",Pin(4)) ## Start to transmit every 10 seconds (or when status changed). # Don't forget the run-comamnd at the end. run(5)
ulno/micropython-extra-ulno
examples/integriot_test/testnode1/files/autostart.py
Python
mit
1,163
#!/usr/bin/env node // Fires up a console with Valid loaded. // Allows you to quickly play with Valid on the console. Valid = require('./lib/valid'); require('repl').start();
bronson/valid
console.js
JavaScript
mit
177
<?php /* * This file is part of ThraceMediaBundle * * (c) Nikolay Georgiev <symfonist@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Thrace\MediaBundle\Exception; interface ExceptionInterface {}
thrace-project/media-bundle
Exception/ExceptionInterface.php
PHP
mit
291
class CategoriesController < ApplicationController def index @categories = Category.all end def show @category = Category.find_by_id(params[:id]) end end
nyc-squirrels-2015/craigslist_mw_kb
app/controllers/categories_controller.rb
Ruby
mit
172
# Copyright (c) 2015 Uber Technologies, Inc. # # 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. from __future__ import absolute_import from . import common from .. import rw from ..glossary import DEFAULT_TIMEOUT from .base import BaseMessage class CancelMessage(BaseMessage): __slots__ = BaseMessage.__slots__ + ( 'ttl', 'tracing', 'why', ) def __init__(self, ttl=DEFAULT_TIMEOUT, tracing=None, why=None, id=0): super(CancelMessage, self).__init__(id) self.ttl = ttl self.tracing = tracing or common.Tracing(0, 0, 0, 0) self.why = why or '' cancel_rw = rw.instance( CancelMessage, ('ttl', rw.number(4)), # ttl:4 ('tracing', common.tracing_rw), # tracing:24 ('why', rw.len_prefixed_string(rw.number(2))), # why:2 )
Willyham/tchannel-python
tchannel/messages/cancel.py
Python
mit
1,854
package com.adben.testdatabuilder.core.analyzers.generators.generator; import static com.adben.testdatabuilder.core.helper.ReflectionHelper.getClz; import static java.lang.invoke.MethodHandles.lookup; import static org.slf4j.LoggerFactory.getLogger; import com.google.common.base.MoreObjects; import java.lang.reflect.Type; import java.util.Objects; import org.slf4j.Logger; /** * {@link com.adben.testdatabuilder.core.analyzers.generators.Generator Generator} for {@link * Boolean}. * * <p> * * {@link BooleanGenerator#currValue} starts at false, then flip flops from there. */ public class BooleanGenerator extends AbstractGenerator<Boolean> { private static final Logger LOGGER = getLogger(lookup().lookupClass()); private boolean currValue = false; /** * Default constructor. */ public BooleanGenerator() { super(); LOGGER.trace("Default constructor"); } /** * Applicable type is {@link Boolean} or boolean. * * <p> * * {@inheritDoc} */ @Override protected boolean isApplicable(final Type type) { return Boolean.class.isAssignableFrom(getClz(type)) || Objects.equals(getClz(type), boolean.class); } /** * Get the next value for this generator, and flip the boolean value. * * <p> * * {@inheritDoc} */ @Override protected Boolean getNextValue(final Type type) { try { return this.currValue; } finally { this.currValue = !this.currValue; } } @Override public String toString() { LOGGER.trace("toString"); return MoreObjects.toStringHelper(this) .add("currValue", this.currValue) .toString(); } }
adben002/test-data-builder
core/src/main/java/com/adben/testdatabuilder/core/analyzers/generators/generator/BooleanGenerator.java
Java
mit
1,657
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M4 18h11c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1s.45 1 1 1zm0-5h8c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1s.45 1 1 1zM3 7c0 .55.45 1 1 1h11c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1zm17.3 7.88L17.42 12l2.88-2.88c.39-.39.39-1.02 0-1.41a.9959.9959 0 00-1.41 0L15.3 11.3c-.39.39-.39 1.02 0 1.41l3.59 3.59c.39.39 1.02.39 1.41 0 .38-.39.39-1.03 0-1.42z" /> , 'MenuOpenRounded');
lgollut/material-ui
packages/material-ui-icons/src/MenuOpenRounded.js
JavaScript
mit
514
'use strict'; describe('Service: awesomeThings', function() { // load the service's module beforeEach(module('initApp')); // instantiate service var awesomeThings; beforeEach(inject(function(_awesomeThings_) { awesomeThings = _awesomeThings_; })); it('should return all the awesomeThings at the static list', function() { expect(awesomeThings.getAll().length).toBe(4); }); it('should return an specific awesome thing', function() { // We can test the object itself here. Not doing for simplicity expect(awesomeThings.get('2').name).toBe('AngularJS'); }); });
ivosantiago/angular-sample
test/spec/services/awesomethings.js
JavaScript
mit
602
<?php /** * Created by PhpStorm. * User: Niels * Date: 18/10/2014 * Time: 18:00 */ namespace Repositories; use Utilities\Utilities; /** * The repository contains all methods for interacting with the database for the TalkTag model * * Class TalkTagRepository * @package Repositories */ class TalkTagRepository { /** * @return array Returns all talktags */ public static function getTalkTags() { $sql_query = "SELECT * FROM talk_tag"; $con=Utilities::getConnection(); $stmt = $con->query($sql_query); return $stmt->fetchAll(\PDO::FETCH_ASSOC); } /** * @param $talkId int The talkid of the TalkTag * @param $tagId int The tagid of the TalkTag * @return bool Returns true if successful */ public static function insertTalkTag($talkId, $tagId) { try { $sql_query = "INSERT INTO talk_tag (talk_id, tag_id) VALUES (:talk_id,:tag_id);"; $con = Utilities::getConnection(); $stmt = $con->prepare($sql_query); return $stmt->execute(array(':talk_id' => $talkId, ':tag_id' => $tagId)); }catch (\Exception $ex){ return false; } } }
SNiels/Multi-Mania-app
backend/Repositories/TalkTagRepository.php
PHP
mit
1,214
module TestEngine class FaceToFace < Duration end end
AdamGorbert/test_engine
app/models/test_engine/face_to_face.rb
Ruby
mit
58
<?php /* * Created on Aug 30, 2007 * * To change the template for this generated file go to * Window - Preferences - PHPeclipse - PHP - Code Templates */ // Page requirements define('LOGIN_REQUIRED', true); define('PAGE_ACCESS_LEVEL', 2); define('PAGE_TYPE', 'ADMIN'); // Set for every page require ('engine/common.php'); if (this_season_has_teams()) { $playerid = 0; $playerName = ""; $jersey1 = 0; $jersey2 = 0; $jersey3 = 0; $manual = 0; $location = 'players'; if ($_GET || $_POST) { if (isset($_GET['playerid']) && $_GET['playerid'] > 0) { $playerid = $_GET['playerid']; } else if (isset($_POST['playerid']) && $_POST['playerid'] > 0) { $playerid = $_POST['playerid']; } else { header("Location: $location.php"); } if (isset($_GET['manual']) && $_GET['manual'] > 0) { $manual = $_GET['manual']; } else if (isset($_POST['manual']) && $_POST['manual'] > 0) { $manual = $_POST['manual']; } if (isset($_GET['location'])) { $location = $_GET['location']; } else if (isset($_POST['location'])) { $location = $_POST['location']; } //Set players jersey choices if ($manual > 0) { set_manual_player_info(); } else { set_player_info(); } $smarty->assign('playerid', $playerid); $smarty->assign('playerName', $playerName); $smarty->assign('jersey1', $jersey1); $smarty->assign('jersey2', $jersey2); $smarty->assign('jersey3', $jersey3); $smarty->assign('location', $location); setup_jersey_warning_info(); setup_team_already_on(); setup_team_select(); setup_jersey_select(); } if ((isset($_POST['action'])) && ($_POST['action'] == "Add Player to Roster")) { process_assignplayerteam_form(); header("Location: $location.php"); } } else { $smarty->assign('no_teams_this_season', true); $smarty->assign('season', get_season_name($SEASON)); } // If teams exist for this season $page_name = 'Assign ' . $playerName . ' to Team'; $smarty->assign('page_name', $page_name); // Build the page require ('global_begin.php'); $smarty->display('admin/assignplayerteam.tpl'); require ('global_end.php'); /* * ******************************************************************************** * ******************************************************************************** * **************************L O C A L F U N C T I O N S************************** * ******************************************************************************** * ******************************************************************************** */ /* * See if this season has teams yet. */ function this_season_has_teams() { global $SEASON; global $Link; $teamsThisSeasonExistSQL = 'SELECT count(*) as totalTeamsThisSeason FROM ' . TEAMSOFSEASONS . ' WHERE seasonID=' . $SEASON; $teamsThisSeasonExistResult = mysql_query($teamsThisSeasonExistSQL, $Link) or die("sp_clubs (Line " . __LINE__ . "): " . mysql_errno() . ": " . mysql_error()); $totalTeamsThisSeason = 0; if ($teamsThisSeasonExistResult) { if (mysql_num_rows($teamsThisSeasonExistResult) > 0) { $teamsThisSeasonCount = mysql_fetch_assoc($teamsThisSeasonExistResult); $totalTeamsThisSeason = $teamsThisSeasonCount['totalTeamsThisSeason']; } } if ($totalTeamsThisSeason > 0) { return true; } else { return false; } } /* * Manual player addition. Not based on registration. */ function set_manual_player_info() { global $SEASON; global $playerid; global $playerName; global $Link; $columns = 'playerFName,playerLName'; $select = 'SELECT ' . $columns . ' FROM ' . PLAYER . ' WHERE ' . PLAYER . '.playerID=' . $playerid . ' AND ' . PLAYER . '.seasonId=' . $SEASON; $result = mysql_query($select, $Link) or die("sp_clubs (Line " . __LINE__ . "): " . mysql_errno() . ": " . mysql_error()); if ($result && mysql_num_rows($result) > 0) { $player = mysql_fetch_assoc($result); $playerName = $player['playerFName'] . ' ' . $player['playerLName']; } } /* * Set this players jersey choices */ function set_player_info() { global $SEASON; global $playerid; global $playerName; global $jersey1; global $jersey2; global $jersey3; global $Link; $jerseySelectColumns = 'playerFName,playerLName,jerseyNumberOne,jerseyNumberTwo,jerseyNumberThree'; $jerseySelect = 'SELECT ' . $jerseySelectColumns . ' FROM ' . PLAYER . ' JOIN ' . REGISTRATION . ' ON ' . PLAYER . '.playerId = ' . REGISTRATION . '.playerId WHERE ' . PLAYER . '.playerId=' . $playerid . ' AND ' . REGISTRATION . '.seasonId=' . $SEASON; $jerseyResult = mysql_query($jerseySelect, $Link) or die("sp_clubs (Line " . __LINE__ . "): " . mysql_errno() . ": " . mysql_error()); if ($jerseyResult && mysql_num_rows($jerseyResult) > 0) { $player = mysql_fetch_assoc($jerseyResult); $playerName = $player['playerFName'] . ' ' . $player['playerLName']; $jersey1 = $player['jerseyNumberOne']; $jersey2 = $player['jerseyNumberTwo']; $jersey3 = $player['jerseyNumberThree']; } } /* * */ function setup_jersey_warning_info() { global $smarty; global $SEASON; global $jersey1; global $jersey2; global $jersey3; global $Link; $jerseyWarningSelectColumns = ROSTERSOFTEAMSOFSEASONS . '.teamID,teamName,' . ROSTERSOFTEAMSOFSEASONS . '.playerID,playerFName,playerLName,' . ROSTERSOFTEAMSOFSEASONS . '.jerseyNumber'; $jerseyWarningSelect = 'SELECT ' . $jerseyWarningSelectColumns . ' FROM ' . ROSTERSOFTEAMSOFSEASONS . ' JOIN ' . TEAMS . ' ON ' . TEAMS . '.teamID = ' . ROSTERSOFTEAMSOFSEASONS . '.teamID JOIN ' . PLAYER . ' ON ' . PLAYER . '.playerID = ' . ROSTERSOFTEAMSOFSEASONS . '.playerID WHERE (' . ROSTERSOFTEAMSOFSEASONS . '.jerseyNumber=' . $jersey1 . ' OR ' . ROSTERSOFTEAMSOFSEASONS . '.jerseyNumber=' . $jersey2 . ' OR ' . ROSTERSOFTEAMSOFSEASONS . '.jerseyNumber=' . $jersey3 . ') AND ' . ROSTERSOFTEAMSOFSEASONS . '.seasonID=' . $SEASON; $jerseyWarningResult = mysql_query($jerseyWarningSelect, $Link) or die("sp_clubs (Line " . __LINE__ . "): " . mysql_errno() . ": " . mysql_error()); if ($jerseyWarningResult && mysql_num_rows($jerseyWarningResult) > 0) { $jwConfictsCount = 0; $smarty->assign('jwConflictNum', array()); $smarty->assign('jwTeamName', array()); $smarty->assign('jwPlayerName', array()); $smarty->assign('jwJerseyNumber', array()); while ($jw = mysql_fetch_array($jerseyWarningResult, MYSQL_ASSOC)) { $jwConfictsCount++; $jwTeamName = $jw['teamName']; $jwPlayerName = $jw['playerFName'] . ' ' . $jw['playerLName']; $jwJerseyNumber = $jw['jerseyNumber']; $smarty->append('jwConflictNum', $jwConfictsCount); $smarty->append('jwTeamName', $jwTeamName); $smarty->append('jwPlayerName', $jwPlayerName); $smarty->append('jwJerseyNumber', $jwJerseyNumber); } $smarty->assign('jwConfictsCount', $jwConfictsCount); } } /* * Setup team player is already on - Since people can now be on more than one team. */ function setup_team_already_on() { global $smarty; global $SEASON; global $playerid; global $Link; $teamAlreadyOnSelect = 'SELECT teamName FROM ' . ROSTERSOFTEAMSOFSEASONS . ' JOIN ' . TEAMS . ' ON ' . TEAMS . '.teamID = ' . ROSTERSOFTEAMSOFSEASONS . '.teamID WHERE playerID=' . $playerid . ' AND seasonId=' . $SEASON; $teamsAlreadyOnResult = mysql_query($teamAlreadyOnSelect, $Link) or die("sp_clubs (Line " . __LINE__ . "): " . mysql_errno() . ": " . mysql_error()); if ($teamsAlreadyOnResult && mysql_num_rows($teamsAlreadyOnResult) > 0) { $countAlreadyOnTeams = 0; $smarty->assign('teamAlreadyOnName', array()); while ($team = mysql_fetch_array($teamsAlreadyOnResult, MYSQL_ASSOC)) { $countAlreadyOnTeams++; $aoTeamName = $team['teamName']; $smarty->append('teamAlreadyOnName', $aoTeamName); } $smarty->assign('countAlreadyOnTeams', $countAlreadyOnTeams); } } /* * Setup teams that can be chosen to put this playerId onto. */ function setup_team_select() { global $smarty; global $SEASON; global $playerid; global $Link; $teamCandidatesSelect = 'SELECT teamID, teamName FROM ' . TEAMS . ' WHERE teamID NOT IN (SELECT teamID FROM ' . ROSTERSOFTEAMSOFSEASONS . ' WHERE playerID=' . $playerid . ' AND seasonId=' . $SEASON . ')'; $teamCandidatesSelect.= ' AND teamID In (SELECT teamID FROM ' . TEAMSOFSEASONS . ' WHERE seasonID=' . $SEASON . ')'; $teamsCandidatesResult = mysql_query($teamCandidatesSelect, $Link) or die("sp_clubs (Line " . __LINE__ . "): " . mysql_errno() . ": " . mysql_error()); if ($teamsCandidatesResult && mysql_num_rows($teamsCandidatesResult) > 0) { $countCandidateTeams = 0; $smarty->assign('teamCandidateID', array()); $smarty->assign('teamCandidateName', array()); while ($team = mysql_fetch_array($teamsCandidatesResult, MYSQL_ASSOC)) { $countCandidateTeams++; $teamId = $team['teamID']; $teamName = $team['teamName']; $smarty->append('teamCandidateID', $teamId); $smarty->append('teamCandidateName', $teamName); } $smarty->assign('countCandidateTeams', $countCandidateTeams); } } /* * Setup jersey number select */ function setup_jersey_select() { global $smarty; global $jersey1; $jerseySelect = '<select name="jerseyNumber">'; for ($i = 0;$i < 100;$i++) { if ($i != $jersey1) { $jerseySelect.= '<option value="' . $i . '">' . $i . '</option>'; } else { $jerseySelect.= '<option value="' . $i . '" selected="selected">' . $i . '</option>'; } } $jerseySelect.= '</select>'; $smarty->assign('jerseySelect', $jerseySelect); } /* * Assign player to a team */ function process_assignplayerteam_form() { global $SEASON; global $playerid; global $Link; $teamId = $_POST['candidateTeams']; $jerseyNumber = $_POST['jerseyNumber']; $assignPlayerInsert = 'INSERT INTO ' . ROSTERSOFTEAMSOFSEASONS . ' (`seasonID`,`teamID`,`playerID`,`jerseyNumber`) VALUES (' . $SEASON . ',' . $teamId . ',' . $playerid . ',' . $jerseyNumber . ')'; mysql_query($assignPlayerInsert, $Link) or die("sp_clubs (Line " . __LINE__ . "): " . mysql_errno() . ": " . mysql_error()); } ?>
klangrud/tcshl
assignplayerteam.php
PHP
mit
10,735
# coding: utf-8 import pygame import os from color import * from pygame.locals import * class Score(pygame.sprite.Sprite): def __init__(self, score, player, width, height): super(pygame.sprite.Sprite).__init__(Score) self.score = int(score) self.color = None self.player = player self.bossHeight = height self.bossWidth = width self.size = 70 self.update() def update(self): self.score = int(self.score) self.whatColor() self.score = str(self.score) scoreFont = pygame.font.Font('./fonts/Dearest.ttf', self.size) # We need to convert it to do the condition in 'self.wharColor' # and 'scoreFont.rend' only takes 'str' as argument self.surface = scoreFont.render(self.score, True, self.color) self.rect = self.surface.get_rect() if self.player == 1: self.rect.center = (55, self.bossHeight - 50) elif self.player == -1: self.rect.center = (self.bossWidth - 55, self.bossHeight - 50) def whatColor(self): self.size = 80 if self.score < 6: self.color = white elif self.score < 8: self.color = aqua elif self.score < 10: self.color = blueGreen else: self.color = lime self.size = 100 def updateScore(self, score): self.score = score def __repr__(self): return "<Score de ", str(self.player), "= ", str(self.score)
Ilphrin/TuxleTriad
Score.py
Python
mit
1,523
'use strict'; var matrix = require( 'dstructs-matrix' ), ekurtosis = require( './../lib' ); var k, mat, out, tmp, i; // ---- // Plain arrays... k = new Array( 10 ); for ( i = 0; i < k.length; i++ ) { k[ i ] = i; } out = ekurtosis( k ); console.log( 'Arrays: %s\n', out ); // ---- // Object arrays (accessors)... function getValue( d ) { return d.x; } for ( i = 0; i < k.length; i++ ) { k[ i ] = { 'x': k[ i ] }; } out = ekurtosis( k, { 'accessor': getValue }); console.log( 'Accessors: %s\n', out ); // ---- // Deep set arrays... for ( i = 0; i < k.length; i++ ) { k[ i ] = { 'x': [ i, k[ i ].x ] }; } out = ekurtosis( k, { 'path': 'x/1', 'sep': '/' }); console.log( 'Deepset:'); console.dir( out ); console.log( '\n' ); // ---- // Typed arrays... k = new Float64Array( 10 ); for ( i = 0; i < k.length; i++ ) { k[ i ] = i; } tmp = ekurtosis( k ); out = ''; for ( i = 0; i < k.length; i++ ) { out += tmp[ i ]; if ( i < k.length-1 ) { out += ','; } } console.log( 'Typed arrays: %s\n', out ); // ---- // Matrices... mat = matrix( k, [5,2], 'float64' ); out = ekurtosis( mat ); console.log( 'Matrix: %s\n', out.toString() ); // ---- // Matrices (custom output data type)... out = ekurtosis( mat, { 'dtype': 'uint8' }); console.log( 'Matrix (%s): %s\n', out.dtype, out.toString() );
distributions-io/chisquare-ekurtosis
examples/index.js
JavaScript
mit
1,317
/* public/core.js */ var angTodo = angular.module('angTodo', []); function mainController($scope, $http) { $scope.formData = {}; /* when landing on the page, get all todos and show them */ $http.get('/api/todos') .success(function(data) { $scope.todos = data; console.log(data); }) .error(function(data) { console.log('Error: ' + data); }); /* when submitting the add form, send the text to the node API */ $scope.createTodo = function() { $http.post('/api/todos', $scope.formData) .success(function(data) { $scope.formData = {}; // clear the form so another todo can be entered $scope.todos = data; console.log(data); }) .error(function(data) { console.log('Error: ' + data); }); }; /* delete a todo after checking it */ $scope.deleteTodo = function(id) { $http.delete('/api/todos/' + id) .success(function(data) { $scope.todos = data; console.log(data); }) .error(function(data) { console.log('Error: ' + data); }); }; } /* function mainController */
rsperberg/angular-to-do
public/js/core.js
JavaScript
mit
1,300
package cmdji type Compound struct { KanjiCompound string KanaCompound string CompoundMeanings []string } type kanjiStruct struct { Kanji string `json:"kanji"` Meanings []string `json:"meanings"` Onyomis []string `json:"onyomis"` Kunyomis []string `json:"kunyomis` Nanoris []string `json:"nanoris"` Joyo bool `json:"joyo"` Jlpt int `json:"jlpt"` Newspaper_rank int `json:"newspaper_rank"` On_compounds [][]interface{} `json:"on_compounds"` Kun_compounds [][]interface{} `json:"kun_compounds"` Max_newspaper_rank int `json:"max_newspaper_rank"` Published_at string `json:"published_at"` Image []string `json:"image"` Source_url string `json:"source_url"` } type KanjiADay struct { Kanji kanjiStruct `json:"kanji"` Home_url string `json:"home_url"` }
ProfOak/cmdji
go-bindings/types.go
GO
mit
1,020
from __future__ import unicode_literals from django.db import models from django.utils.timezone import now, timedelta Q = models.Q class LogisticJob(models.Model): LOCK_FOR = ( (60*15, '15 minutes'), (60*30, '30 minutes'), (60*45, '45 minutes'), (60*60, '1 hour'), (60*60*3, '3 hours'), (60*60*6, '6 hours'), (60*60*9, '9 hours'), (60*60*12, '12 hours'), (60*60*18, '18 hours'), (60*60*24, '24 hours'), ) RESOURCE = ( ('wood', 'Wood'), ('stone', 'Stone'), ('food', 'Food'), # ('cole', 'Cole'), ) SPEED = ( ('-1', 'Keine Pferde'), ('1001', 'Gold Pferde (test)'), ('1004', 'Rubi Pferde 1 (test)'), ('1007', 'Rubi Pferde 2 (test)'), ) player = models.ForeignKey("gge_proxy_manager.Player", related_name='logistic_jobs') castle = models.ForeignKey("gge_proxy_manager.Castle", related_name='outgoing_logistic_jobs') receiver = models.ForeignKey("gge_proxy_manager.Castle", related_name='incoming_logistic_jobs') speed = models.CharField(max_length=5, choices=SPEED) is_active = models.BooleanField(default=True) resource = models.CharField(max_length=6, choices=RESOURCE) gold_limit = models.PositiveIntegerField(null=True, blank=True, default=None) resource_limit = models.PositiveIntegerField() lock_for = models.PositiveIntegerField(choices=LOCK_FOR, default=60*45) locked_till = models.DateTimeField(default=now, db_index=True) class Meta: app_label = 'gge_proxy_manager' def delay(self): self.locked_till = now() + timedelta(seconds=self.lock_for) self.save() def last_succeed(self): from .log import LogisticLog log = LogisticLog.objects.filter(castle=self.castle, receiver=self.receiver, resource=self.resource).order_by('-sent').first() if log: return log.sent return None class ProductionJob(models.Model): player = models.ForeignKey("gge_proxy_manager.Player", related_name='production_jobs') castle = models.ForeignKey("gge_proxy_manager.Castle", related_name='production_jobs') unit = models.ForeignKey("gge_proxy_manager.Unit") valid_until = models.PositiveIntegerField(null=True, blank=True, default=None, help_text='Bis zu welcher Menge ist der Auftrag gueltig') is_active = models.BooleanField(default=True) gold_limit = models.PositiveIntegerField(null=True, blank=True, default=None) food_balance_limit = models.IntegerField(null=True, blank=True, default=None) wood_limit = models.PositiveIntegerField(null=True, blank=True, default=None) stone_limit = models.PositiveIntegerField(null=True, blank=True, default=None) burst_mode = models.BooleanField(default=False, help_text='Ignoriert Nahrungsbilanz') locked_till = models.DateTimeField(default=now, db_index=True) last_fault_reason = models.CharField(null=True, default=None, max_length=128) last_fault_date = models.DateTimeField(default=None, null=True) class Meta: app_label = 'gge_proxy_manager' def last_succeed(self): from .log import ProductionLog log = ProductionLog.objects.filter(castle=self.castle, unit=self.unit).order_by('-produced').first() if log: return log.produced return None
mrcrgl/gge-storage
gge_proxy_manager/models/jobs.py
Python
mit
3,505
define([], function() { return function($translateProvider) { $translateProvider.translations('en', { WELCOME_TO_PIO: 'Welcome to PIO', SIGN_IN: 'Sign in', SIGN_UP: 'Sign up', SIGN_OUT: 'Sign out', FORGOT_PASSWORD: 'Forgot password?', DO_NOT_HAVE_AN_ACCOUNT: 'Do not have an account?', CREATE_AN_ACCOUNT: 'Create an account', POLLS: 'Polls', ADMINISTRATION: 'Administration', TITLE: 'Title', USERS: 'Users', CREATE: 'Create', DASHBOARD: 'Dashboard', DETAILS: 'Details', DETAIL: 'Detail', CREATE_POLL: 'Create poll', CREATE_USER: 'Create user', POLL_DETAILS: 'Poll details', USER_DETAILS: 'User details', TAGS: 'Tags', SUMMARY: 'Summary', STATUS: 'Status', NAME: 'Name', AVATAR: 'Avatar', POLLINGS: 'Pollings', NOTES: 'Notes', EMAIL: 'Email', DATE: 'Date', SAVE: 'Save', CANCEL: 'Cancel' }); $translateProvider.translations('es', { WELCOME_TO_PIO: 'Bienvenido a PIO', SIGN_IN: 'Acceder', SIGN_UP: 'Registro', SIGN_OUT: 'Salir', FORGOT_PASSWORD: '¿Olvidó la contraseña?', DO_NOT_HAVE_AN_ACCOUNT: '¿No tiene una cuenta?', CREATE_AN_ACCOUNT: 'Crear un acuenta', POLLS: 'Encuestas', ADMINISTRATION: 'Administración', TITLE: 'Título', USERS: 'Usuarios', CREATE: 'Crear', DASHBOARD: 'Panel', DETAILS: 'Detalles', DETAIL: 'Detalle', CREATE_POLL: 'Crear encuesta', CREATE_USER: 'Crear usuario', POLL_DETAILS: 'Detalles de encuesta', USER_DETAILS: 'Detalles de usuario', TAGS: 'Etiquetas', SUMMARY: 'Resumen', STATUS: 'Estado', NAME: 'Nombre', AVATAR: 'Avatar', POLLINGS: 'Votaciones', NOTES: 'Notas', EMAIL: 'Correo', DATE: 'Fecha', SAVE: 'Guardar', CANCEL: 'Cancelar' }); $translateProvider.useSanitizeValueStrategy('escapeParameters'); $translateProvider.preferredLanguage('es'); }; });
rubeniskov/node-pio
app/src/i18n.js
JavaScript
mit
2,466
<?php /* :informacion:index.html.twig */ class __TwigTemplate_3fe207d07cb2a7021f8181185385f866207e1e1b6e8e118c7b08937099592d8c extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 $this->parent = $this->loadTemplate("base.html.twig", ":informacion:index.html.twig", 1); $this->blocks = array( 'stylesheets_extra' => array($this, 'block_stylesheets_extra'), 'body' => array($this, 'block_body'), 'javascripts_extra' => array($this, 'block_javascripts_extra'), ); } protected function doGetParent(array $context) { return "base.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $__internal_680719deb7b4b8273131714fbcec70196a09115941cbaa49b48bf1542be78804 = $this->env->getExtension("native_profiler"); $__internal_680719deb7b4b8273131714fbcec70196a09115941cbaa49b48bf1542be78804->enter($__internal_680719deb7b4b8273131714fbcec70196a09115941cbaa49b48bf1542be78804_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", ":informacion:index.html.twig")); $this->parent->display($context, array_merge($this->blocks, $blocks)); $__internal_680719deb7b4b8273131714fbcec70196a09115941cbaa49b48bf1542be78804->leave($__internal_680719deb7b4b8273131714fbcec70196a09115941cbaa49b48bf1542be78804_prof); } // line 2 public function block_stylesheets_extra($context, array $blocks = array()) { $__internal_61d99f116531dc40075507813235c209b44752ea80cdd7cb2cd9d8861a67adae = $this->env->getExtension("native_profiler"); $__internal_61d99f116531dc40075507813235c209b44752ea80cdd7cb2cd9d8861a67adae->enter($__internal_61d99f116531dc40075507813235c209b44752ea80cdd7cb2cd9d8861a67adae_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "stylesheets_extra")); // line 3 echo " "; $__internal_61d99f116531dc40075507813235c209b44752ea80cdd7cb2cd9d8861a67adae->leave($__internal_61d99f116531dc40075507813235c209b44752ea80cdd7cb2cd9d8861a67adae_prof); } // line 7 public function block_body($context, array $blocks = array()) { $__internal_05f88ce797520f6d572ef3db3c35f16034597aa098181ffb6b04c774ae1bc814 = $this->env->getExtension("native_profiler"); $__internal_05f88ce797520f6d572ef3db3c35f16034597aa098181ffb6b04c774ae1bc814->enter($__internal_05f88ce797520f6d572ef3db3c35f16034597aa098181ffb6b04c774ae1bc814_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "body")); // line 8 echo " <h1>Información</h1> <!-- BEGIN CONTAINER --> <div class=\"page-container\"> <!-- BEGIN CONTENT --> <div class=\"row\"> <div class=\"col-xs-12 col-sm-12 col-md-12 col-lg-12 \"> <a class=\"btn btn-success\" href=\""; // line 14 echo $this->env->getExtension('routing')->getPath("informacion_new"); echo "\" ><span>Agregar</span></a> <br><br> <!-- BEGIN EXAMPLE TABLE PORTLET--> <div class=\"portlet light bordered\"> <div class=\"portlet-title\"> <div class=\"caption font-green\"> <i class=\"icon-settings font-green\"></i> <span class=\"caption-subject bold uppercase\"></span> </div> <div class=\"tools\"> </div> </div> <div class=\"portlet-body\"> <table class=\"table table-striped table-bordered table-hover dt-responsive\" width=\"100%\" id=\"sample_2\"> <thead> <tr> <th class=\"all\" width=\"10%\">Detalle</th> <th class=\"all\" width=\"10%\">Editar</th> <th class=\"all\">Descripcion</th> <th class=\"all\">Fecha</th> </tr> </thead> <tbody> "; // line 37 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable((isset($context["informacions"]) ? $context["informacions"] : $this->getContext($context, "informacions"))); foreach ($context['_seq'] as $context["_key"] => $context["Informacion"]) { // line 38 echo " <tr> <td> <center> <a href=\""; // line 41 echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("informacion_show", array("id" => $this->getAttribute($context["Informacion"], "id", array()))), "html", null, true); echo "\"> <i class=\"glyphicon glyphicon-search\"></i> </a> </center> </td> <td> <center> <a href=\""; // line 48 echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("informacion_edit", array("id" => $this->getAttribute($context["Informacion"], "id", array()))), "html", null, true); echo "\"> <i class=\"glyphicon glyphicon-pencil\"></i> </a> </center> </td> <td>"; // line 54 echo $this->getAttribute($context["Informacion"], "descripcion", array()); echo "</td> <td>"; // line 56 echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute($context["Informacion"], "fechahora", array()), "d/m/Y"), "html", null, true); echo "</td> </tr> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['Informacion'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 60 echo " </tbody> </table> </div> </div> <!-- END EXAMPLE TABLE PORTLET--> </div> </div> <!-- END CONTENT BODY --> </div> <!-- END CONTAINER --> "; $__internal_05f88ce797520f6d572ef3db3c35f16034597aa098181ffb6b04c774ae1bc814->leave($__internal_05f88ce797520f6d572ef3db3c35f16034597aa098181ffb6b04c774ae1bc814_prof); } // line 77 public function block_javascripts_extra($context, array $blocks = array()) { $__internal_3fcefd8ca3b85ea42d90154347a109ffe2c9ace7fa7a1773265a41a63c892a2a = $this->env->getExtension("native_profiler"); $__internal_3fcefd8ca3b85ea42d90154347a109ffe2c9ace7fa7a1773265a41a63c892a2a->enter($__internal_3fcefd8ca3b85ea42d90154347a109ffe2c9ace7fa7a1773265a41a63c892a2a_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "javascripts_extra")); // line 78 echo " <script> "; $__internal_3fcefd8ca3b85ea42d90154347a109ffe2c9ace7fa7a1773265a41a63c892a2a->leave($__internal_3fcefd8ca3b85ea42d90154347a109ffe2c9ace7fa7a1773265a41a63c892a2a_prof); } public function getTemplateName() { return ":informacion:index.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 161 => 78, 155 => 77, 133 => 60, 123 => 56, 118 => 54, 109 => 48, 99 => 41, 94 => 38, 90 => 37, 64 => 14, 56 => 8, 50 => 7, 42 => 3, 36 => 2, 11 => 1,); } } /* {% extends 'base.html.twig' %}*/ /* {% block stylesheets_extra %}*/ /* */ /* {% endblock %}*/ /* */ /* */ /* {% block body %}*/ /* <h1>Información</h1>*/ /* <!-- BEGIN CONTAINER -->*/ /* <div class="page-container">*/ /* <!-- BEGIN CONTENT -->*/ /* <div class="row">*/ /* <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 ">*/ /* <a class="btn btn-success" href="{{ path('informacion_new') }}" ><span>Agregar</span></a>*/ /* <br><br> */ /* <!-- BEGIN EXAMPLE TABLE PORTLET-->*/ /* <div class="portlet light bordered">*/ /* <div class="portlet-title">*/ /* <div class="caption font-green">*/ /* <i class="icon-settings font-green"></i>*/ /* <span class="caption-subject bold uppercase"></span>*/ /* </div>*/ /* <div class="tools"> </div>*/ /* </div>*/ /* <div class="portlet-body">*/ /* <table class="table table-striped table-bordered table-hover dt-responsive" width="100%" id="sample_2">*/ /* <thead>*/ /* <tr>*/ /* <th class="all" width="10%">Detalle</th>*/ /* <th class="all" width="10%">Editar</th>*/ /* <th class="all">Descripcion</th>*/ /* <th class="all">Fecha</th>*/ /* */ /* </tr>*/ /* </thead>*/ /* <tbody>*/ /* {% for Informacion in informacions%}*/ /* <tr>*/ /* <td>*/ /* <center>*/ /* <a href="{{ path('informacion_show', { 'id': Informacion.id }) }}">*/ /* <i class="glyphicon glyphicon-search"></i>*/ /* </a> */ /* </center>*/ /* </td>*/ /* <td>*/ /* <center>*/ /* <a href="{{ path('informacion_edit', { 'id': Informacion.id }) }}">*/ /* <i class="glyphicon glyphicon-pencil"></i>*/ /* </a> */ /* </center>*/ /* </td>*/ /* */ /* <td>{{ Informacion.descripcion | raw }}</td>*/ /* */ /* <td>{{ Informacion.fechahora | date("d/m/Y")}}</td>*/ /* */ /* </tr>*/ /* {% endfor %}*/ /* </tbody> */ /* </table>*/ /* </div>*/ /* </div>*/ /* <!-- END EXAMPLE TABLE PORTLET-->*/ /* </div>*/ /* */ /* </div>*/ /* */ /* */ /* <!-- END CONTENT BODY -->*/ /* */ /* </div> */ /* <!-- END CONTAINER -->*/ /* */ /* {% endblock %}*/ /* */ /* {% block javascripts_extra %}*/ /* */ /* */ /* <script> */ /* {% endblock %}*/
mwveliz/sitio
app/dev/cache/twig/dc/dcb7e8d84a1e074cd38632b157f2734551f32d9ae88b80d5d5cd4220dc152bad.php
PHP
mit
13,782
{ document.getElementsByClassName('close')[0].addEventListener('click', function() { window.close(); }); }
Conorrr/prox-t-chrome-extension
app/scripts.babel/firstRun.js
JavaScript
mit
112
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.Entities; using Umbraco.Cms.Core.Notifications; using Umbraco.Cms.Core.Trees; using Umbraco.Cms.Web.BackOffice.Controllers; using Umbraco.Cms.Web.Common.Filters; using Umbraco.Cms.Web.Common.ModelBinders; using Umbraco.Extensions; namespace Umbraco.Cms.Web.BackOffice.Trees { /// <summary> /// A base controller reference for non-attributed trees (un-registered). /// </summary> /// <remarks> /// Developers should generally inherit from TreeController. /// </remarks> [AngularJsonOnlyConfiguration] public abstract class TreeControllerBase : UmbracoAuthorizedApiController, ITree { // TODO: Need to set this, but from where? // Presumably not injecting as this will be a base controller for package/solution developers. private readonly UmbracoApiControllerTypeCollection _apiControllers; private readonly IEventAggregator _eventAggregator; protected TreeControllerBase(UmbracoApiControllerTypeCollection apiControllers, IEventAggregator eventAggregator) { _apiControllers = apiControllers; _eventAggregator = eventAggregator; } /// <summary> /// The method called to render the contents of the tree structure /// </summary> /// <param name="id"></param> /// <param name="queryStrings"> /// All of the query string parameters passed from jsTree /// </param> /// <remarks> /// We are allowing an arbitrary number of query strings to be passed in so that developers are able to persist custom data from the front-end /// to the back end to be used in the query for model data. /// </remarks> protected abstract ActionResult<TreeNodeCollection> GetTreeNodes(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))]FormCollection queryStrings); /// <summary> /// Returns the menu structure for the node /// </summary> /// <param name="id"></param> /// <param name="queryStrings"></param> /// <returns></returns> protected abstract ActionResult<MenuItemCollection> GetMenuForNode(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))]FormCollection queryStrings); /// <summary> /// The name to display on the root node /// </summary> public abstract string RootNodeDisplayName { get; } /// <inheritdoc /> public abstract string TreeGroup { get; } /// <inheritdoc /> public abstract string TreeAlias { get; } /// <inheritdoc /> public abstract string TreeTitle { get; } /// <inheritdoc /> public abstract TreeUse TreeUse { get; } /// <inheritdoc /> public abstract string SectionAlias { get; } /// <inheritdoc /> public abstract int SortOrder { get; } /// <inheritdoc /> public abstract bool IsSingleNodeTree { get; } /// <summary> /// Returns the root node for the tree /// </summary> /// <param name="queryStrings"></param> /// <returns></returns> public async Task<ActionResult<TreeNode>> GetRootNode([ModelBinder(typeof(HttpQueryStringModelBinder))]FormCollection queryStrings) { if (queryStrings == null) queryStrings = FormCollection.Empty; var nodeResult = CreateRootNode(queryStrings); if (!(nodeResult.Result is null)) { return nodeResult.Result; } var node = nodeResult.Value; //add the tree alias to the root node.AdditionalData["treeAlias"] = TreeAlias; AddQueryStringsToAdditionalData(node, queryStrings); //check if the tree is searchable and add that to the meta data as well if (this is ISearchableTree) node.AdditionalData.Add("searchable", "true"); //now update all data based on some of the query strings, like if we are running in dialog mode if (IsDialog(queryStrings)) node.RoutePath = "#"; await _eventAggregator.PublishAsync(new RootNodeRenderingNotification(node, queryStrings, TreeAlias)); return node; } /// <summary> /// The action called to render the contents of the tree structure /// </summary> /// <param name="id"></param> /// <param name="queryStrings"> /// All of the query string parameters passed from jsTree /// </param> /// <returns>JSON markup for jsTree</returns> /// <remarks> /// We are allowing an arbitrary number of query strings to be passed in so that developers are able to persist custom data from the front-end /// to the back end to be used in the query for model data. /// </remarks> public async Task<ActionResult<TreeNodeCollection>> GetNodes(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))]FormCollection queryStrings) { if (queryStrings == null) queryStrings = FormCollection.Empty; var nodesResult = GetTreeNodes(id, queryStrings); if (!(nodesResult.Result is null)) { return nodesResult.Result; } var nodes = nodesResult.Value; foreach (var node in nodes) AddQueryStringsToAdditionalData(node, queryStrings); //now update all data based on some of the query strings, like if we are running in dialog mode if (IsDialog(queryStrings)) foreach (var node in nodes) node.RoutePath = "#"; //raise the event await _eventAggregator.PublishAsync(new TreeNodesRenderingNotification(nodes, queryStrings, TreeAlias)); return nodes; } /// <summary> /// The action called to render the menu for a tree node /// </summary> /// <param name="id"></param> /// <param name="queryStrings"></param> /// <returns></returns> public async Task<ActionResult<MenuItemCollection>> GetMenu(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))]FormCollection queryStrings) { if (queryStrings == null) queryStrings = FormCollection.Empty; var menuResult = GetMenuForNode(id, queryStrings); if (!(menuResult.Result is null)) { return menuResult.Result; } var menu = menuResult.Value; //raise the event await _eventAggregator.PublishAsync(new MenuRenderingNotification(id, menu, queryStrings, TreeAlias)); return menu; } /// <summary> /// Helper method to create a root model for a tree /// </summary> /// <returns></returns> protected virtual ActionResult<TreeNode> CreateRootNode(FormCollection queryStrings) { var rootNodeAsString = Constants.System.RootString; queryStrings.TryGetValue(TreeQueryStringParameters.Application, out var currApp); var node = new TreeNode( rootNodeAsString, null, //this is a root node, there is no parent Url.GetTreeUrl(_apiControllers, GetType(), rootNodeAsString, queryStrings), Url.GetMenuUrl(_apiControllers, GetType(), rootNodeAsString, queryStrings)) { HasChildren = true, RoutePath = currApp, Name = RootNodeDisplayName }; return node; } #region Create TreeNode methods /// <summary> /// Helper method to create tree nodes /// </summary> /// <param name="id"></param> /// <param name="parentId"></param> /// <param name="queryStrings"></param> /// <param name="title"></param> /// <returns></returns> public TreeNode CreateTreeNode(string id, string parentId, FormCollection queryStrings, string title) { var jsonUrl = Url.GetTreeUrl(_apiControllers, GetType(), id, queryStrings); var menuUrl = Url.GetMenuUrl(_apiControllers, GetType(), id, queryStrings); var node = new TreeNode(id, parentId, jsonUrl, menuUrl) { Name = title }; return node; } /// <summary> /// Helper method to create tree nodes /// </summary> /// <param name="id"></param> /// <param name="parentId"></param> /// <param name="queryStrings"></param> /// <param name="title"></param> /// <param name="icon"></param> /// <returns></returns> public TreeNode CreateTreeNode(string id, string parentId, FormCollection queryStrings, string title, string icon) { var jsonUrl = Url.GetTreeUrl(_apiControllers, GetType(), id, queryStrings); var menuUrl = Url.GetMenuUrl(_apiControllers, GetType(), id, queryStrings); var node = new TreeNode(id, parentId, jsonUrl, menuUrl) { Name = title, Icon = icon, NodeType = TreeAlias }; return node; } /// <summary> /// Helper method to create tree nodes /// </summary> /// <param name="id"></param> /// <param name="parentId"></param> /// <param name="queryStrings"></param> /// <param name="title"></param> /// <param name="routePath"></param> /// <param name="icon"></param> /// <returns></returns> public TreeNode CreateTreeNode(string id, string parentId, FormCollection queryStrings, string title, string icon, string routePath) { var jsonUrl = Url.GetTreeUrl(_apiControllers, GetType(), id, queryStrings); var menuUrl = Url.GetMenuUrl(_apiControllers, GetType(), id, queryStrings); var node = new TreeNode(id, parentId, jsonUrl, menuUrl) { Name = title, RoutePath = routePath, Icon = icon }; return node; } /// <summary> /// Helper method to create tree nodes and automatically generate the json URL + UDI /// </summary> /// <param name="entity"></param> /// <param name="entityObjectType"></param> /// <param name="parentId"></param> /// <param name="queryStrings"></param> /// <param name="hasChildren"></param> /// <returns></returns> public TreeNode CreateTreeNode(IEntitySlim entity, Guid entityObjectType, string parentId, FormCollection queryStrings, bool hasChildren) { var contentTypeIcon = entity is IContentEntitySlim contentEntity ? contentEntity.ContentTypeIcon : null; var treeNode = CreateTreeNode(entity.Id.ToInvariantString(), parentId, queryStrings, entity.Name, contentTypeIcon); treeNode.Path = entity.Path; treeNode.Udi = Udi.Create(ObjectTypes.GetUdiType(entityObjectType), entity.Key); treeNode.HasChildren = hasChildren; treeNode.Trashed = entity.Trashed; return treeNode; } /// <summary> /// Helper method to create tree nodes and automatically generate the json URL + UDI /// </summary> /// <param name="entity"></param> /// <param name="entityObjectType"></param> /// <param name="parentId"></param> /// <param name="queryStrings"></param> /// <param name="icon"></param> /// <param name="hasChildren"></param> /// <returns></returns> public TreeNode CreateTreeNode(IUmbracoEntity entity, Guid entityObjectType, string parentId, FormCollection queryStrings, string icon, bool hasChildren) { var treeNode = CreateTreeNode(entity.Id.ToInvariantString(), parentId, queryStrings, entity.Name, icon); treeNode.Udi = Udi.Create(ObjectTypes.GetUdiType(entityObjectType), entity.Key); treeNode.Path = entity.Path; treeNode.HasChildren = hasChildren; return treeNode; } /// <summary> /// Helper method to create tree nodes and automatically generate the json URL /// </summary> /// <param name="id"></param> /// <param name="parentId"></param> /// <param name="queryStrings"></param> /// <param name="title"></param> /// <param name="icon"></param> /// <param name="hasChildren"></param> /// <returns></returns> public TreeNode CreateTreeNode(string id, string parentId, FormCollection queryStrings, string title, string icon, bool hasChildren) { var treeNode = CreateTreeNode(id, parentId, queryStrings, title, icon); treeNode.HasChildren = hasChildren; return treeNode; } /// <summary> /// Helper method to create tree nodes and automatically generate the json URL /// </summary> /// <param name="id"></param> /// <param name="parentId"></param> /// <param name="queryStrings"></param> /// <param name="title"></param> /// <param name="routePath"></param> /// <param name="hasChildren"></param> /// <param name="icon"></param> /// <returns></returns> public TreeNode CreateTreeNode(string id, string parentId, FormCollection queryStrings, string title, string icon, bool hasChildren, string routePath) { var treeNode = CreateTreeNode(id, parentId, queryStrings, title, icon); treeNode.HasChildren = hasChildren; treeNode.RoutePath = routePath; return treeNode; } /// <summary> /// Helper method to create tree nodes and automatically generate the json URL + UDI /// </summary> /// <param name="id"></param> /// <param name="parentId"></param> /// <param name="queryStrings"></param> /// <param name="title"></param> /// <param name="routePath"></param> /// <param name="hasChildren"></param> /// <param name="icon"></param> /// <param name="udi"></param> /// <returns></returns> public TreeNode CreateTreeNode(string id, string parentId, FormCollection queryStrings, string title, string icon, bool hasChildren, string routePath, Udi udi) { var treeNode = CreateTreeNode(id, parentId, queryStrings, title, icon); treeNode.HasChildren = hasChildren; treeNode.RoutePath = routePath; treeNode.Udi = udi; return treeNode; } #endregion /// <summary> /// The AdditionalData of a node is always populated with the query string data, this method performs this /// operation and ensures that special values are not inserted or that duplicate keys are not added. /// </summary> /// <param name="node"></param> /// <param name="queryStrings"></param> protected void AddQueryStringsToAdditionalData(TreeNode node, FormCollection queryStrings) { foreach (var q in queryStrings.Where(x => node.AdditionalData.ContainsKey(x.Key) == false)) node.AdditionalData.Add(q.Key, q.Value); } /// <summary> /// If the request is for a dialog mode tree /// </summary> /// <param name="queryStrings"></param> /// <returns></returns> protected bool IsDialog(FormCollection queryStrings) { queryStrings.TryGetValue(TreeQueryStringParameters.Use, out var use); return use == "dialog"; } } }
JimBobSquarePants/Umbraco-CMS
src/Umbraco.Web.BackOffice/Trees/TreeControllerBase.cs
C#
mit
15,982
'use strict'; angular.module('com.module.sandbox') .controller('DatepickerDemoCtrl', function ($scope) { $scope.today = function () { $scope.dt = new Date(); }; $scope.today(); $scope.clear = function () { $scope.dt = null; }; $scope.disabled = function (date, mode) { return (mode === 'day' && (date.getDay() === 0 || date.getDay() === 6)); }; $scope.toggleMin = function () { $scope.minDate = $scope.minDate ? null : new Date(); }; $scope.toggleMin(); $scope.open = function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = true; }; $scope.dateOptions = { formatYear: 'yy', startingDay: 1 }; $scope.formats = [ 'dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate' ]; $scope.format = $scope.formats[0]; });
drmikecrowe/loopback-angular-admin
client/app/modules/sandbox/controllers/sandbox.datepickerdemo.ctrl.js
JavaScript
mit
917
#define ConcurrentHandles #define WARN_VOB //#define INFO_VOB #define TRACE_VOB using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using LionFire.Collections; using LionFire.DependencyInjection; using LionFire.Extensions.ObjectBus; using LionFire.Instantiating; using LionFire.MultiTyping; using LionFire.ObjectBus; using LionFire.Ontology; using LionFire.Referencing; using LionFire.Structures; using LionFire.Types; using LionFire.Vos; using LionFire.Vos.Internals; using LionFire.Vos.Services; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace LionFire.Vos { // ----- Mount notes ----- // //public INotifyingReadOnlyCollection<Mount> Mounts { get { return mounts; } } // ////private MultiBindableDictionary<string, Mount> mountsByPath = new MultiBindableDictionary<string, Mount>(); // //private MultiBindableCollection<Mount> mounts = new MultiBindableCollection<Mount>(); // // Disk location: ValorDir/DataPacks/Official/Valor1/Core.zip // // /Valor/Packages/Nextrek/Maps/Bronco.Map // // /Valor/Packages/Nextrek/Maps/Bronco/Settings/Vanilla // // /Valor/Packages/Nextrek/Maps/Bronco/Settings/INL // // Disk location: ValorDir/DataPacks/Official/Expansion1.zip // // Disk location: ValorDir/DataPacks/Official/Maps/MapPack1.zip // // /Valor/Packages/Nextrek/Maps/Chaos.Map // // /Valor/Packages/Nextrek/Maps/Chaos/Settings/Cibola // // Disk location: ValorDir/DataPacks/Official/Maps/MapPack2.zip // // Disk location: ValorDir/DataPacks/Official/Expansion1/Core.zip // // Disk location: ValorDir/DataPacks/Official/Expansion2/Core.zip // // Disk location: ValorDir/DataPacks/Downloaded/Vanilla2.zip // // Disk location: ValorDir/DataPacks/Mods/TAMod/Core.1.0.zip // // Disk location: ValorDir/DataPacks/Mods/TAMod/Core.1.1.zip // // Disk location: ValorDir/DataPacks/Mods/TAMod/MapPack1.zip // // /Valor/Packages/Nextrek/Maps/Bronco/Settings/Vanilla2 // // Data Packs Menu: // // - Core // // - Base // // - Custom // // - Vanilla2 // // Disk location: ValorDir/Data (rooted at Valor/Packages)/Nextrek/Maps/Bronco/Settings/Vanilla3 // // Disk location: ValorDir/Data // // 3 mounts: // // Valor/Data | file:///c:/Program Files/LionFire/Valor/Data // // Valor/Data | file:///c:/Program Files/LionFire/Valor/DataPacks // ---------------- Other notes // // vos://host/path/to/node%Type // // vos://host/path/to/.node.Type.ext // // vos://host/path/to/node%Type[instanceName] // // vos://host/path/to/node/.TYPEs/instanceName // // vos://host/path/to/node%Type[] - all instances, except main instance //public class PathTree<T> // where T : class //{ // public T this[string subpath] => this[subpath]; // public T GetChild(string subpath) => GetChild(subpath.ToPathArray(), 0); // public T QueryChild(string reference) => QueryChild(subpath.ToPathArray(), 0); //} /// <summary> /// /// VOB: /// knows where it is (has reference) /// keeps track of its children (is an active node in a VosBase) /// is invalidated when mounts change /// has handles to objects in multiple layers /// has handles to its multi-type objects /// - can be locked to a uni-type object /// /// Dynamic Object. /// /// Brainstorm: /// /// Dob: created automatically as a multitype object (if needed) /// UnitType (references components of types) /// Pob: Partial object. Object piece. Can have subchildren /// - Version (optional decorator, but may be required by app) /// - Could be implemented as a field, then implement the read-only IMultiType to provide OBus access to it /// - Personal notes (saved in personal layer) /// /// - For child objects: is it an 'is a' or 'has a' relationship? Containment vs reference / decorators /// - allow nested subobjects????? /// /// Anyobject support: hooray for POCO /// /// Can Proxies/mixins help? /// - load an object, get a mixin back? Doesn't seem so hard now that I think I've done it /// </summary> /// <remarks> /// Handle overrides: /// - (TODO) Object set/get. /// - get_Object - for Vob{T} this will return the object as T, if any. Otherwise, it may return a single object, or a MultiType object /// - set_Object - depending on the situation, it may assign into a MultiType object /// </remarks> public partial class Vob : // RENAME - MinimalVob? //CachingHandleBase<Vob, Vob>, //CachingChildren<Vob>, //IHasHandle, //H, // TODO - make this a smarter handle. The object might be a dynamically created MultiType for complex scenarios IReferencable #if AOT IParented #else , IParentable<IVob> #endif , IVob , IVobInternals , IMultiTypable , IHierarchyOfKeyedOnDemand<IVob> // TODO //, SReadOnlyMultiTyped // FUTURE? { #region Identity public string Name => name; private readonly string name; #region Relationships #region Parent #if AOT object IParented.Parent { get { return this.Parent; } set { throw new NotSupportedException(); } } #endif #region Parent public IVob Parent { get => parent; set => throw new NotSupportedException(); } private readonly IVob parent; #endregion #endregion #endregion #endregion #region Construction public Vob(IVob parent, string name) { if (this is RootVob rootVob) { #if DEBUG if (!string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("Name must be null or empty for RootVobs."); // Redundant check #endif } else { if (parent == null) { throw new ArgumentNullException($"'{nameof(parent)}' must be set for all non-RootVob Vobs."); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException($"'{nameof(name)}' must not be null or empty for a non-root Vob"); } } this.parent = parent; this.name = name ?? ""; } //public Vob(VBase vos, Vob parent, string name) : this(parent,name) //{ // if (vos == null) // { // throw new ArgumentNullException("vos"); // } // this.vbase = vos; //} #endregion #region Derived public string Key => VobReference.Key; #region Path public virtual string Path => LionPath.GetTrimmedAbsolutePath(LionPath.Combine(parent == null ? "" : parent.Path, name)); internal int Depth => LionPath.GetAbsolutePathDepth(Path); public IEnumerable<string> PathElements { get { if (Parent != null) { foreach (var pathElement in Parent.PathElements) { yield return pathElement; } } if (!String.IsNullOrEmpty(Name)) { yield return Name; } else { if (Parent == null) { // yield nothing } else { yield return null; // Shouldn't happen. //yield return String.Empty; // REVIEW - what to do here? } } } } public IEnumerable<string> PathElementsReverse { get { yield return Name; if (Parent != null) { foreach (var pathElement in Parent.PathElementsReverse) { yield return pathElement; } } } } #endregion #region Reference public VobReference VobReference { get { if (vobReference == null) { vobReference = new VobReference(Path); } return vobReference; } set { if (vobReference == value) { return; } if (vobReference != default(IReference)) { throw new NotSupportedException("Reference can only be set once. To relocate, use the Move() method."); } vobReference = value; } } private VobReference vobReference; public IVobReference Reference => VobReference; IReference IReferencable.Reference // TODO MEMORYOPTIMIZE: I think a base class has an IReference field { get => VobReference; //set //{ // if (value == null) { VobReference = null; return; } // VobReference vr = value as VobReference; // if (vr != null) // { // VobReference = vr; // return; // } // else // { // //new VobReference(value); // FUTURE: Try converting // throw new ArgumentException("Reference for a Vob must be VobReference"); // } //} } #endregion IRootVob IVob.Root => Root; public virtual RootVob Root { get { IVob vob; for (vob = this; vob.Parent != null; vob = vob.Parent) ; return vob as RootVob; } } #endregion public object FlexData { get; set; } #region MultiTyped // Non-inhereted extensions public IMultiTyped MultiTyped { get { if (multiTyped == null) { multiTyped = new MultiType(); } return multiTyped; } } protected MultiType multiTyped; #endregion #region VobNodes #region Vob Nodes: Own data IEnumerable<KeyValuePair<Type, IVobNode>> IVobInternals.VobNodesByType => vobNodesByType; protected ConcurrentDictionary<Type, IVobNode> vobNodesByType; VobNode<T> IVobInternals.TryAcquireOwnVobNode<T>() where T : class { var collection = vobNodesByType; if (collection == null) return null; if (collection.TryGetValue(typeof(T), out IVobNode v)) return (VobNode<T>)v; return null; } T DefaultFactory<T>(params object[] parameters) { var serviceProvider = this.GetService<IServiceProvider>(); if (serviceProvider != null) { { var factory = this.GetService<IInjectingFactory<T>>(); if (factory != null) { return factory.Create(serviceProvider, parameters); } } { var factory = this.GetService<IFactory<T>>(); if (factory != null) { return factory.Create(parameters); } } } return (T)Activator.CreateInstance(typeof(T), parameters); } #region VobNode Value Factory TInterface DefaultVobNodeValueFactory<TInterface>(IVobNode vobNode) { { var factory = this.GetService<IFactory<TInterface>>(); if (factory != null) { return factory.Create(); } } { var func = this.GetService<Func<Vob, TInterface>>(); if (func != null) { return func(this); } } { var func = this.GetService<Func<TInterface>>(); if (func != null) { return func(); } } if (!typeof(TInterface).IsAbstract && !typeof(TInterface).IsInterface) { return ActivatorUtilities.CreateInstance<TInterface>(ServiceProviderForVobNode(vobNode)); } throw new NotSupportedException($"No IFactory<TInterface> or Func<IVob, TInterface> or Func<TInterface> service registered and type is abstract or interface -- cannot create TInterface of type: {typeof(TInterface).Name}"); } TInterface DefaultVobNodeValueFactory<TInterface, TImplementation>(IVobNode vobNode) where TImplementation : TInterface => ActivatorUtilities.CreateInstance<TImplementation>(ServiceProviderForVobNode(vobNode)); IServiceProvider ServiceProviderForVobNode(IVobNode vobNode) => new ServiceProviderWrapper(this.GetServiceProvider(), factoryServices(vobNode)); IDictionary<Type, object> factoryServices(IVobNode vobNode) { return new Dictionary<Type, object> { [typeof(Vob)] = vobNode.Vob, [typeof(IVobNode)] = vobNode }; } #endregion VobNode<TInterface> IVobInternals.TryAddOwnVobNode<TInterface>(Func<IVobNode, TInterface> valueFactory) { if (vobNodesByType == null) vobNodesByType = new ConcurrentDictionary<Type, IVobNode>(); var already = vobNodesByType.ContainsKey(typeof(TInterface)); VobNode<TInterface> result = null; if (!already) { already = !vobNodesByType.TryAdd(typeof(TInterface), result = (VobNode<TInterface>)Activator.CreateInstance(typeof(VobNode<>).MakeGenericType(typeof(TInterface)), this, valueFactory ?? DefaultVobNodeValueFactory<TInterface>)); } // if (already) throw new AlreadyException($"Already contains {typeof(TInterface).Name}"); // ENH: Create a separate AddOwnVobNode extension method to throw this return already ? null : result; } VobNode<TInterface> IVobInternals.AcquireOrAddOwnVobNode<TInterface>(Func<IVobNode, TInterface> valueFactory) { if (vobNodesByType == null) vobNodesByType = new ConcurrentDictionary<Type, IVobNode>(); return (VobNode<TInterface>)vobNodesByType.GetOrAdd(typeof(TInterface), t => (IVobNode)Activator.CreateInstance(typeof(VobNode<>).MakeGenericType(t), this, valueFactory ?? DefaultVobNodeValueFactory<TInterface>)); } VobNode<TInterface> IVobInternals.AcquireOrAddOwnVobNode<TInterface, TImplementation>(Func<IVobNode, TInterface> valueFactory) //where TInterface : class //where TImplementation : TInterface { if (vobNodesByType == null) vobNodesByType = new ConcurrentDictionary<Type, IVobNode>(); return (VobNode<TInterface>)vobNodesByType.GetOrAdd(typeof(TInterface), t => (IVobNode)Activator.CreateInstance(typeof(VobNode<>).MakeGenericType(t), this, valueFactory ?? DefaultVobNodeValueFactory<TInterface, TImplementation>)); } /// <summary> /// Get Value from own VobNode /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T AcquireOwn<T>() where T : class => Acquire<T>(maxDepth: 0).Take(1).FirstOrDefault(); //{ // var node = ((IVobInternals)this).TryAcquireOwnVobNode<T>(); // if (node != null) return node.Value; // return default; //} public IEnumerable<T> Acquire<T>(int minDepth = 0, int maxDepth = -1) where T : class { IVob vob = this; int depth = 0; for (int skip = minDepth; skip > 0 && vob != null; skip--) { vob = vob.Parent; depth++; } for (IVobNode<T> node = vob.TryGetOwnVobNode<T>(); node != null && (maxDepth < 0 || depth <= maxDepth); node = node.ParentVobNode) { if (node?.Value != null) yield return node.Value; if (node?.ParentVobNode != null) { depth += node.Vob.Depth - node.ParentVobNode.Vob.Depth; } } } public IEnumerable<T> AcquireMany<T>() where T : class => Acquire<IEnumerable<T>>().SelectMany(e => e); #endregion #region Vob Nodes: Inheritance public IEnumerable<IVob> ParentEnumerable { get { yield return this; for (var vob = Parent; vob != null; vob = vob.Parent) yield return vob; } } VobNode<T> IVobInternals.TryAcquireNextVobNode<T>(int minDepth, int maxDepth) where T : class { var depth = 0; var vobEnumerable = ParentEnumerable; vobEnumerable.Skip(minDepth); depth += minDepth; foreach (var vob in vobEnumerable) { if (maxDepth >= 0 && depth > maxDepth) break; var vobNode = ((IVobInternals)vob).TryAcquireOwnVobNode<T>(); if (vobNode != null) return vobNode; } //var vob = ParentEnumerable.ElementAt(skipOwn ? 1 : 0); //while (vob != null) //{ // var vobNode = ((IVobInternals)vob).TryGetOwnVobNode<T>(); // if (vobNode != null) return vobNode; // vob = vob.Parent; //} return null; } ContextedVobNode<T> IVobInternals.TryGetNextContextedVobNode<T>(int minDepth) where T : class => new ContextedVobNode<T>(this, ((IVobInternals)this).TryAcquireNextVobNode<T>(minDepth)); /// <param name="addAtRoot">True: if missing, will add at root. False: if missing, add at local Vob</param> /// <returns></returns> public VobNode<TInterface> AcquireOrAddNextVobNode<TInterface, TImplementation>(Func<IVobNode, TInterface> factory = null, bool addAtRoot = true) where TImplementation : TInterface where TInterface : class { IVob vob; for (vob = this; vob != null; vob = vob.Parent) { var vobNode = vob.TryGetOwnVobNode<TInterface>(); if (vobNode != null) return vobNode; } return (addAtRoot ? vob : this).GetOrAddOwnVobNode<TInterface, TImplementation>(factory); } public T AcquireNext<T>(int minDepth = 0, int maxDepth = -1) where T : class => this.TryGetNextVobNode<T>(minDepth: minDepth, maxDepth: maxDepth)?.Value ?? default; #if TODO // If needed public int NextVobNodeRelativeDepth { get { int i = 0; var vob = this; while (vob != null) { if (vob.VobNode != null) return i; vob = vob.Parent; i--; } throw new VosException("Missing NextVobNode"); // Should not happen - RootVob should always have a VobNode. } } #endif #endregion #region Vob Nodes: Descendants #if TODO // Maybe public IEnumerable<VobNode> ChildVobNodes { get { foreach (var child in Children.Select(kvp => kvp.Value)) { if (child.VobNode != null) yield return child.VobNode; foreach (var childVobNode in child.ChildVobNodes) { yield return childVobNode; } } } } #endif #endregion #endregion #region Referencing #region GetReference<T> // TODO: Move to extension method? // FUTURE MEMOPTIMIZE - consider caching/reusing these references to save memory? /// <summary> /// Get typed reference /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public IVobReference<T> GetReference<T>() => new VobReference<T>(Path) { Persister = string.IsNullOrEmpty(Root.RootName) ? null : Root.RootName }; // OPTIMIZE: new VosRelativeReference(this) // TODO: Use VobReference<T>? Providers need to be wired up to DI #endregion #endregion #region Misc public override bool Equals(object obj) { var other = obj as Vob; if (other == null) { return false; } #if DEBUG if (Path == other.Path && this != other) { l.TraceWarn("Two Vobs with same path but !="); } if (Path == other.Path && !object.ReferenceEquals(this, other)) { l.TraceWarn("Two Vobs with same path but !ReferenceEquals"); } #endif return Path == other.Path; } public override int GetHashCode() => Path.GetHashCode(); public override string ToString() => Reference?.ToString(); private static readonly ILogger l = Log.Get(); #endregion } }
lionfire/Core
src/LionFire.Vos/Vob/Vob.cs
C#
mit
23,106
import Ember from 'ember'; const { computed } = Ember; let IronSelector = Ember.Component.extend({ attributeBindings: [ 'selected', 'role', 'attrForSelected', 'multi' ], selectedItem: computed({ get() {}, set(key, value) { let items = this.get('items'); let idx = -1; if (items) { idx = this.get('items').indexOf(value); } if (this.getSelectedIndex() !== idx && idx !== -1) { this.set('selected', idx); } return value; } }), getSelectedIndex() { let el = this.element; if (el) { return typeof el.selected === 'number' ? el.selected : el.indexOf(el.selectedItem); } else { return -1; } }, didInsertElement() { this._super(...arguments); this.$().on('iron-select', () => { let el = this.element; let items = this.get('items'); if (items) { this.set('selectedItem', items[this.getSelectedIndex()]); } else { this.set('selectedItem', el.selected); } }); // initial selection let selectedItem = this.get('selectedItem'); if (selectedItem) { let items = this.get('items'); if (items) { this.element.select(selectedItem === 'number' ? selectedItem : items.indexOf(selectedItem)); } else { this.element.select(selectedItem === 'number' ? selectedItem : this.element.items.indexOf(selectedItem)); } } } }); IronSelector.reopenClass({ positionalParams: [ 'items' ] }); export default IronSelector;
dunnkers/ember-polymer-paper
addon/components/iron-selector.js
JavaScript
mit
1,701
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Engine { public class Item { public int ID { get; set; } public string Name { get; set; } public string NamePlural { get; set; } public Item(int id, string name, string namePlural) { ID = id; Name = name; NamePlural = namePlural; } } }
DKarandikar/SuperAdventure
SuperAdventure/Engine/Item.cs
C#
mit
489
"""Parse ISI journal abbreviations website.""" # Copyright (c) 2012 Andrew Dawson # # 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. try: from html.parser import HTMLParser except ImportError: from HTMLParser import HTMLParser class ISIJournalParser(HTMLParser): """Parser for ISI Web of Knowledge journal abbreviation pages. **Note:** Due to the ISI pages containing malformed html one must call the :py:meth:`ISIJournalParser.finalize` method once parsing is complete to ensure all entries are read correctly. """ def __init__(self): HTMLParser.__init__(self) self.journal_names = [] self.journal_abbreviations = [] self.parser_state = None self.data_entities = None def handle_starttag(self, tag, attrs): if tag not in ('dd', 'dt'): return self._storedata() self.parser_state = tag self.data_entities = [] def handle_data(self, data): if self.parser_state in ('dd', 'dt'): self.data_entities.append(data) def _storedata(self): if self.data_entities and self.parser_state: if self.parser_state == 'dt': self.journal_names.append(''.join(self.data_entities).strip()) elif self.parser_state == 'dd': self.journal_abbreviations.append(''.join(self.data_entities).strip()) def finalize(self): """Ensures all data is stored. This method must be called when parsing is complete. """ self._storedata()
ajdawson/jabr
lib/parser.py
Python
mit
2,590
module V1 module Modules class User < Grape::API before_validation do authenticate! end format :json content_type :json, 'application/json' # params :auth do # requires :access_token, type: String, desc: 'Auth token', documentation: { example: '837f6b854fc7802c2800302e' } # end resource :users do desc 'Retuns all users' get :all do ::User.all.to_a end desc 'Returns me', { notes: <<-NOTE ### Description It returns the logged user. \n ### Example successful response { "id": "1", "name": "Lourdez Astre", "first_name": "Lourdez", "last_name": "Astre", "email": "lourdezastre@test.com", } NOTE } get :me do # 'grape transformation' gem works the same way to :type paramater in present method? present current_user, with: V1::Entities::User end desc 'Update the current user', { notes: <<-NOTE ### Description Update the current user. \n It returns the logged user. \n ### Example successful response { "id": "1", "name": "Lourdez Astre", "first_name": "Lourdez", "last_name": "Astre", "email": "lourdezastre@test.com", } NOTE } params do requires :user, type: Hash end put '/', http_codes: [ [200, "Successful"], [400, "Invalid parameter"], [401, "Unauthorized"], [404, "Entry not found"], ] do current_user.update(params[:user]) present current_user, with: V1::Entities::User end end end end end
degzcs/rails-angular-lineman-example
app/api/v1/modules/user.rb
Ruby
mit
2,040
package org.simplemart.product.health; import com.codahale.metrics.health.HealthCheck; public class PingHealthCheck extends HealthCheck { @Override protected Result check() throws Exception { return Result.healthy(); } }
rzhilkibaev/demo-simple-web
demo-store/src/main/java/org/simplemart/product/health/PingHealthCheck.java
Java
mit
245
<?php namespace Mascame\Artificer\Fields; use Mascame\Artificer\Artificer; class Field extends AbstractField implements FieldInterface { use Filterable, HasHooks, HasWidgets; /** * Field constructor. * @param $type * @param $name * @param array $options */ public function __construct($type, $name, $options = []) { $this->type = $type; $this->name = $name; $this->options = $options; $this->widgets = $this->getInstalledWidgets(); $this->attachHooks(); } /** * @return bool */ public function isRelation() { return (bool) $this->getOption('relationship', false); } /** * @param $array * @return bool */ protected function isAll($array) { return is_array($array) && isset($array[0]) && ($array[0] == '*' || $array == '*'); } /** * @param string $visibility [visible|hidden] * @return bool */ protected function hasVisibility($visibility) { $visibilityOptions = Artificer::modelManager()->current()->settings()->getOption( Artificer::getCurrentAction() ); if (! $visibilityOptions || ! isset($visibilityOptions[$visibility])) { return false; } return $this->isAll($visibilityOptions[$visibility]) || $this->isInArray($this->getName(), $visibilityOptions[$visibility]); } /** * Hidden fields have preference. * * @return bool */ public function isVisible() { if ($this->isHidden()) { return false; } return $this->hasVisibility('visible'); } /** * @param $value * @param $array * @return bool */ private function isInArray($value, $array) { return is_array($array) && in_array($value, $array); } /** * @return bool */ public function isHidden() { return $this->hasVisibility('hidden'); } /** * @return bool */ public function isFillable() { $fillable = Artificer::modelManager()->current()->settings()->getFillable(); return $this->isAll($fillable) || in_array($this->getName(), $fillable); } /** * @param array|string $classes */ protected function mergeAttribute($attribute, $value) { if (! is_array($value)) { $value = [$value]; } $attributes = $this->getAttributes()[$attribute] ?? []; return array_merge($attributes, $value); } /** * @param string $attribute * @param array|string $value */ public function addAttribute($attribute, $value) { $value = $this->mergeAttribute($attribute, $value); $this->setOptions(['attributes' => [$attribute => $value]]); } /** * @param $value * @return mixed */ public function transformValue($value) { return $value; } }
marcmascarell/artificer
src/Fields/Field.php
PHP
mit
3,046
export { FilterDisableHiddenStateComponent } from './filter-disable-hidden-state.component';
shlomiassaf/tdm
apps/demo/src/modules/@forms/tutorials/9-filter-disable-hidden-state/index.ts
TypeScript
mit
93
export default function reducer (state = {}, action) { return state; };
moooink/too-much-noise
client/source/reducers/language.js
JavaScript
mit
74
import React, { Component, ComponentType } from 'react' import { getBoundsForNode, TComputedBounds, TGetBoundsForNodeArgs } from './utils' import { TSelectableItemState, TSelectableItemProps } from './Selectable.types' import { SelectableGroupContext } from './SelectableGroup.context' type TAddedProps = Partial<Pick<TSelectableItemProps, 'isSelected'>> export const createSelectable = <T extends any>( WrappedComponent: ComponentType<TSelectableItemProps & T> ): ComponentType<T & TAddedProps> => class SelectableItem extends Component<T & TAddedProps, TSelectableItemState> { static contextType = SelectableGroupContext static defaultProps = { isSelected: false, } state = { isSelected: this.props.isSelected, isSelecting: false, } node: HTMLElement | null = null bounds: TComputedBounds[] | null = null componentDidMount() { this.updateBounds() this.context.selectable.register(this) } componentWillUnmount() { this.context.selectable.unregister(this) } updateBounds = (containerScroll?: TGetBoundsForNodeArgs) => { this.bounds = getBoundsForNode(this.node!, containerScroll) } getSelectableRef = (ref: HTMLElement | null) => { this.node = ref } render() { return ( <WrappedComponent {...this.props} {...this.state} selectableRef={this.getSelectableRef} /> ) } }
valerybugakov/react-selectable-fast
src/CreateSelectable.tsx
TypeScript
mit
1,421
/* var jsonfile = require('jsonfile'); var file = '../data1.json'; var tasksController = require('../public/js/tasks.js'); jsonfile.writeFile(file,data1); */ // var User = require('../public/js/mongoUser.js'); var Task = require('../public/js/mongoTasks.js'); var MongoClient = require('mongodb').MongoClient, format = require('util').format; var dJ = require('../data1.json'); var tasksCount, taskList, groupList; exports.viewTasks = function(req, res){ MongoClient.connect('mongodb://heroku_2s7m53vj:lqb9p32ov0u6akts4hoekc7h5l@ds153677.mlab.com:53677/heroku_2s7m53vj', function(err, db) { if(err) throw err; var collection = db.collection('tasks'); var collection2 = db.collection('groups'); // collection.count(function(err, count) { // //console.log(format("count = %s", count)); // tasksCount = count; // }); // Locate all the entries using find collection.find().toArray(function(err, results) { taskList = results; }); collection2.find().toArray(function(err,results) { groupList = results; // console.dir(groupList); }); db.close(); }) res.render('tasks', { dataJson: dJ, tasks: taskList, groups: groupList }); }; exports.updateTasks = function(req,res) { var name = req.body.name; var reward = req.body.reward; var description = req.body.description; var userSelected = ""; var newTask = new Task({ name: name, reward: reward, description: description, userSelected: userSelected }); Task.createTask(newTask, function(err,task) { if(err) throw err; //console.log(task); }); res.redirect(req.get('referer')); // res.redirect('/index'); } exports.editTasks = function(req,res) { MongoClient.connect('mongodb://heroku_2s7m53vj:lqb9p32ov0u6akts4hoekc7h5l@ds153677.mlab.com:53677/heroku_2s7m53vj', function(err, db) { if(err) throw err; var collection = db.collection('tasks'); var oldName = req.body.oldName || req.query.oldName; var oldReward = req.body.oldReward || req.query.oldReward; var oldDescription = req.body.oldDescription || req.query.oldDescription; var taskName = req.body.taskName || req.query.taskName; var taskReward = req.body.taskReward || req.query.taskReward; var taskDescription = req.body.taskDescription || req.query.taskDescription; //console.dir(taskName); //collection.remove({"name": memberName}); collection.update({'name': oldName},{$set:{'name':taskName}}); collection.update({'reward': parseInt(oldReward)},{$set:{'reward': parseInt(taskReward)}}); collection.update({'description': oldDescription},{$set:{'description':taskDescription}}); db.close() // Group.removeMember(memberName, function(err,group){ // if(err) throw err; // console.log(group); // }) }) res.redirect(req.get('referer')); } exports.removeTasks = function(req,res){ MongoClient.connect('mongodb://heroku_2s7m53vj:lqb9p32ov0u6akts4hoekc7h5l@ds153677.mlab.com:53677/heroku_2s7m53vj', function(err, db) { if(err) throw err; var collection = db.collection('tasks'); var taskName = req.body.taskID || req.query.taskID; //console.dir(taskName); collection.remove({ $or: [{"name": taskName}, {"name": ''}] }); db.close() // Group.removeMember(memberName, function(err,group){ // if(err) throw err; // console.log(group); // }) }) res.redirect(req.get('referer')); } exports.selectUser = function(req,res){ MongoClient.connect('mongodb://heroku_2s7m53vj:lqb9p32ov0u6akts4hoekc7h5l@ds153677.mlab.com:53677/heroku_2s7m53vj', function(err, db) { if(err) throw err; var collection = db.collection('tasks'); var selectedUser = req.body.selectedUser || req.query.selectedUser; var taskName = req.body.taskName || req.query.taskName; // console.dir(selectedUser); collection.update({'name': taskName},{$set:{'userSelected': selectedUser}}); db.close() }) }
odangitsdjang/CleaningApp
routes/tasks.js
JavaScript
mit
4,170
import glob import os import pandas as pd class CTD(object): """docstring for CTD""" def __init__(self): self.format_l = [] self.td_l = [] self.iternum = 0 self.formatname = "" def feature(self,index): format_l = self.format_l feature = ((float(format_l[index+1][1])-float(format_l[index+3][1]))/float(format_l[index+1][1]))+((float(format_l[index+1][4])-float(format_l[index+3][4]))/float(format_l[index+1][4])) if (feature == 0): feature = 0.0001 return feature def format(self,path): a = path.split('/') self.formatname = a[2] with open(path, 'r') as f: a = f.read() f = a.split('\n') f.pop(0) self.iternum = len(f)-3 for a in range(len(f)): a = f[a].split(',') a.pop(0) self.format_l.append(a) def trainData(self): for index in range(self.iternum): try: format_l = self.format_l classify = (float(format_l[index][3])-float(format_l[index+1][3]))/float(format_l[index+1][3])*100 feature = self.feature(index) a = ['0']+format_l[index+1]+format_l[index+2]+format_l[index+3]+[feature] self.td_l.append(a) except: pass def storage_csv(self): rowname=['classify','feature','1-open','1-high','1-low','1-close','1-volume','1-adj close','2-open','2-high','2-low','2-close','2-volume','2-adj close','3-open','3-high','3-low','3-close','3-volume','3-adj close'] df = pd.DataFrame(self.td_l,columns=rowname) with open('./traindata/td_'+self.formatname+'.csv', 'w') as f: df.to_csv(f) print('td_'+self.formatname+'.csv is creat!') def storage_txt(self,pathname): with open('./predict/data/'+pathname,'ab') as f: for a in self.td_l: b = str(a[0])+'\t' for c in range(1,20): d = str(c)+':'+str(a[c])+'\t' b += d f.write(b+'\n') def run(self): path = './stock/*' paths=glob.glob(path) for index,path in enumerate(paths,1): print(index) self.format_l = [] self.td_l = [] self.format(path) self.trainData() path = path.split('/') pathname = path[2] self.storage_txt(pathname) print os.popen("./bin/svm-scale -s predict_scale_model ./predict/data/"+pathname+" > ./predict/scale/"+pathname+"predict_data.scale").read() print os.popen("./bin/rvkde --best --predict --classify -v ./train/scale/"+pathname+"train_data.scale -V ./predict/scale/"+pathname+"predict_data.scale > ./predict/result/"+pathname+"predict_result").read() def main(): ctd = CTD() ctd.run() if __name__ == '__main__' : main()
wy36101299/NCKU_Machine-Learning-and-Bioinformatics
hw4_predictData/creatPredictdata.py
Python
mit
2,986
using System; using System.IO; namespace Day2 { class Program { static string puzzleInput = File.ReadAllText("puzzleInput.txt"); static int[,] KeyPad = new int[3, 3] { {1,2,3} , {4,5,6} , {7,8,9} }; static char[,] KeyPad2 = new char[5, 5] { {'-','-','1','-','-'}, {'-','2','3','4','-'}, {'5','6','7','8','9'}, {'-','A','B','C','-'}, {'-','-','D','-','-'} }; static int Row; static int Column; static void Main(string[] args) { var instructions = puzzleInput.Replace(" ", string.Empty).Split(new string[] { Environment.NewLine }, StringSplitOptions.None); // Part one Row = 1; Column = 1; foreach (var instruction in instructions) { HandleInstruction(instruction); Console.Write(KeyPad[Row, Column]); } Console.Write("\n"); // Part two Row = 2; Column = 0; foreach (var instruction in instructions) { HandleInstruction2(instruction); Console.Write(KeyPad2[Row, Column]); } Console.Write("\n"); Console.Read(); } static void HandleInstruction2(string instruction) { foreach (char c in instruction) { switch (c) { case 'U': if (Row > 0 && KeyPad2[Row - 1, Column] != '-') Row--; break; case 'D': if (Row < 4 && KeyPad2[Row + 1, Column] != '-') Row++; break; case 'L': if (Column > 0 && KeyPad2[Row, Column - 1] != '-') Column--; break; case 'R': if (Column < 4 && KeyPad2[Row, Column + 1] != '-') Column++; break; } } } static void HandleInstruction(string instruction) { foreach (char c in instruction) { switch (c) { case 'U': Row--; break; case 'D': Row++; break; case 'L': Column--; break; case 'R': Column++; break; } Row = Row < 0 ? 0 : Row; Row = Row > 2 ? 2 : Row; Column = Column < 0 ? 0 : Column; Column = Column > 2 ? 2 : Column; } } } }
fredrikljung93/AdventOfCode2016
AdventOfCode/Day2/Program.cs
C#
mit
3,235
<?php namespace Maidmaid\WebotBundle\Event; use GuzzleHttp\Message\Response; use NumberPlate\AbstractSearcherSubscriber; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\EventDispatcher\GenericEvent; class SearcherSubscriber extends AbstractSearcherSubscriber { /* @var $input InputInterface */ private $input; /* @var $output OutputInterface */ private $output; public function __construct(InputInterface $input, OutputInterface $output) { $this->input = $input; $this->output = $output; } public function onCookieInitialize(GenericEvent $e) { $cookies = $e->getSubject(); $cookie = $cookies[0]['Name'] . '=' . $cookies[0]['Value']; $this->output->writeln(sprintf('cookie.initialize: <comment>%s</comment>', $cookie)); $this->sleep(); } public function onCaptchaDownload(Event $e) { $this->output->writeln('captcha.download'); } public function onCaptchaDecode(GenericEvent $e) { $this->output->writeln(sprintf('captcha.decode: <comment>%s</comment>', $e->getSubject())); } public function onSearchSend(GenericEvent $e) { /* @var $response Response */ $response = $e->getSubject(); $this->output->writeln(sprintf('search.send: <comment>%s</comment>', $response->getStatusCode() . ' ' . $response->getReasonPhrase())); } public function onErrorReturn(GenericEvent $e) { $this->output->writeln(sprintf('error.return: <error>%s</error>', $e->getSubject())); $this->sleep(); } public function sleep() { $seconds = rand($this->input->getOption('min-sleep'), $this->input->getOption('max-sleep')); $this->output->writeln(sprintf('sleep <comment>%s</comment> seconds', $seconds)); sleep($seconds); } }
maidmaid/webot
src/Maidmaid/WebotBundle/Event/SearcherSubscriber.php
PHP
mit
1,795
class CreateCoursesCompleteds < ActiveRecord::Migration def self.up create_table :courses_completeds do |t| t.timestamps end end def self.down drop_table :courses_completeds end end
ponzao/opal
db/migrate/20091210230319_create_courses_completeds.rb
Ruby
mit
210
/* ======================================== ID: mathema6 TASK: LANG: C++14 * File Name : A.cpp * Creation Date : 10-04-2021 * Last Modified : Tue 13 Apr 2021 11:12:59 PM CEST * Created By : Karel Ha <mathemage@gmail.com> * URL : https://codingcompetitions.withgoogle.com/codejam/round/000000000043585d/00000000007549e5 * Points/Time : * ~2h20m * 2h30m -> practice mode already :-( :-( :-( * * upsolve: * + 7m20s = 7m20s * + 1m20s = 8m40s * + 2m30s = 11m10s * +~80m10s = 1h31m20s * * Total/ETA : * 15m :-/ :-( * 15m (upsolve) * * Status : * S WA - :-( * S AC WA :-/ * S AC TLE :-O * S AC TLE :-/ * S AC RE (probed while-loop with exit code -> RE) * S AC AC YESSSSSSSSSSSSSSSSS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * ==========================================*/ #include <string> #define PROBLEMNAME "TASK_PLACEHOLDER_FOR_VIM" #include <bits/stdc++.h> using namespace std; #define endl "\n" #define REP(i,n) for(int i=0;i<(n);i++) #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define FORD(i,a,b) for(int i=(a);i>=(b);i--) #define ALL(A) (A).begin(), (A).end() #define REVALL(A) (A).rbegin(), (A).rend() #define F first #define S second #define PB push_back #define MP make_pair #define MTP make_tuple #define MINUPDATE(A,B) A = min((A), (B)); #define MAXUPDATE(A,B) A = max((A), (B)); #define SGN(X) ((X) ? ( (X)>0?1:-1 ) : 0) #define CONTAINS(S,E) ((S).find(E) != (S).end()) #define SZ(x) ((int) (x).size()) using ll = long long; using ul = unsigned long long; using llll = pair<ll, ll>; using ulul = pair<ul, ul>; #ifdef ONLINE_JUDGE #undef MATHEMAGE_DEBUG #endif #ifdef MATHEMAGE_DEBUG #define MSG(a) cerr << "> " << (#a) << ": " << (a) << endl; #define MSG_VEC_VEC(v) cerr << "> " << (#v) << ":\n" << (v) << endl; #define MSG_VEC_PAIRS(v) print_vector_pairs((v), (#v)); #define LINESEP1 cerr << "----------------------------------------------- " << endl; #define LINESEP2 cerr << "_________________________________________________________________" << endl; #else #define MSG(a) #define MSG_VEC_VEC(v) #define MSG_VEC_PAIRS(v) #define LINESEP1 #define LINESEP2 #endif ostream& operator<<(ostream& os, const vector<string> & vec) { os << endl; for (const auto & s: vec) os << s << endl; return os; } template<typename T> ostream& operator<<(ostream& os, const vector<T> & vec) { for (const auto & x: vec) os << x << " "; return os; } template<typename T> ostream& operator<<(ostream& os, const vector<vector<T>> & vec) { for (const auto & v: vec) os << v << endl; return os; } template<typename T> inline ostream& operator<<(ostream& os, const vector<vector<vector<T>>> & vec) { for (const auto & row: vec) { for (const auto & col: row) { os << "[ " << col << "] "; } os << endl; } return os; } template<typename T> ostream& operator<<(ostream& os, const set<T>& vec) { os << "{ | "; for (const auto & x: vec) os << x << "| "; os << "}"; return os; } template<typename T1, typename T2> void print_vector_pairs(const vector<pair<T1, T2>> & vec, const string & name) { cerr << "> " << name << ": "; for (const auto & x: vec) cerr << "(" << x.F << ", " << x.S << ")\t"; cerr << endl; } template<typename T> inline bool bounded(const T & x, const T & u, const T & l=0) { return min(l,u)<=x && x<max(l,u); } const int CLEAN = -1; const int UNDEF = -42; const long long MOD = 1000000007; const double EPS = 1e-8; const int INF = INT_MAX; const long long INF_LL = LLONG_MAX; const long long INF_ULL = ULLONG_MAX; const vector<int> DX4 = {-1, 0, 1, 0}; const vector<int> DY4 = { 0, 1, 0, -1}; const vector<pair<int,int>> DXY4 = { {-1,0}, {0,1}, {1,0}, {0,-1} }; const vector<int> DX8 = {-1, -1, -1, 0, 0, 1, 1, 1}; const vector<int> DY8 = {-1, 0, 1, -1, 1, -1, 0, 1}; const vector<pair<int,int>> DXY8 = { {-1,-1}, {-1,0}, {-1,1}, { 0,-1}, { 0,1}, { 1,-1}, { 1,0}, { 1,1} }; string atLeast, newNum; void solve() { int N; cin >> N; MSG(N); vector<string> X(N); REP(i,N) { MSG(i); cin >> X[i]; } MSG(X); cerr.flush(); int result = 0; FOR(i,1,N-1) { MSG(i); cerr.flush(); if (SZ(X[i-1])<SZ(X[i])) { continue; } if (SZ(X[i-1])==SZ(X[i]) && X[i-1]<X[i]) { continue; } atLeast=X[i-1]; bool only9s=true; FORD(pos,SZ(atLeast)-1,0) { if (atLeast[pos]=='9') { atLeast[pos]='0'; } else { atLeast[pos]++; only9s=false; break; } } // if (count(ALL(atLeast), '0')==SZ(atLeast)) { if (only9s) { atLeast='1'+atLeast; } MSG(X[i-1]); MSG(atLeast); cerr.flush(); newNum=X[i]; if (atLeast.substr(0,SZ(X[i])) == X[i]) { // it's a prefix newNum = atLeast; } else { while (SZ(newNum)<SZ(atLeast)) { newNum+='0'; } if (newNum<atLeast) { newNum+='0'; } } result+=SZ(newNum) - SZ(X[i]); MSG(X[i]); MSG(newNum); MSG(result); cerr.flush(); X[i]=newNum; newNum.clear(); atLeast.clear(); LINESEP1; } MSG(X); cerr.flush(); cout << result << endl; X.clear(); MSG(X); cerr.flush(); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int cases = 1; cin >> cases; FOR(tt,1,cases) { cout << "Case #" << tt << ": "; cout.flush(); cerr.flush(); solve(); LINESEP2; cout.flush(); cerr.flush(); } return 0; }
mathemage/CompetitiveProgramming
gcodejam/2021/round-1A/A/A.cpp
C++
mit
5,478
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: java.security.cert.PKIXCertPathBuilderResult ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_SECURITY_CERT_PKIXCERTPATHBUILDERRESULT_HPP_DECL #define J2CPP_JAVA_SECURITY_CERT_PKIXCERTPATHBUILDERRESULT_HPP_DECL namespace j2cpp { namespace java { namespace lang { class String; } } } namespace j2cpp { namespace java { namespace security { class PublicKey; } } } namespace j2cpp { namespace java { namespace security { namespace cert { class CertPath; } } } } namespace j2cpp { namespace java { namespace security { namespace cert { class PKIXCertPathValidatorResult; } } } } namespace j2cpp { namespace java { namespace security { namespace cert { class CertPathBuilderResult; } } } } namespace j2cpp { namespace java { namespace security { namespace cert { class PolicyNode; } } } } namespace j2cpp { namespace java { namespace security { namespace cert { class TrustAnchor; } } } } #include <java/lang/String.hpp> #include <java/security/PublicKey.hpp> #include <java/security/cert/CertPath.hpp> #include <java/security/cert/CertPathBuilderResult.hpp> #include <java/security/cert/PKIXCertPathValidatorResult.hpp> #include <java/security/cert/PolicyNode.hpp> #include <java/security/cert/TrustAnchor.hpp> namespace j2cpp { namespace java { namespace security { namespace cert { class PKIXCertPathBuilderResult; class PKIXCertPathBuilderResult : public object<PKIXCertPathBuilderResult> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) explicit PKIXCertPathBuilderResult(jobject jobj) : object<PKIXCertPathBuilderResult>(jobj) { } operator local_ref<java::security::cert::PKIXCertPathValidatorResult>() const; operator local_ref<java::security::cert::CertPathBuilderResult>() const; PKIXCertPathBuilderResult(local_ref< java::security::cert::CertPath > const&, local_ref< java::security::cert::TrustAnchor > const&, local_ref< java::security::cert::PolicyNode > const&, local_ref< java::security::PublicKey > const&); local_ref< java::security::cert::CertPath > getCertPath(); local_ref< java::lang::String > toString(); }; //class PKIXCertPathBuilderResult } //namespace cert } //namespace security } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_SECURITY_CERT_PKIXCERTPATHBUILDERRESULT_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_SECURITY_CERT_PKIXCERTPATHBUILDERRESULT_HPP_IMPL #define J2CPP_JAVA_SECURITY_CERT_PKIXCERTPATHBUILDERRESULT_HPP_IMPL namespace j2cpp { java::security::cert::PKIXCertPathBuilderResult::operator local_ref<java::security::cert::PKIXCertPathValidatorResult>() const { return local_ref<java::security::cert::PKIXCertPathValidatorResult>(get_jobject()); } java::security::cert::PKIXCertPathBuilderResult::operator local_ref<java::security::cert::CertPathBuilderResult>() const { return local_ref<java::security::cert::CertPathBuilderResult>(get_jobject()); } java::security::cert::PKIXCertPathBuilderResult::PKIXCertPathBuilderResult(local_ref< java::security::cert::CertPath > const &a0, local_ref< java::security::cert::TrustAnchor > const &a1, local_ref< java::security::cert::PolicyNode > const &a2, local_ref< java::security::PublicKey > const &a3) : object<java::security::cert::PKIXCertPathBuilderResult>( call_new_object< java::security::cert::PKIXCertPathBuilderResult::J2CPP_CLASS_NAME, java::security::cert::PKIXCertPathBuilderResult::J2CPP_METHOD_NAME(0), java::security::cert::PKIXCertPathBuilderResult::J2CPP_METHOD_SIGNATURE(0) >(a0, a1, a2, a3) ) { } local_ref< java::security::cert::CertPath > java::security::cert::PKIXCertPathBuilderResult::getCertPath() { return call_method< java::security::cert::PKIXCertPathBuilderResult::J2CPP_CLASS_NAME, java::security::cert::PKIXCertPathBuilderResult::J2CPP_METHOD_NAME(1), java::security::cert::PKIXCertPathBuilderResult::J2CPP_METHOD_SIGNATURE(1), local_ref< java::security::cert::CertPath > >(get_jobject()); } local_ref< java::lang::String > java::security::cert::PKIXCertPathBuilderResult::toString() { return call_method< java::security::cert::PKIXCertPathBuilderResult::J2CPP_CLASS_NAME, java::security::cert::PKIXCertPathBuilderResult::J2CPP_METHOD_NAME(2), java::security::cert::PKIXCertPathBuilderResult::J2CPP_METHOD_SIGNATURE(2), local_ref< java::lang::String > >(get_jobject()); } J2CPP_DEFINE_CLASS(java::security::cert::PKIXCertPathBuilderResult,"java/security/cert/PKIXCertPathBuilderResult") J2CPP_DEFINE_METHOD(java::security::cert::PKIXCertPathBuilderResult,0,"<init>","(Ljava/security/cert/CertPath;Ljava/security/cert/TrustAnchor;Ljava/security/cert/PolicyNode;Ljava/security/PublicKey;)V") J2CPP_DEFINE_METHOD(java::security::cert::PKIXCertPathBuilderResult,1,"getCertPath","()Ljava/security/cert/CertPath;") J2CPP_DEFINE_METHOD(java::security::cert::PKIXCertPathBuilderResult,2,"toString","()Ljava/lang/String;") } //namespace j2cpp #endif //J2CPP_JAVA_SECURITY_CERT_PKIXCERTPATHBUILDERRESULT_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
kakashidinho/HQEngine
ThirdParty-mod/java2cpp/java/security/cert/PKIXCertPathBuilderResult.hpp
C++
mit
5,433
<?php namespace Richpolis\ShoppingCartBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Producto * * @ORM\Table() * @ORM\Entity(repositoryClass="Richpolis\ShoppingCartBundle\Repository\ProductoRepository") */ class Producto { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="nombre", type="string", length=255) */ private $nombre; /** * @var string * * @ORM\Column(name="imagen", type="string", length=255) */ private $imagen; /** * @var string * * @ORM\Column(name="precio", type="decimal") */ private $precio; /** * @var integer * * @ORM\Column(name="position", type="integer") */ private $position; /** * @var boolean * * @ORM\Column(name="isActive", type="boolean") */ private $isActive; /** * @var string * * @ORM\Column(name="slug", type="string", length=255) */ private $slug; /** * @var integer * * @ORM\Column(name="categoria", type="integer") */ private $categoria; /** * @var \DateTime * * @ORM\Column(name="createdAt", type="datetime") */ private $createdAt; /** * @var \DateTime * * @ORM\Column(name="updatedAt", type="datetime") */ private $updatedAt; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nombre * * @param string $nombre * @return Producto */ public function setNombre($nombre) { $this->nombre = $nombre; return $this; } /** * Get nombre * * @return string */ public function getNombre() { return $this->nombre; } /** * Set imagen * * @param string $imagen * @return Producto */ public function setImagen($imagen) { $this->imagen = $imagen; return $this; } /** * Get imagen * * @return string */ public function getImagen() { return $this->imagen; } /** * Set precio * * @param string $precio * @return Producto */ public function setPrecio($precio) { $this->precio = $precio; return $this; } /** * Get precio * * @return string */ public function getPrecio() { return $this->precio; } /** * Set position * * @param integer $position * @return Producto */ public function setPosition($position) { $this->position = $position; return $this; } /** * Get position * * @return integer */ public function getPosition() { return $this->position; } /** * Set isActive * * @param boolean $isActive * @return Producto */ public function setIsActive($isActive) { $this->isActive = $isActive; return $this; } /** * Get isActive * * @return boolean */ public function getIsActive() { return $this->isActive; } /** * Set slug * * @param string $slug * @return Producto */ public function setSlug($slug) { $this->slug = $slug; return $this; } /** * Get slug * * @return string */ public function getSlug() { return $this->slug; } /** * Set categoria * * @param integer $categoria * @return Producto */ public function setCategoria($categoria) { $this->categoria = $categoria; return $this; } /** * Get categoria * * @return integer */ public function getCategoria() { return $this->categoria; } /** * Set createdAt * * @param \DateTime $createdAt * @return Producto */ public function setCreatedAt($createdAt) { $this->createdAt = $createdAt; return $this; } /** * Get createdAt * * @return \DateTime */ public function getCreatedAt() { return $this->createdAt; } /** * Set updatedAt * * @param \DateTime $updatedAt * @return Producto */ public function setUpdatedAt($updatedAt) { $this->updatedAt = $updatedAt; return $this; } /** * Get updatedAt * * @return \DateTime */ public function getUpdatedAt() { return $this->updatedAt; } }
richpolis/sf2Maldivino
src/Richpolis/ShoppingCartBundle/Entity/Producto.php
PHP
mit
4,812
""" Running the template pre-processor standalone. Input: Templated Antimony model (stdin) Output: Expanded Antimony model (stdout) """ import fileinput import os import sys directory = os.path.dirname(os.path.abspath(__file__)) path = os.path.join(directory, "TemplateSB") sys.path.append(path) from template_processor import TemplateProcessor template_stg = '' for line in fileinput.input(): template_stg += "\n" + line processor = TemplateProcessor(template_stg) expanded_stg = processor.do() sys.stdout.write(expanded_stg)
BioModelTools/TemplateSB
run.py
Python
mit
543
import React, { useState } from 'react'; import { registerComponent, Components } from '../../../lib/vulcan-lib'; import MoreVertIcon from '@material-ui/icons/MoreVert'; import Menu from '@material-ui/core/Menu'; import { useCurrentUser } from '../../common/withUser'; import { useTracking } from "../../../lib/analyticsEvents"; const styles = (theme: ThemeType): JssStyles => ({ icon: { cursor: "pointer", fontSize:"1.4rem" }, menu: { position:"absolute", right:0, top:0, zIndex: theme.zIndexes.commentsMenu, } }) const CommentsMenu = ({classes, className, comment, post, showEdit, icon}: { classes: ClassesType, className?: string, comment: CommentsList, post?: PostsMinimumInfo, showEdit: ()=>void, icon?: any, }) => { const [anchorEl, setAnchorEl] = useState<any>(null); // Render menu-contents if the menu has ever been opened (keep rendering // contents when closed after open, because of closing animation). const [everOpened, setEverOpened] = useState(false); const currentUser = useCurrentUser(); const { captureEvent } = useTracking({eventType: "commentMenuClicked", eventProps: {commentId: comment._id, itemType: "comment"}}) if (!currentUser) return null return ( <span className={className}> <span onClick={event => { captureEvent("commentMenuClicked", {open: true}) setAnchorEl(event.currentTarget) setEverOpened(true); }}> {icon ? icon : <MoreVertIcon className={classes.icon}/>} </span> <Menu onClick={event => { captureEvent("commentMenuClicked", {open: false}) setAnchorEl(null) }} open={Boolean(anchorEl)} anchorEl={anchorEl} > {everOpened && <Components.CommentActions currentUser={currentUser} comment={comment} post={post} showEdit={showEdit} />} </Menu> </span> ) } const CommentsMenuComponent = registerComponent('CommentsMenu', CommentsMenu, {styles}); declare global { interface ComponentTypes { CommentsMenu: typeof CommentsMenuComponent, } }
Discordius/Telescope
packages/lesswrong/components/comments/CommentsItem/CommentsMenu.tsx
TypeScript
mit
2,151
'use strict'; const Joi = require('joi'); const uuid = require('uuid'); const reqUtils = require('../utils/requestUtils'); const R = require('ramda'); //fixme: allow unknown fields and just require absolutely mandatory ones const cucumberSchema = Joi.array().items(Joi.object().keys({ id: Joi.string().required(), name: Joi.string().required(), description: Joi.string(), line: Joi.number().integer(), keyword: Joi.string(), uri: Joi.string(), elements: Joi.array().items(Joi.object().keys({ name: Joi.string().required(), id: Joi.string().required(), line: Joi.number().integer(), keyword: Joi.string(), description: Joi.string(), type: Joi.string().required(), steps: Joi.array().items(Joi.object().keys({ name: Joi.string(), line: Joi.number().integer(), keyword: Joi.string(), result: Joi.object().keys({ status: Joi.string(), duration: Joi.number().integer() }), match: Joi.object().keys({ location: Joi.string() }) })) })) })); module.exports = function (server, emitter) { server.route({ method: 'POST', path: '/upload/cucumber', config: { tags: ['upload'], payload: { //allow: ['multipart/form-data'], parse: true, output: 'stream' }, validate: { query: { evaluation: Joi.string().min(1).required(), evaluationTag: Joi.string().min(1).required(), subject: Joi.string().min(1).required() } } }, handler: function(request, reply) { return reqUtils.getObject(request, 'cucumber') .then(o => reqUtils.validateObject(o, cucumberSchema)) .then(report => { emitter.emit( 'uploads/cucumber', R.assoc('report', report, R.pick(['subject', 'evaluation', 'evaluationTag'], request.query)) ); return reply().code(202); }) // fixme: this will resolve even internal errors as 429's // break the initial processing (which returns 429 codes) // from the final one (which returns 5xx codes) .catch(e => { return reply(e.message).code(400); }); } }); };
dclucas/metrics-tracker
app/routes/cucumber-upload.js
JavaScript
mit
2,541
from bottle import route, default_app app = default_app() data = { "id": 78874, "seriesName": "Firefly", "aliases": [ "Serenity" ], "banner": "graphical/78874-g3.jpg", "seriesId": "7097", "status": "Ended", "firstAired": "2002-09-20", "network": "FOX (US)", "networkId": "", "runtime": "45", "genre": [ "Drama", "Science-Fiction" ], "overview": "In the far-distant future, Captain Malcolm \"Mal\" Reynolds is a renegade former brown-coat sergeant, now turned smuggler & rogue, " "who is the commander of a small spacecraft, with a loyal hand-picked crew made up of the first mate, Zoe Warren; the pilot Hoban \"Wash\" Washburn; " "the gung-ho grunt Jayne Cobb; the engineer Kaylee Frye; the fugitives Dr. Simon Tam and his psychic sister River. " "Together, they travel the far reaches of space in search of food, money, and anything to live on.", "lastUpdated": 1486759680, "airsDayOfWeek": "", "airsTime": "", "rating": "TV-14", "imdbId": "tt0303461", "zap2itId": "EP00524463", "added": "", "addedBy": None, "siteRating": 9.5, "siteRatingCount": 472, } @route('/api') def api(): return data
romanvm/WsgiBoostServer
benchmarks/test_app.py
Python
mit
1,229
import { Registration } from "./Models"; export class Container { private registrations: Array<Registration> = []; private createInstance<T extends object>(classType: {new (): T} | Function): T { return Reflect.construct(classType, []); } private isItemRegistered(item: any) : boolean { const registrationMatch = this.registrations.filter(registration => registration.RegisteredInterface == item || registration.RegisteredClass == item)[0]; return registrationMatch != null; } registerAbstraction<T, U extends T>(abstractClass: (new (...args: any[]) => T) | Function, implementedClass: { new (...args: any[]): U; }, singleton: boolean = false): Container { const existingRegistration = this.registrations .filter(existingRegistration => existingRegistration.RegisteredClass == implementedClass || existingRegistration.RegisteredInterface == abstractClass); if(this.isItemRegistered(abstractClass)) throw `You cannot register an abstract class twice`; if(this.isItemRegistered(implementedClass)) throw `You cannot register an implemented class twice`; const registration = new Registration(); registration.RegisteredClass = implementedClass; registration.RegisteredInterface = abstractClass; this.registrations.push(registration); return this; } registerClass<T>(implementedClass: { new (): T }, singleton: boolean = false): Container { if(this.isItemRegistered(implementedClass)) throw `You cannot register a class more than once`; const registration = new Registration(); registration.RegisteredClass = implementedClass; registration.SingletonReference = singleton ? this.createInstance(implementedClass) : null; this.registrations.push(registration); return this; } resolve<T>(itemToResolve: (new (...args: any[]) => T) | Function): T { const resolvedRegistration = this.registrations.filter(registration => registration.RegisteredClass == itemToResolve || registration.RegisteredInterface == itemToResolve)[0]; if(!resolvedRegistration) throw `No matching implementation was registered.`; return this.createInstance(resolvedRegistration.RegisteredClass as Function) as T; } } export const container: Container = new Container();
dunnweb/tinjector
src/Container.ts
TypeScript
mit
2,388
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Bundler.Infrastructure; using Bundler.Infrastructure.Server; namespace Bundler.Sources { public class StreamSource : ISource { public const string Tag = nameof(StreamSource); private readonly string[] _virtualFiles; public StreamSource(params string[] virtualFiles) { _virtualFiles = virtualFiles; Identifier = string.Join(";", virtualFiles.OrderBy(x => x.ToLower())); } public void Dispose() { } public bool AddItems(IBundleContext bundleContext, ICollection<ISourceItem> items, ICollection<string> watchPaths) { foreach (var virtualFile in _virtualFiles) { if (!virtualFile.StartsWith("~/", StringComparison.InvariantCultureIgnoreCase)) { bundleContext.Diagnostic.Log(LogLevel.Error, Tag, nameof(AddItems), $"Path should be virtual for ${virtualFile}!"); return false; } if (!bundleContext.VirtualPathProvider.FileExists(virtualFile)) { bundleContext.Diagnostic.Log(LogLevel.Error, Tag, nameof(AddItems), $"Can't find file {virtualFile}"); return false; } items.Add(new StreamSourceItem(virtualFile, bundleContext.VirtualPathProvider)); watchPaths.Add(virtualFile); } return true; } public string Identifier { get; } private class StreamSourceItem : ISourceItem { private readonly IBundleVirtualPathProvider _virtualPathProvider; public StreamSourceItem(string virtualFile, IBundleVirtualPathProvider virtualPathProvider) { _virtualPathProvider = virtualPathProvider; VirtualFile = virtualFile; } public string VirtualFile { get; } public string Get() { try { using (var stream = _virtualPathProvider.Open(VirtualFile)) { using (var streamReader = new StreamReader(stream)) { return streamReader.ReadToEnd(); } } } catch (Exception) { return null; } } public void Dispose() {} } } }
irii/Bundler
Bundler/Sources/StreamSource.cs
C#
mit
2,415
/* * The MIT License * * Copyright 2015 Sanket K. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package sortingexamples; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Sanket K */ public class SortingExamples { /** * @param args the command line arguments */ public static void main(String[] args) { SortingExamples obj = new SortingExamples(); List<Integer> data = new LinkedList<>(); // TODO add random numbers in a loop data.add(100); data.add(34); data.add(39); data.add(3); data.add(3); data.add(3); //System.out.println("Unsorted list = " + data); //if (obj.insertionSort(data)) { //System.out.println("Sorted list = " + data); //} int [] data2 = {3,5,6,7,8,9,2,2,1000,4111, 377, 178, 3726, 1, 9, 67754, 56425}; System.out.println("Unsorted = " + Arrays.toString(data2)); obj.quickSort(0, data2.length - 1, data2); System.out.println("Sorted = " + Arrays.toString(data2)); } public SortingExamples() { } private void dumpState(int j, List<Integer> list) { for(int i =0; i < list.size(); i++ ) { if (i == j) { System.out.print("(" + list.get(i) + ")"); }else { System.out.print(list.get(i)); } System.out.print(", "); } try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException ex) { Logger.getLogger(SortingExamples.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(""); } public boolean insertionSort(List<Integer> mylist) { if (null == mylist) { System.out.println("Cannot sort a null list"); return false; } if (mylist.isEmpty()) { System.out.println("Cannot sort an empty list"); return false; } for (int i = 1; i < mylist.size(); i++) { int j = i; int testvar = mylist.get(i); System.out.print("Testing " + testvar + ": "); dumpState(j, mylist); while (j > 0 && mylist.get(j-1) > testvar ) { System.out.println(mylist.get(j-1) + " > " + testvar); mylist.set(j, mylist.get(j-1)); //unsorted.set(j-1,0); j = j-1; //dumpState(testvar, data); } mylist.set(j, testvar); } return true; } public boolean shellSort(List<Integer> unsorted) { return false; } private void dump(int i, int j, int pivot, int[] d) { System.out.println(""); for (int k = 0; k < 40; k++) System.out.print("-"); System.out.println(""); int close = 0; for(int k=0; k < d.length; k++) { if (k == i) { System.out.print("i("); close++; } if (k == j) { System.out.print("j("); close++; } if (d[k] == pivot) { System.out.print("p("); close++; } System.out.print(d[k]); while(close > 0) { System.out.print(")"); close--; } System.out.print(", "); } System.out.println(""); } public boolean quickSort(int low, int high, int[] d) { int i = low, j = high; System.out.println("\n\nQuicksort called: low value = " + d[low] + " high value = " + d[high]); // Pivots can be selected many ways int p = low + (high - low)/2; int pivot = d[p]; System.out.println("pivot = " + pivot); while (i <= j) { dump(i, j, pivot, d); System.out.println("\ninc i until d[i]>pivot & dec j until d[j]<pivot"); while (d[i] < pivot) i++; while (d[j] > pivot) j--; dump(i, j, pivot, d); if (i <= j) { swap(i,j, d); System.out.println("\nSwap i & j"); dump(i, j, pivot, d); i++; j--; } } if (low < j) { System.out.println("low < j"); quickSort(low, j, d); } if (i < high) { System.out.println("i < high"); quickSort(i, high, d); } return false; } private void swap(int i, int j, int[] d) { int temp = d[i]; d[i] = d[j]; d[j] = temp; } }
hckrtst/TIJ
sortingExamples/src/sortingexamples/SortingExamples.java
Java
mit
6,022
<?php namespace Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\Config\FileLocator; class YamlDoctrineExtensionTest extends AbstractDoctrineExtensionTest { protected function loadFromFile(ContainerBuilder $container, $file) { $loadYaml = new YamlFileLoader($container, new FileLocator(__DIR__.'/Fixtures/config/yml')); $loadYaml->load($file.'.yml'); } }
gencer/DoctrineBundle
Tests/DependencyInjection/YamlDoctrineExtensionTest.php
PHP
mit
543
<?php namespace Moeketsi\AclAdminControlPanel\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; }
meccado/acl-admin-control-panel
src/Http/Controllers/Controller.php
PHP
mit
387
#!/usr/bin/env python # A Raspberry Pi GPIO based relay device import RPi.GPIO as GPIO from common.adafruit.Adafruit_MCP230xx.Adafruit_MCP230xx import Adafruit_MCP230XX class Relay(object): _mcp23017_chip = {} # Conceivably, we could have up to 8 of these as there are a possibility of 8 MCP chips on a bus. def __init__(self, mcp_pin, i2c_address=0x27): """ Initialize a relay :param mcp_pin: BCM gpio number that is connected to a relay :return: """ self.ON = 0 self.OFF = 1 self._i2c_address = i2c_address self._mcp_pin = mcp_pin if GPIO.RPI_REVISION == 1: i2c_busnum = 0 else: i2c_busnum = 1 if not self._mcp23017_chip.has_key(self._i2c_address): self._mcp23017_chip[self._i2c_address] = Adafruit_MCP230XX(busnum=i2c_busnum, address=self._i2c_address, num_gpios=16) self._relay = self._mcp23017_chip[self._i2c_address] self._relay.config(self._mcp_pin, self._relay.OUTPUT) self._relay.output(self._mcp_pin, self.OFF) self.state = self.OFF def set_state(self, state): """ Set the state of the relay. relay.ON, relay.OFF :param state: :return: """ if state == self.ON: self._relay.output(self._mcp_pin, self.ON) self.state = self.ON elif state == self.OFF: self._relay.output(self._mcp_pin, self.OFF) self.state = self.OFF def toggle(self): """ Toggle the state of a relay :return: """ if self.state == self.ON: self._relay.output(self._mcp_pin, self.OFF) self.state = self.OFF else: self._relay.output(self._mcp_pin, self.ON) self.state = self.ON def get_state(self): return self.state if __name__ == '__main__': import time pause = .15 for pin in range(16): print("Pin: %s" % pin) r = Relay(pin) r.set_state(r.ON) time.sleep(pause) r.set_state(r.OFF) time.sleep(pause) r.toggle() time.sleep(pause) r.toggle() time.sleep(pause) r1 = Relay(10) r2 = Relay(2) r3 = Relay(15) r1.set_state(r1.ON) print(r1._mcp_pin) r2.set_state(r2.ON) print(r2._mcp_pin) r3.set_state(r3.ON) print(r3._mcp_pin) time.sleep(1) r1.set_state(r1.OFF) r2.set_state(r2.OFF) r3.set_state(r3.OFF)
mecworks/garden_pi
common/relay.py
Python
mit
2,522
var accessToken="i7LM4k7JcSKs4ucCpxpgNPcs3i1kRbNKyUE8aPGKZzZWASagz9uZiuLgmgDgBJzY"; $(window).load(function() { $('#pseudo_submit').click(function() { NProgress.start(); $.ajax({ type: "POST", url: "../db-app/signdown.php", dataType: 'text', data: { password: $("#basic_pass").val() }, complete: function(xhr, statusText){ NProgress.done(); }, success: function (res) { console.log(res); if(res.indexOf("ERR")==-1) { delete_schedule(res); } else { new PNotify({ title: 'Error :(', text: "Something went wrong", type: 'error', styling: 'bootstrap3' }); } } }); }); }); function delete_schedule(id) { NProgress.start(); var del_url = "https://api.whenhub.com/api/schedules/"+id+"?access_token="+accessToken; $.ajax({ type: "DELETE", url: del_url, complete: function(xhr, statusText){ NProgress.done(); console.log(xhr.status+" "+statusText); }, success: function (data) { console.log(data); window.location.href = "account_deleted.php"; }, error: function(xhr, statusText, err){ console.log(xhr); console.log(statusText); console.log(err); } }); }
mehamasum/ElegantResume
dashboard/whenhub_api/delete.js
JavaScript
mit
1,625
package net.glowstone.io.entity; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; import net.glowstone.entity.AttributeManager; import net.glowstone.entity.AttributeManager.Property; import net.glowstone.entity.GlowLivingEntity; import net.glowstone.entity.objects.GlowLeashHitch; import net.glowstone.io.nbt.NbtSerialization; import net.glowstone.util.InventoryUtil; import net.glowstone.util.nbt.CompoundTag; import org.bukkit.Location; import org.bukkit.attribute.AttributeModifier; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LeashHitch; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; public abstract class LivingEntityStore<T extends GlowLivingEntity> extends EntityStore<T> { public LivingEntityStore(Class<T> clazz, String type) { super(clazz, type); } public LivingEntityStore(Class<T> clazz, EntityType type) { super(clazz, type); } // these tags that apply to living entities only are documented as global: // - short "Air" // - string "CustomName" // - bool "CustomNameVisible" // todo: the following tags // - float "AbsorptionAmount" // - short "HurtTime" // - int "HurtByTimestamp" // - short "DeathTime" // - bool "PersistenceRequired" // on ActiveEffects, bool "ShowParticles" @Override public void load(T entity, CompoundTag compound) { super.load(entity, compound); compound.readShort("Air", entity::setRemainingAir); compound.readString("CustomName", entity::setCustomName); compound.readBoolean("CustomNameVisible", entity::setCustomNameVisible); if (!compound.readFloat("HealF", entity::setHealth)) { compound.readShort("Health", entity::setHealth); } compound.readShort("AttackTime", entity::setNoDamageTicks); compound.readBoolean("FallFlying", entity::setFallFlying); compound.iterateCompoundList("ActiveEffects", effect -> { // should really always have every field, but be forgiving if possible if (!effect.isByte("Id") || !effect.isInt("Duration")) { return; } PotionEffectType type = PotionEffectType.getById(effect.getByte("Id")); int duration = effect.getInt("Duration"); if (type == null || duration < 0) { return; } final int amplifier = compound.tryGetInt("Amplifier").orElse(0); boolean ambient = compound.getBoolean("Ambient", false); // bool "ShowParticles" entity.addPotionEffect(new PotionEffect(type, duration, amplifier, ambient), true); }); EntityEquipment equip = entity.getEquipment(); if (equip != null) { loadEquipment(entity, equip, compound); } compound.readBoolean("CanPickUpLoot", entity::setCanPickupItems); AttributeManager am = entity.getAttributeManager(); compound.iterateCompoundList("Attributes", tag -> { if (!tag.isString("Name") || !tag.isDouble("Base")) { return; } List<AttributeModifier> modifiers = new ArrayList<>(); tag.iterateCompoundList("Modifiers", modifierTag -> { if (modifierTag.isDouble("Amount") && modifierTag.isString("Name") && modifierTag.isInt("Operation") && modifierTag.isLong("UUIDLeast") && modifierTag.isLong("UUIDMost")) { modifiers.add(new AttributeModifier( new UUID(modifierTag.getLong("UUIDLeast"), modifierTag.getLong("UUIDMost")), modifierTag.getString("Name"), modifierTag.getDouble("Amount"), AttributeModifier.Operation.values()[modifierTag.getInt("Operation")])); } }); AttributeManager.Key key = AttributeManager.Key.fromName(tag.getString("Name")); am.setProperty(key, tag.getDouble("Base"), modifiers); }); Optional<CompoundTag> maybeLeash = compound.tryGetCompound("Leash"); if (maybeLeash.isPresent()) { CompoundTag leash = maybeLeash.get(); if (!leash.readUuid("UUIDMost", "UUIDLeast", entity::setLeashHolderUniqueId) && leash.isInt("X") && leash.isInt("Y") && leash.isInt("Z")) { int x = leash.getInt("X"); int y = leash.getInt("Y"); int z = leash.getInt("Z"); LeashHitch leashHitch = GlowLeashHitch .getLeashHitchAt(new Location(entity.getWorld(), x, y, z).getBlock()); entity.setLeashHolder(leashHitch); } } else { compound.readBoolean("Leashed", leashSet -> { if (leashSet) { // We know that there was something leashed, but not what entity it was // This can happen, when for example Minecart got leashed // We still have to make sure that we drop a Leash Item entity.setLeashHolderUniqueId(UUID.randomUUID()); } }); } } private void loadEquipment(T entity, EntityEquipment equip, CompoundTag compound) { // Deprecated since 15w31a, left here for compatibilty for now compound.readCompoundList("Equipment", list -> { equip.setItemInMainHand(getItem(list, 0)); equip.setBoots(getItem(list, 1)); equip.setLeggings(getItem(list, 2)); equip.setChestplate(getItem(list, 3)); equip.setHelmet(getItem(list, 4)); }); // Deprecated since 15w31a, left here for compatibilty for now compound.readFloatList("DropChances", list -> { equip.setItemInMainHandDropChance(getOrDefault(list, 0, 1f)); equip.setBootsDropChance(getOrDefault(list, 1, 1f)); equip.setLeggingsDropChance(getOrDefault(list, 2, 1f)); equip.setChestplateDropChance(getOrDefault(list, 3, 1f)); equip.setHelmetDropChance(getOrDefault(list, 4, 1f)); }); compound.readCompoundList("HandItems", list -> { equip.setItemInMainHand(getItem(list, 0)); equip.setItemInOffHand(getItem(list, 1)); }); compound.readCompoundList("ArmorItems", list -> { equip.setBoots(getItem(list, 0)); equip.setLeggings(getItem(list, 1)); equip.setChestplate(getItem(list, 2)); equip.setHelmet(getItem(list, 3)); }); // set of dropchances on a player throws an UnsupportedOperationException if (!(entity instanceof Player)) { compound.readFloatList("HandDropChances", list -> { equip.setItemInMainHandDropChance(getOrDefault(list, 0, 1f)); equip.setItemInOffHandDropChance(getOrDefault(list, 1, 1f)); }); compound.readFloatList("ArmorDropChances", list -> { equip.setBootsDropChance(getOrDefault(list, 0, 1f)); equip.setLeggingsDropChance(getOrDefault(list, 1, 1f)); equip.setChestplateDropChance(getOrDefault(list, 2, 1f)); equip.setHelmetDropChance(getOrDefault(list, 3, 1f)); }); } } private ItemStack getItem(List<CompoundTag> list, int index) { if (list == null) { return InventoryUtil.createEmptyStack(); } if (index >= list.size()) { return InventoryUtil.createEmptyStack(); } return NbtSerialization.readItem(list.get(index)); } private float getOrDefault(List<Float> list, int index, float defaultValue) { if (list == null) { return defaultValue; } if (index >= list.size()) { return defaultValue; } return list.get(index); } @Override public void save(T entity, CompoundTag tag) { super.save(entity, tag); tag.putShort("Air", entity.getRemainingAir()); if (entity.getCustomName() != null && !entity.getCustomName().isEmpty()) { tag.putString("CustomName", entity.getCustomName()); tag.putBool("CustomNameVisible", entity.isCustomNameVisible()); } tag.putFloat("HealF", entity.getHealth()); tag.putShort("Health", (int) entity.getHealth()); tag.putShort("AttackTime", entity.getNoDamageTicks()); tag.putBool("FallFlying", entity.isFallFlying()); Map<String, Property> properties = entity.getAttributeManager().getAllProperties(); if (!properties.isEmpty()) { List<CompoundTag> attributes = new ArrayList<>(properties.size()); properties.forEach((key, property) -> { CompoundTag attribute = new CompoundTag(); attribute.putString("Name", key); attribute.putDouble("Base", property.getValue()); Collection<AttributeModifier> modifiers = property.getModifiers(); if (modifiers != null && !modifiers.isEmpty()) { List<CompoundTag> modifierTags = modifiers.stream().map(modifier -> { CompoundTag modifierTag = new CompoundTag(); modifierTag.putDouble("Amount", modifier.getAmount()); modifierTag.putString("Name", modifier.getName()); modifierTag.putInt("Operation", modifier.getOperation().ordinal()); UUID uuid = modifier.getUniqueId(); modifierTag.putLong("UUIDLeast", uuid.getLeastSignificantBits()); modifierTag.putLong("UUIDMost", uuid.getMostSignificantBits()); return modifierTag; }).collect(Collectors.toList()); attribute.putCompoundList("Modifiers", modifierTags); } attributes.add(attribute); }); tag.putCompoundList("Attributes", attributes); } List<CompoundTag> effects = new LinkedList<>(); for (PotionEffect effect : entity.getActivePotionEffects()) { CompoundTag effectTag = new CompoundTag(); effectTag.putByte("Id", effect.getType().getId()); effectTag.putByte("Amplifier", effect.getAmplifier()); effectTag.putInt("Duration", effect.getDuration()); effectTag.putBool("Ambient", effect.isAmbient()); effectTag.putBool("ShowParticles", true); effects.add(effectTag); } tag.putCompoundList("ActiveEffects", effects); EntityEquipment equip = entity.getEquipment(); if (equip != null) { tag.putCompoundList("HandItems", Arrays.asList( NbtSerialization.writeItem(equip.getItemInMainHand(), -1), NbtSerialization.writeItem(equip.getItemInOffHand(), -1) )); tag.putCompoundList("ArmorItems", Arrays.asList( NbtSerialization.writeItem(equip.getBoots(), -1), NbtSerialization.writeItem(equip.getLeggings(), -1), NbtSerialization.writeItem(equip.getChestplate(), -1), NbtSerialization.writeItem(equip.getHelmet(), -1) )); tag.putFloatList("HandDropChances", Arrays.asList( equip.getItemInMainHandDropChance(), equip.getItemInOffHandDropChance() )); tag.putFloatList("ArmorDropChances", Arrays.asList( equip.getBootsDropChance(), equip.getLeggingsDropChance(), equip.getChestplateDropChance(), equip.getHelmetDropChance() )); } tag.putBool("CanPickUpLoot", entity.getCanPickupItems()); tag.putBool("Leashed", entity.isLeashed()); if (entity.isLeashed()) { Entity leashHolder = entity.getLeashHolder(); CompoundTag leash = new CompoundTag(); // "Non-living entities excluding leashes will not persist as leash holders." // The empty Leash tag is still persisted tough if (leashHolder instanceof LeashHitch) { Location location = leashHolder.getLocation(); leash.putInt("X", location.getBlockX()); leash.putInt("Y", location.getBlockY()); leash.putInt("Z", location.getBlockZ()); } else if (leashHolder instanceof LivingEntity) { leash.putLong("UUIDMost", entity.getUniqueId().getMostSignificantBits()); leash.putLong("UUIDLeast", entity.getUniqueId().getLeastSignificantBits()); } tag.putCompound("Leash", leash); } } }
GlowstoneMC/GlowstonePlusPlus
src/main/java/net/glowstone/io/entity/LivingEntityStore.java
Java
mit
13,397
<?php switch ($page){ case 'psd-files': $subtitle = ' - PSD files included'; break; case 'changelog': $subtitle = ' - Changelog'; break; case 'assets': $subtitle = ' - Assets'; break; default: $subtitle = ''; } ?> <!DOCTYPE HTML> <html> <head> <title>My Heaven - Online Booking PSD Template<?php echo $subtitle; ?></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="My Heaven is a clean and complete booking PSD template ideal for hotels, guest houses, villas and more." /> <meta name="keywords" content="availability, book, booking, calendar, holiday, hostel, hotel, rate, rent, reservation, room, schedule, travel, vacation, villa" /> <?php include_once('../libraries/php/assets.php'); ?> <?php include_once('../libraries/php/google-analytics.php'); ?> </head> <body> <div id="wrapper"> <div id="header"> <h1>My Heaven - Online Booking PSD Template</h1> </div>
dotonpaper/envato-help
my-heaven-online-booking-psd-template/header.php
PHP
mit
1,163
<?php /* * Copyright (c) 2012, Christoph Mewes, http://www.xrstf.de/ * * This file is released under the terms of the MIT license. You can find the * complete text in the attached LICENSE file or online at: * * http://www.opensource.org/licenses/mit-license.php */ /** * Generated result class for `hg root` * * @generated * @see http://selenic.com/hg/help/root * @package libhg.Command.Root */ class libhg_Command_Root_Result { /** * command output * * @var string */ public $output; /** * command return code * * @var int */ public $code; /** * Constructor * * @param string $output command's output * @param int $code command's return code */ public function __construct($output, $code) { $this->output = $output; $this->code = $code; } }
xrstf/libhg
libhg/Command/Root/Result.php
PHP
mit
808
// ----------------------------------------------------------------------- // <copyright file="BasePartnerComponent{TContext}.java" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- package com.microsoft.store.partnercenter; /** * Holds common partner component properties and behavior. All components should inherit from this class. The context * object type. */ public abstract class BasePartnerComponent<TContext> implements IPartnerComponent<TContext> { /** * Initializes a new instance of the {@link #BasePartnerComponent{TContext}} class. * * @param rootPartnerOperations The root partner operations that created this component. * @param componentContext A component context object to work with. */ protected BasePartnerComponent( IPartner rootPartnerOperations, TContext componentContext ) { if ( rootPartnerOperations == null ) { throw new NullPointerException( "rootPartnerOperations null" ); } this.setPartner( rootPartnerOperations ); this.setContext( componentContext ); } /** * Gets a reference to the partner operations instance that generated this component. */ private IPartner __Partner; @Override public IPartner getPartner() { return __Partner; } private void setPartner( IPartner value ) { __Partner = value; } /** * Gets the component context object. */ private TContext __Context; @Override public TContext getContext() { return __Context; } private void setContext( TContext value ) { __Context = value; } }
iogav/Partner-Center-Java-SDK
PartnerSdk/src/main/java/com/microsoft/store/partnercenter/BasePartnerComponent.java
Java
mit
1,795
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdFlashOn(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <polygon points="14 4 14 26 20 26 20 44 34 20 26 20 34 4" /> </IconBase> ); } export default MdFlashOn;
suitejs/suitejs
packages/icons/src/md/image/FlashOn.js
JavaScript
mit
273
/**************************************************************************** * ¹¦ ÄÜ£ºÒôƵÎļþ²Ù×÷Àà * * Ìí ¼Ó ÈË£ºÐ¡¿É * * Ìí¼Óʱ¼ä£º2015.01.17 12£º27 * * °æ±¾ÀàÐÍ£º³õʼ°æ±¾ * * ÁªÏµ·½Ê½£ºQQ-1035144170 * ****************************************************************************/ #include "StdAfx.h" #include "MusicOperat.h" CMusicOpreat::CMusicOpreat(HWND m_PWnd) { m_ParenhWnd=m_PWnd; nIndex=0; //²¥·ÅË÷Òý hStream=NULL; //²¥·ÅÁ÷ m_pBassMusic=NULL; m_pMainState=NULL; //²âÊÔ£º CLrcParse lrcPar; lrcPar.ReadFile(""); } CMusicOpreat::~CMusicOpreat(void) { if (hStream) { BASS_ChannelStop(hStream); hStream=NULL; } } //CMusicOpreat * CMusicOpreat::GetInstance() //{ // static CMusicOpreat _Instance; // // return &_Instance; //} void CMusicOpreat::InitDatas() { //³õʼ»¯ÉùÒô×é¼þ m_pBassMusic = CBassMusicEngine::GetInstance(); if ( m_pBassMusic == NULL ) { if ( SMessageBox(NULL,TEXT("ÉùÒôÒýÇæ³õʼ»¯Ê§°Ü"),_T("¾¯¸æ"),MB_OK|MB_ICONEXCLAMATION) == IDOK ) { PostQuitMessage(0); } } m_pBassMusic->Init(m_hWnd,this); } void CMusicOpreat::InsertMapInfo(int nNum, CString strPath, tagMusicInfo &pMuInfo) { //¼ÓÔØÎļþ HSTREAM hStream = m_pBassMusic->LoadFile(strPath); if ( hStream == -1 ) return; //»ñȡýÌå±êÇ© tagMusicInfo *pInfo = m_pBassMusic->GetInfo(hStream); //ͨ¹ýmapºÍListBox½áºÏ£¬Ò»Æð¹ÜÀí²¥·ÅÁбí tagMusicInfo *pMusicInfo = new tagMusicInfo; pMusicInfo->dwTime = pInfo->dwTime; pMusicInfo->hStream = pInfo->hStream; lstrcpyn(pMusicInfo->szArtist,pInfo->szArtist,CountArray(pMusicInfo->szArtist)); lstrcpyn(pMusicInfo->szTitle,pInfo->szTitle,CountArray(pMusicInfo->szTitle)); pMuInfo=*pMusicInfo; m_MusicManager.insert(pair<int,tagMusicInfo*>(nNum,pMusicInfo)); } void CMusicOpreat::OnButPrev() // ÉÏÒ»Çú { m_pBassMusic->Stop(hStream); nIndex--; if (nIndex<0) { nIndex=m_MusicManager.size()-1; } CMusicManagerMap::iterator iter = m_MusicManager.find(nIndex); if ( iter == m_MusicManager.end() ) return; hStream = iter->second->hStream; if( m_pBassMusic->Play(hStream,true) ) { int i=0; } } void CMusicOpreat::OnButPlay() // ²¥·Å { m_pBassMusic->Stop(hStream); CMusicManagerMap::iterator iter = m_MusicManager.find(nIndex); if ( iter == m_MusicManager.end() ) { return; }else { hStream = iter->second->hStream; if( m_pBassMusic->Play(hStream,/*(++nIndex!= nIndex) ? false : true)*/true )) { int i=0; } } } void CMusicOpreat::OnButPause() // ÔÝÍ£ { if ( m_pBassMusic->IsPlaying(hStream) == FALSE ) return; if( m_pBassMusic->Pause(hStream) ) { int i=0; } } void CMusicOpreat::OnButPlayNext() // ÏÂÒ»Çú { m_pBassMusic->Stop(hStream); nIndex++; if (nIndex>=m_MusicManager.size()) { nIndex=0; } CMusicManagerMap::iterator iter = m_MusicManager.find(nIndex); if ( iter == m_MusicManager.end() ) return; hStream = iter->second->hStream; if( m_pBassMusic->Play(hStream,true) ) { int i=0; } } void CMusicOpreat::OnStop() { //×Ô¶¯Çл»ÏÂÒ»Ê׸è OnButPlayNext(); //::PostMessage(GetContainer()->GetHostHwnd(), MSG_USER_SEARCH_DMTASKDLG, 0, 0); ::PostMessage(m_ParenhWnd,MSG_USER_REDRAW,0,0); }
wugh7125/ui
MusicPlayer/MusicOperat.cpp
C++
mit
3,575
/**************************************************************************** ** Meta object code from reading C++ file 'cookiejar.h' ** ** Created: Fri May 7 07:20:45 2010 ** by: The Qt Meta Object Compiler version 62 (Qt 4.6.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../cookiejar.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'cookiejar.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.6.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_CookieJar[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 4, 14, // methods 5, 34, // properties 2, 49, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: signature, parameters, type, tag, flags 11, 10, 10, 10, 0x05, // slots: signature, parameters, type, tag, flags 28, 10, 10, 10, 0x0a, 36, 10, 10, 10, 0x0a, 51, 10, 10, 10, 0x08, // properties: name, type, flags 71, 58, 0x0009510b, 95, 84, 0x0009510b, 118, 106, 0x0b095103, 133, 106, 0x0b095103, 148, 106, 0x0b095103, // enums: name, flags, count, data 58, 0x0, 3, 57, 84, 0x0, 3, 63, // enum data: key, value 171, uint(CookieJar::AcceptAlways), 184, uint(CookieJar::AcceptNever), 196, uint(CookieJar::AcceptOnlyFromSitesNavigatedTo), 227, uint(CookieJar::KeepUntilExpire), 243, uint(CookieJar::KeepUntilExit), 257, uint(CookieJar::KeepUntilTimeLimit), 0 // eod }; static const char qt_meta_stringdata_CookieJar[] = { "CookieJar\0\0cookiesChanged()\0clear()\0" "loadSettings()\0save()\0AcceptPolicy\0" "acceptPolicy\0KeepPolicy\0keepPolicy\0" "QStringList\0blockedCookies\0allowedCookies\0" "allowForSessionCookies\0AcceptAlways\0" "AcceptNever\0AcceptOnlyFromSitesNavigatedTo\0" "KeepUntilExpire\0KeepUntilExit\0" "KeepUntilTimeLimit\0" }; const QMetaObject CookieJar::staticMetaObject = { { &QNetworkCookieJar::staticMetaObject, qt_meta_stringdata_CookieJar, qt_meta_data_CookieJar, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &CookieJar::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *CookieJar::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *CookieJar::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CookieJar)) return static_cast<void*>(const_cast< CookieJar*>(this)); return QNetworkCookieJar::qt_metacast(_clname); } int CookieJar::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QNetworkCookieJar::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: cookiesChanged(); break; case 1: clear(); break; case 2: loadSettings(); break; case 3: save(); break; default: ; } _id -= 4; } #ifndef QT_NO_PROPERTIES else if (_c == QMetaObject::ReadProperty) { void *_v = _a[0]; switch (_id) { case 0: *reinterpret_cast< AcceptPolicy*>(_v) = acceptPolicy(); break; case 1: *reinterpret_cast< KeepPolicy*>(_v) = keepPolicy(); break; case 2: *reinterpret_cast< QStringList*>(_v) = blockedCookies(); break; case 3: *reinterpret_cast< QStringList*>(_v) = allowedCookies(); break; case 4: *reinterpret_cast< QStringList*>(_v) = allowForSessionCookies(); break; } _id -= 5; } else if (_c == QMetaObject::WriteProperty) { void *_v = _a[0]; switch (_id) { case 0: setAcceptPolicy(*reinterpret_cast< AcceptPolicy*>(_v)); break; case 1: setKeepPolicy(*reinterpret_cast< KeepPolicy*>(_v)); break; case 2: setBlockedCookies(*reinterpret_cast< QStringList*>(_v)); break; case 3: setAllowedCookies(*reinterpret_cast< QStringList*>(_v)); break; case 4: setAllowForSessionCookies(*reinterpret_cast< QStringList*>(_v)); break; } _id -= 5; } else if (_c == QMetaObject::ResetProperty) { _id -= 5; } else if (_c == QMetaObject::QueryPropertyDesignable) { _id -= 5; } else if (_c == QMetaObject::QueryPropertyScriptable) { _id -= 5; } else if (_c == QMetaObject::QueryPropertyStored) { _id -= 5; } else if (_c == QMetaObject::QueryPropertyEditable) { _id -= 5; } else if (_c == QMetaObject::QueryPropertyUser) { _id -= 5; } #endif // QT_NO_PROPERTIES return _id; } // SIGNAL 0 void CookieJar::cookiesChanged() { QMetaObject::activate(this, &staticMetaObject, 0, 0); } static const uint qt_meta_data_CookieModel[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 13, 12, 12, 12, 0x08, 0 // eod }; static const char qt_meta_stringdata_CookieModel[] = { "CookieModel\0\0cookiesChanged()\0" }; const QMetaObject CookieModel::staticMetaObject = { { &QAbstractTableModel::staticMetaObject, qt_meta_stringdata_CookieModel, qt_meta_data_CookieModel, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &CookieModel::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *CookieModel::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *CookieModel::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CookieModel)) return static_cast<void*>(const_cast< CookieModel*>(this)); return QAbstractTableModel::qt_metacast(_clname); } int CookieModel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QAbstractTableModel::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: cookiesChanged(); break; default: ; } _id -= 1; } return _id; } static const uint qt_meta_data_CookiesDialog[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; static const char qt_meta_stringdata_CookiesDialog[] = { "CookiesDialog\0" }; const QMetaObject CookiesDialog::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_CookiesDialog, qt_meta_data_CookiesDialog, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &CookiesDialog::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *CookiesDialog::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *CookiesDialog::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CookiesDialog)) return static_cast<void*>(const_cast< CookiesDialog*>(this)); if (!strcmp(_clname, "Ui_CookiesDialog")) return static_cast< Ui_CookiesDialog*>(const_cast< CookiesDialog*>(this)); return QDialog::qt_metacast(_clname); } int CookiesDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } static const uint qt_meta_data_CookieExceptionsModel[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; static const char qt_meta_stringdata_CookieExceptionsModel[] = { "CookieExceptionsModel\0" }; const QMetaObject CookieExceptionsModel::staticMetaObject = { { &QAbstractTableModel::staticMetaObject, qt_meta_stringdata_CookieExceptionsModel, qt_meta_data_CookieExceptionsModel, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &CookieExceptionsModel::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *CookieExceptionsModel::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *CookieExceptionsModel::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CookieExceptionsModel)) return static_cast<void*>(const_cast< CookieExceptionsModel*>(this)); return QAbstractTableModel::qt_metacast(_clname); } int CookieExceptionsModel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QAbstractTableModel::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } static const uint qt_meta_data_CookiesExceptionsDialog[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 4, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 25, 24, 24, 24, 0x08, 33, 24, 24, 24, 0x08, 41, 24, 24, 24, 0x08, 64, 59, 24, 24, 0x08, 0 // eod }; static const char qt_meta_stringdata_CookiesExceptionsDialog[] = { "CookiesExceptionsDialog\0\0block()\0" "allow()\0allowForSession()\0text\0" "textChanged(QString)\0" }; const QMetaObject CookiesExceptionsDialog::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_CookiesExceptionsDialog, qt_meta_data_CookiesExceptionsDialog, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &CookiesExceptionsDialog::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *CookiesExceptionsDialog::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *CookiesExceptionsDialog::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CookiesExceptionsDialog)) return static_cast<void*>(const_cast< CookiesExceptionsDialog*>(this)); if (!strcmp(_clname, "Ui_CookiesExceptionsDialog")) return static_cast< Ui_CookiesExceptionsDialog*>(const_cast< CookiesExceptionsDialog*>(this)); return QDialog::qt_metacast(_clname); } int CookiesExceptionsDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: block(); break; case 1: allow(); break; case 2: allowForSession(); break; case 3: textChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; default: ; } _id -= 4; } return _id; } QT_END_MOC_NAMESPACE
misizeji/StudyNote_201308
Qt/browser/debug/moc_cookiejar.cpp
C++
mit
12,240
<?php namespace Webiny\Component\Validation\Validators; use Webiny\Component\Validation\ValidationException; use Webiny\Component\Validation\ValidatorInterface; class Number implements ValidatorInterface { public function getName() { return 'number'; } public function validate($value, $params = [], $throw = false) { if (is_numeric($value)) { return true; } $message = 'Value must be a number'; if ($throw) { throw new ValidationException($message); } return $message; } }
Webiny/Framework
src/Webiny/Component/Validation/Validators/Number.php
PHP
mit
582
<?php /*-------------------------------------------------------+ | PHP-Fusion Content Management System | Copyright © 2002 - 2008 Nick Jones | http://www.php-fusion.co.uk/ +--------------------------------------------------------+ | Filename: user_sig_include.php | Author: Digitanium +--------------------------------------------------------+ | This program is released as free software under the | Affero GPL license. You can redistribute it and/or | modify it under the terms of this license which you | can read by viewing the included agpl.txt or online | at www.gnu.org/licenses/agpl.html. Removal of this | copyright header is strictly prohibited without | written permission from the original author(s). +--------------------------------------------------------*/ if (!defined("IN_FUSION")) { die("Access Denied"); } if ($profile_method == "input") { require_once INCLUDES."bbcode_include.php"; echo "<tr>\n"; echo "<td valign='top' class='tbl'>".$locale['uf_sig']."</td>\n"; echo "<td class='tbl'><textarea name='user_sig' cols='60' rows='5' class='textbox' style='width:295px'>".(isset($user_data['user_sig']) ? $user_data['user_sig'] : "")."</textarea><br />\n"; echo display_bbcodes("300px", "user_sig", "inputform", "smiley|b|i|u||center|small|url|mail|img|color")."</td>\n"; echo "</tr>\n"; } elseif ($profile_method == "display") { // Not shown in profile } elseif ($profile_method == "validate_insert") { $db_fields .= ", user_sig"; $db_values .= ", '".(isset($_POST['user_sig']) ? stripinput(trim($_POST['user_sig'])) : "")."'"; } elseif ($profile_method == "validate_update") { $db_values .= ", user_sig='".(isset($_POST['user_sig']) ? stripinput(trim($_POST['user_sig'])) : "")."'"; } ?>
simplyianm/clububer
includes/user_fields/user_sig_include.php
PHP
mit
1,717
using System; namespace EFLikeDemo.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
juniorporfirio/novidadesEFCore2
EFLikeDemo/Models/ErrorViewModel.cs
C#
mit
208
package ExercicioPOO; public class TestaAgenda { public static void main(String[] args) { Agenda agenda = new Agenda(2); Pessoa p1 = new Pessoa(); p1.setNome("Emiliano"); p1.setIdade(43); p1.setAltura(1.82); Pessoa p2 = new Pessoa(); p2.setNome("Carvalho"); p2.setIdade(34); p2.setAltura(1.82); agenda.armazenaPessoa(p1.getNome(), p1.getIdade(), p1.getAltura()); agenda.armazenaPessoa(p2.getNome(), p2.getIdade(), p2.getAltura()); agenda.imprimePessoa(0); agenda.imprimeAgenda(); } }
emilianocarvalho/Estacio
src/ExercicioPOO/TestaAgenda.java
Java
mit
513
import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.bcrypt import Bcrypt from flask_sockets import Sockets app = Flask(__name__, static_folder="../static/dist", template_folder="../static") if os.environ.get('PRODUCTION'): app.config.from_object('config.ProductionConfig') else: app.config.from_object('config.TestingConfig') db = SQLAlchemy(app) bcrypt = Bcrypt(app) sockets = Sockets(app)
mortbauer/webapp
application/__init__.py
Python
mit
444
<?php /** * The MIT License (MIT) * * Copyright 2015 Anatoliy Bereznyak * * 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. */ namespace Workers; /** * Class Worker * @package Bezk * @author Анатолий Березняк <bereznyak@me.com> * @homepage http://unrealmac.ru * @link https://github.com/Bezk/Workers */ final class Worker { /** * @const string номер версии скрипта */ const VERSION = '1.0.0-beta'; /** * @var int PID текущего процесса */ private $iPID; /** * @var int PID родительского процесса */ private $iParentPID; /** * @var int PID процесса, при завершении которого сработает * родительский деструктор */ private $iParentDestructorPID; /** * @var string путь к временной директории */ private $sTempDirectory; /** * @var string путь к директории для логов */ private $sLogsDirectory; /** * @var int приоритет процесса */ private $iWorkerPriority = 0; /** * @var string путь к PID файлу */ private $sPIDFilePath; /** * @var string префикс технических файлов (PID, логи) */ private $sFilesBasename; /** * @var int максимальное количество одновременно работающих процессов */ private $iNumberOfWorkers = 1; /** * @var int лимит на время исполнения дочернего процесса (в секундах) */ private $iMaxExecutionTimeInSeconds = 0; /** * @var bool флаг остановки демона */ private $bIsStop = false; /** * @var array массив работающих воркеров */ private $aInstances = array(); /** * @var callable функция с программой воркера */ private $cExecutingFunction = null; /** * @var callable функция с деструктором родительского процесса */ private $cDestructorFunction = null; /** * @var callable функция с деструктором воркера */ private $cWorkerDestructorFunction = null; /** * @var callable функция выполняемая по завершению родительского процесса */ private $cShutdownFunction = null; /** * @var int время первичной задержки для асинхронного запуска в секундах */ private $iFirstDelayBetweenLaunch = 0; /** * @var int номер процесса */ private $iNumberWorker = 0; /** * @var int порядковый номер процесса */ private $iSerialNumberWorker = 0; /** * @var int время задержки между попытками запуска новых воркеров * в милисекундах * (при достижении максимального количества работающих воркеров) */ private $iDelayBetweenLaunch = 1000; /** * @var array массив с данными для воркеров */ private $aWorkers = array(); /** * @var array ключи воркеров */ private $aWorkersNames = array(); /** * @var array данные воркеров */ private $aWorkersData = array(); /** * @var bool флаг цикличной работы */ private $bIsLooped = true; /** * @var bool флаг привязки к консоли */ private $bHookedConsole = false; /** * @var bool флаг вывода в консоль */ private $bSTDInConsole = false; /** * @var bool флаг подробного вывода */ private $bVerbose = false; /** * @var bool флаг последовательной (один за одним) работы */ private $bInSequence = false; /** * @var array массив мета информации процессов */ private $aMeta = array(); /** * @var mixed переменная с данными, которые могут использоваться в воркере */ private $mInstanceData = null; /** * @var bool флаг "запущенности" скрипта */ private $bIsActive = false; /** * @var bool флаг первичного запуска метода run */ private $bIsFirstRun = true; /** * @var bool флаг быстрого запуска */ private $bFastRun = true; /** * @var bool флаг запуска метода run */ private $bIsRun = false; /** * @var array массив воркеров завершивших работу */ private $aStopped = array(); /** * @var array массив воркеров завершивших работу */ private $bVerboseInOUT = false; /** * @var array ключ воркера */ private $sInstanceName = null; /** * @var array массив с ресурсами на потоки ввода/вывода */ private $STD = array( 'IN' => STDIN, 'OUT' => STDOUT, 'ERR' => STDERR ); final public function __construct( $bFastRun = null, $aWorkersData = null, callable $cExecutingFunction = null, callable $cDestructorFunction = null, callable $cWorkerDestructorFunction = null, callable $cShutdownFunction = null, $sTempDirectory = null, $sLogsDirectory = null, $iNumberOfWorkers = null, $iWorkerPriority = null, $iMaxExecutionTimeInSeconds = null, $iFirstDelayBetweenLaunch = null, $iDelayBetweenLaunch = null, $bIsLooped = null, $bInSequence = null, $bHookedConsole = null, $bSTDInConsole = null, $bVerbose = null, $bVerboseInOUT = null ) { declare(ticks=1); if (isset($bInSequence)) $this->bInSequence = (bool) $bInSequence; if ($cExecutingFunction) $this->cExecutingFunction = (string) $cExecutingFunction; $this->iPID = getmypid(); $this->iParentPID = $this->iPID; $this->sTempDirectory = $sTempDirectory ? (string) $sTempDirectory : sys_get_temp_dir(); $this->sLogsDirectory = $sLogsDirectory ? (string) $sLogsDirectory : $this->sTempDirectory; if ($iFirstDelayBetweenLaunch) $this->iFirstDelayBetweenLaunch = $iFirstDelayBetweenLaunch; $this->sFilesBasename = basename($_SERVER['PHP_SELF']); $this->sPIDFilePath = $this->sTempDirectory . DIRECTORY_SEPARATOR . $this->sFilesBasename . '.pid'; if (isset($bHookedConsole)) $this->bHookedConsole = (bool) $bHookedConsole; if (isset($bSTDInConsole)) $this->bSTDInConsole = (bool) $bSTDInConsole; if (isset($bIsLooped)) $this->bIsLooped = (bool) $bIsLooped; if ($cDestructorFunction) $this->cDestructorFunction = (string) $cDestructorFunction; if ($cWorkerDestructorFunction) $this->cWorkerDestructorFunction = (string) $cWorkerDestructorFunction; if ($cShutdownFunction) $this->cShutdownFunction = (string) $cShutdownFunction; if ($iMaxExecutionTimeInSeconds) $this->iMaxExecutionTimeInSeconds = (int) $iMaxExecutionTimeInSeconds; if ($iWorkerPriority) $this->iWorkerPriority = (int) $iWorkerPriority; if (isset($bVerbose)) $this->bVerbose = (bool) $bVerbose; if ($iDelayBetweenLaunch) $this->iDelayBetweenLaunch = (int) $iDelayBetweenLaunch; $this->bIsActive = $this->isActive(); if ($aWorkersData) { // выставляем количество воркеров $this->iNumberOfWorkers = count((array) $aWorkersData); // массив имен демонов => значений для воркеров $this->aWorkers = (array) $aWorkersData; // массив имен демонов $this->aWorkersNames = array_keys((array) $aWorkersData); // массив значений для воркеров $this->aWorkersData = array_values((array) $aWorkersData); } if ($iNumberOfWorkers) { if ($aWorkersData) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "The numbers of processes" because set up' . ' option "Workers data"' ); } else { $this->iNumberOfWorkers = (int) $iNumberOfWorkers; for ($i = 1; $i <= $this->iNumberOfWorkers; $i++) $this->aWorkers[] = null; // массив имен демонов $this->aWorkersNames = array_keys((array) $this->aWorkers); // массив значений для воркеров $this->aWorkersData = array_values((array) $this->aWorkers); } } if (isset($bVerboseInOUT)) $this->bVerboseInOUT = (bool) $bVerboseInOUT; if (isset($bFastRun)) $this->bFastRun = $bFastRun; $this->rVerboseStream = $this->bVerboseInOUT ? $this->STD['OUT'] : $this->STD['ERR']; $this->aStopped = $this->getInstancesKeys($this->aWorkersNames); // быстрый старт if ($this->bFastRun) $this->run(); } /** * Деструкторы родительского и дочернего процессов * * @return void */ final public function __destruct() { switch (getmypid()) { // деструктор родительского процесса case $this->iParentDestructorPID: $this->setStopMeta(); $this->writeInLog($this->rVerboseStream, 'Stopped'); if ($this->bVerbose) $this->writeMeta(); $this->writeInLog( $this->rVerboseStream, '-----------------------------------------' ); if ($this->cDestructorFunction) call_user_func($this->cDestructorFunction); unlink($this->sPIDFilePath); break; case $this->iParentPID: break; // деструктор дочерних процессов default: $sContent = $this->getOutput(ob_get_contents()); ob_end_clean(); echo $sContent; $this->setStopMeta(); if ($this->bVerbose) { $this->writeInLog($this->rVerboseStream, 'Stopped'); $this->writeMeta(); $this->writeInLog( $this->rVerboseStream, '-----------------------------------------' ); } if ($this->cWorkerDestructorFunction) call_user_func($this->cWorkerDestructorFunction); } } /** * Класс запрещено клонировать * * @return void */ final private function __clone() { } /** * Выводит дебаг-инфо * * @return array */ public function __debugInfo() { return array( 'instance' => array( 'name' => $this->sInstanceName, 'data' => $this->mInstanceData, 'meta' => $this->aMeta, 'serial number worker' => $this->iSerialNumberWorker, 'number worker' => $this->iNumberWorker, 'PID' => $this->iPID, 'parent PID' => $this->iParentPID ), 'common' => array( 'version' => self::VERSION, 'parent PID' => $this->iParentPID, 'parent PID in file' => $this->getPIDFromFile(), 'PID file' => realpath($this->sPIDFilePath), 'fast run' => $this->bFastRun, 'workers' => $this->aWorkers, 'workers names' => $this->aWorkersNames, 'workers data' => $this->aWorkersData, 'meta' => $this->aMeta, 'workers program function' => $this->cExecutingFunction, 'parent destructor function' => $this->cDestructorFunction, 'worker destructor function' => $this->cWorkerDestructorFunction, 'shutdown function' => $this->cShutdownFunction, 'files prefix' => $this->sFilesBasename, 'temporary directory' => realpath($this->sTempDirectory), 'logs directory' => realpath($this->sLogsDirectory), 'numbers of workers' => $this->iNumberOfWorkers, 'worker priority' => $this->iWorkerPriority, 'maximum execution time limit' => $this->iMaxExecutionTimeInSeconds, 'first delay between launch workers' => $this->iFirstDelayBetweenLaunch, 'delay between attempts launch workers' => $this->iDelayBetweenLaunch, 'looped mode' => $this->bIsLooped, 'in sequence mode' => $this->bInSequence, 'is unhook console' => !$this->bHookedConsole, 'IO in console' => $this->bSTDInConsole, 'IO' => $this->STD, 'verbose mode' => $this->bVerbose, 'is verbose in out stream' => $this->bVerboseInOUT ) ); } /** * Запускает работу демона (если объект вызывается как функция) * * @return void */ public function __invoke() { $this->run(); } /** * Приостанавливает работу демона * * @return void */ public function __sleep() { $this->iNumberOfWorkers = 0; foreach ($this->aInstances as $iPID => $sValue) { pcntl_waitpid($iPID, $iStatus); if ($iStatus === 0) { $this->aStopped[$this->aInstances[$iPID]] = $this->aInstances[$iPID]; unset($this->aInstances[$iPID]); } } pcntl_sigwaitinfo(array(SIGCONT), $aInfo); $this->iNumberOfWorkers = count($this->aWorkers); } /** * Возобновляет работу демона после остановки * * @return void */ public function __wakeup() { $this->bIsStop = false; $this->iNumberOfWorkers = count($this->aWorkers); } /** * Возвращает строковое представление объекта * * @return string */ public function __toString() { return (string) $this->sFilesBasename; } /** * Отвязывает демона от консоли * * @return boolean */ private function unhookConsole() { if ($this->bVerbose) { $this->writeInLog( $this->rVerboseStream, 'Unhook console: Fork process and kill parent, set up children' . ' as parent...' ); } $iChildPID = pcntl_fork(); if ($iChildPID === -1) { $this->writeInLog($this->STD['ERR'], 'Fork ended with error'); return false; } // выходим из родительского (привязанного к консоли) процесса if ($iChildPID) exit(0); // продолжим работу после завершения родительского процесса $bResult = true; while ($bResult) $bResult = posix_kill($this->iPID, 0); // делаем дочерний процесс основным $bResult = posix_setsid(); if ($bResult === -1) throw new WorkerException( 'Set up current process a session leader ended with error' ); if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, "\t done"); return true; } /** * Запускает работу демона * * @return void */ public function run() { $this->aMeta['time']['start'] = round(microtime(true), 2); // проверка окружения $this->checkWorkflow(); $this->writeInLog( $this->STD['OUT'], $this->bIsLooped ? 'Looped mode' : 'One-off mode' ); $this->bIsRun = true; $this->bIsFirstRun = false; // установка кастомных потоков IO $this->setStreamsIO(); // отвязываемся от консоли if (!$this->bHookedConsole) $this->unhookConsole(); // назначаем функцию завершения if ($this->cShutdownFunction) register_shutdown_function($this->cShutdownFunction); // необходимо обновить данные после отвязки от консоли $this->iPID = getmypid(); $this->iParentPID = $this->iPID; $this->iParentDestructorPID = $this->iPID; // помечаем родительский процесс if (function_exists('cli_set_process_title') && $_SERVER['TERM_PROGRAM'] !== 'Apple_Terminal' ) { cli_set_process_title($this->sFilesBasename . '.parent'); } if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, 'Write PID...'); // фиксируем PID $this->writePIDInFile($this->iPID); if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, "\t write PID " . $this->iPID); if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, 'Set up signal handler...'); // устанавливаем обработку сигналов $this->setSignalHandlers(); if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, "\t set"); while (!$this->bIsStop) { $this->iSerialNumberWorker++; $this->iNumberWorker++; if ($this->iNumberWorker > $this->iNumberOfWorkers) { // если демон не зациклен, выход if (!$this->bIsLooped) break; // сбрасываем порядковый номер дочернего процесса $this->iNumberWorker = 1; } // запущено максимальное количество дочерних процессов, ждем завершения while(count($this->aStopped) === 0) usleep($this->iDelayBetweenLaunch); $this->sInstanceName = array_values($this->aStopped)[0]; unset($this->aStopped[$this->sInstanceName]); // распределяем деление, чтобы не грузить процессор if ( ($this->iSerialNumberWorker > 1 && $this->iSerialNumberWorker <= $this->iNumberOfWorkers) && $this->iFirstDelayBetweenLaunch ) { if ($this->bVerbose) { $this->writeInLog( $this->rVerboseStream, 'Delay between launching instances: ' . $this->iFirstDelayBetweenLaunch . ' seconds' ); } sleep($this->iFirstDelayBetweenLaunch); } $iChildPID = pcntl_fork(); if ($iChildPID === -1) { throw new WorkerException('Create new instance ended with error'); } elseif ($iChildPID) { if ($this->bInSequence) pcntl_wait($sStatus); if ($this->bVerbose) { $this->writeInLog( $this->rVerboseStream, 'New instance: ' . $this->sInstanceName . ' PID: ' . $iChildPID ); } unset($this->aStopped[$this->sInstanceName]); $this->aInstances[$iChildPID] = $this->sInstanceName; } else { $this->worker(); } // выходим из цикла в дочернем процессе if ($this->iPID !== $this->iParentPID) break; $this->checkZombie(); } if ($this->iPID === $this->iParentPID) { if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, 'No work. Stopping'); if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, ' waiting…'); while (count($this->aInstances)) usleep($this->iDelayBetweenLaunch); $this->stop(); // не будем продолжать работу родительского процесса exit(0); } } private function stop() { $this->bIsStop = true; while ($this->aInstances) { foreach ($this->aInstances as $iPID => $mValue) { $iPID = pcntl_waitpid($iPID, $iStatus, WNOHANG|WUNTRACED); if ($iPID > 0) { if (isset($this->aInstances[$iPID])) { if ($this->bVerbose) { $this->writeInLog( $this->rVerboseStream, 'End instance: ' . $this->aInstances[$iPID] . ' PID: ' . $iPID ); } $this->aStopped[$this->aInstances[$iPID]] = $this->aInstances[$iPID]; unset($this->aInstances[$iPID]); } } } } } /** * Выполняет отлов зомби-процессов * * @return void */ private function checkZombie() { foreach ($this->aInstances as $iPID => $mValue) { $iPID = pcntl_waitpid($iPID, $iStatus, WNOHANG|WUNTRACED); if ($iPID > 0) { if (isset($this->aInstances[$iPID])) { if ($this->bVerbose) { $this->writeInLog( $this->rVerboseStream, 'End instance: ' . $this->aInstances[$iPID] . ' PID: ' . $iPID ); } $this->aStopped[$this->aInstances[$iPID]] = $this->aInstances[$iPID]; unset($this->aInstances[$iPID]); } } } } /** * Выполняет проверку окружения * * @return void */ public function checkWorkflow() { // процесс не должен запускаться в нескольких экземплярах if ($this->bIsActive) throw new WorkerException('Already running'); // нельзя дважды запускать метод run if (!$this->bIsFirstRun) throw new WorkerException('Method "run" called only once'); if (!function_exists('pcntl_fork')) { throw new WorkerException( 'PCNTL: Process control doesn\'t support.' . ' Compile PHP with --enable-pcntl' ); } if (!function_exists('pcntl_wait') && $this->bInSequence) { throw new WorkerException( 'PCNTL: Function pcntl_wait doesn\'t support.' . ' Function "In sequence" don\'t work' ); } if (function_exists('pcntl_fork') && !function_exists('pcntl_sigwaitinfo')) { $this->writeInLog( $this->STD['OUT'], 'PCNTL: OS X doesn\'t support function pcntl_sigwaitinfo.' . ' Send SIGTSTP or SIGSTOP return error of undefined function' ); } if ($this->iWorkerPriority < -20 || $this->iWorkerPriority > 20) { throw new WorkerException( 'Incorrect value for option "workers priority".' . ' Set value range from -20 to 20.'); } if (!is_dir($this->sTempDirectory) || !is_writable($this->sTempDirectory)) { throw new WorkerException( 'Incorrect value for option "temp directory" or directory' . ' not allowed write.' ); } if (!is_dir($this->sLogsDirectory) || !is_writable($this->sLogsDirectory)) { throw new WorkerException( 'Incorrect value for option "logs directory" or directory' . ' not allowed write.' ); } } /** * Выполняет работу воркера * * @return void */ private function worker() { $this->iPID = getmypid(); $this->aMeta['time']['start'] = round(microtime(true), 2); // ключ для вызова в функции пользовательской $this->mInstanceData = (bool) $this->aWorkersData ? $this->aWorkersData[$this->iNumberWorker - 1] : null; if (function_exists('cli_set_process_title') && isset($_SERVER['TERM_PROGRAM']) && $_SERVER['TERM_PROGRAM'] !== 'Apple_Terminal' ) { cli_set_process_title($this->sFilesBasename . '.' . $this->sInstanceName); } $this->setStreamsIO($this->sInstanceName); if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, 'PID: ' . $this->iPID); // установка приоритета на процесс if ($this->iWorkerPriority) { if ($this->bVerbose) { $this->writeInLog( $this->rVerboseStream, 'Set process priority equal ' . $this->iWorkerPriority ); } $this->setPriority($this->iWorkerPriority); } // лимит на время исполнения дочернего процесса if ($this->iMaxExecutionTimeInSeconds) { if ($this->bVerbose) { $this->writeInLog( $this->rVerboseStream, 'Set process lifetime ' . $this->iMaxExecutionTimeInSeconds . ' seconds' ); } // считает время работы скрипта set_time_limit($this->iMaxExecutionTimeInSeconds); // считает время исполнения вне скрипта (потоки, коннекты, sleep, etc) pcntl_alarm($this->iMaxExecutionTimeInSeconds); } if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, 'Started'); // перехватываем вывод ob_start(); // запускаем функцию if ($this->cExecutingFunction) { call_user_func($this->cExecutingFunction, $this->mInstanceData); // успешно выходим exit(0); } } /** * Обработчик сигналов * * @param integer $iSignalNumber * @param integer $iPID * @param integer $iPID * @return void */ public function sigHandler($iSignalNumber, $iPID = null, $iStatus = null) { switch($iSignalNumber) { // при получении сигнала завершения работы устанавливаем флаг case SIGTERM: case SIGHUP: case SIGINT; $this->stop(); break; // сигнал от дочернего процесса case SIGCHLD: $iPID = pcntl_waitpid(-1, $iStatus, WNOHANG|WUNTRACED); if ($iPID == -1) { $this->writeInLog( $this->STD['ERR'], 'Error receive ' . SIGCHLD . ' (sigchld) signal' ); return true; } // юниксовый код выхода $iExitCode = pcntl_wexitstatus($iStatus); // закончим всю работу, если воркеры выходят с фатальной ошибкой if ($iExitCode === 255) $this->stop(); if (isset($this->aInstances[$iPID])) { if ($this->bVerbose) { $this->writeInLog( $this->rVerboseStream, 'End instance: ' . $this->aInstances[$iPID] . ' PID: ' . $iPID ); } $this->aStopped[$this->aInstances[$iPID]] = $this->aInstances[$iPID]; unset($this->aInstances[$iPID]); } break; case SIGALRM: case SIGVTALRM: // код выхода дочернего процесса exit(1); echo 'Child exit on timeout' . PHP_EOL; break; case SIGTSTP: case SIGSTOP: $this->__sleep(); break; case SIGCONT: $this->__wakeup(); break; } return true; } /** * Возвращает флаг, является ли PID записанный в файле активным процессом * * @return boolean */ private function isActive() { // очищаем файловый кеш для PID файла clearstatcache(true, $this->sPIDFilePath); if (file_exists($this->sPIDFilePath) && is_readable($this->sPIDFilePath)) { $iPID = $this->getPIDFromFile(); return (is_numeric($iPID) && posix_kill($iPID, 0) === true) ? true : false; } return false; } /** * Возвращает флаг, является ли массив ассоциативным * * @param array $aArray * @return boolean */ private function isAssoc(array $aArray) { return array_keys($aArray) !== range(0, count($aArray) - 1); } /** * Записывает в файл PID процесса * * @param integer $iPID * @return boolean */ private function writePIDInFile($iPID) { return file_put_contents($this->sPIDFilePath, $iPID, LOCK_EX); } /** * Записывает строку в файл, возвращает количество записанных байт * * @param resource $rLog * @param string $sMessage * @return integer */ public function writeInLog($rLog, $sMessage) { return fwrite( $rLog, '[' . date('d-M-Y H:i:s e') . '] ' . $sMessage . PHP_EOL ); } /** * Пишет в лог мета-информацию * * @return void */ private function writeMeta() { $this->writeInLog( $this->rVerboseStream, 'Execution time: ' . round($this->aMeta['execution_time'], 2) . ' seconds' ); $this->writeInLog($this->rVerboseStream, 'Load average: ' . round($this->aMeta['load_average'][0], 2) . ', ' . round($this->aMeta['load_average'][1], 2) . ', ' . round($this->aMeta['load_average'][2], 2) ); } /** * Устанавливает флаг привязки к консоли * * @return boolean */ public function setUnhookConsole($bHookedConsole) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "unhook console" because workers already run' ); return false; } $this->bHookedConsole = (bool) !$bHookedConsole; return true; } /** * Устанавливает флаг цикличности * * @return boolean */ public function setLoopedMode($bIsLooped) { $this->bIsLooped = (bool) $bIsLooped; return true; } /** * Устанавливает задержку для асинхронного запуска * * @return boolean */ public function setLaunchInstancesDelay($iFirstDelayBetweenLaunch) { $this->iFirstDelayBetweenLaunch = $iFirstDelayBetweenLaunch; return true; } /** * Устанавливает задержку между повторными попытками запуска новых воркеров * * @return boolean */ public function setDelayBetweenLaunchAttempts($iDelayBetweenLaunch) { $this->iDelayBetweenLaunch = $iDelayBetweenLaunch; return true; } /** * Устанавливает максимальное время работы воркеров в секундах * * @return boolean */ public function setMaxExecutionTime($iMaxExecutionTimeInSeconds) { $this->iMaxExecutionTimeInSeconds = $iMaxExecutionTimeInSeconds; return true; } /** * Устанавливает мод подробного вывода * * @return boolean */ public function setVerboseMode($bVerbose) { $this->bVerbose = $bVerbose; return true; } /** * Устанавливает количество воркеров * * @return boolean */ public function setNumberOfWorkers($iWorkers) { if ($this->aWorkers) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "The numbers of processes" because set up option' . ' "Workers data"' ); return false; } else { $this->iNumberOfWorkers = (int) $iWorkers; for ($i = 1; $i <= $this->iNumberOfWorkers; $i++) $this->aWorkers[] = null; // массив имен демонов $this->aWorkersNames = array_keys((array) $this->aWorkers); // массив значений для воркеров $this->aWorkersData = array_values((array) $this->aWorkers); $this->aStopped = $this->getInstancesKeys($this->aWorkersNames); return true; } } /** * Устанавливает данные для проброса в воркер * * @return boolean */ public function setWorkersData($aWorkersData) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "workers data" because workers already run' ); return false; } if ($this->iNumberOfWorkers) $this->writeInLog( $this->STD['OUT'], 'Ignore option "The numbers of processes" because set up option' . ' "Workers data"' ); // выставляем количество воркеров $this->iNumberOfWorkers = count((array) $aWorkersData); // массив имен демонов => значений для воркеров $this->aWorkers = (array) $aWorkersData; // массив имен демонов $this->aWorkersNames = array_keys((array) $aWorkersData); // массив значений для воркеров $this->aWorkersData = array_values((array) $aWorkersData); $this->aStopped = $this->getInstancesKeys($this->aWorkersNames); return true; } /** * Устанавливает функцию, в которой находится программа воркеров * * @return void */ public function setWorkersFunction(callable $cExecutingFunction) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "workers function" because workers already run' ); return false; } $this->cExecutingFunction = (string) $cExecutingFunction; return true; } /** * Устанавливает функцию деструктора родительского процесса * * @return void */ public function setDestructorFunction($cDestructorFunction) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "destructor function" because workers already run' ); return false; } $this->cDestructorFunction = (string) $cDestructorFunction; return true; } /** * Устанавливает функцию деструктора дочерних процессов * * @return void */ public function setWorkercDestructorFunction($cWorkerDestructorFunction) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "workers destructor function" because workers' . ' already run' ); return false; } $this->cWorkerDestructorFunction = (string) $cWorkerDestructorFunction; return true; } /** * Устанавливает вывод потоков ввода/вывода в консоль * * @return void */ public function setIOInConsole($bSTDInConsole) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "set IO in console" because workers already run' ); return false; } $this->bSTDInConsole = (bool) $bSTDInConsole; } /** * Устанавливает временную директорию * * @return boolean */ public function setTempDirectory($sTempDirectory) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "set temp directory" because workers already run' ); return false; } $this->sTempDirectory = $sTempDirectory; $this->sPIDFilePath = $this->sTempDirectory . DIRECTORY_SEPARATOR . $this->sFilesBasename . '.pid'; return true; } /** * Устанавливает директорию логов * * @return boolean */ public function setLogsDirectory($sLogsDirectory) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "set logs directory" because workers already run' ); return false; } $this->sLogsDirectory = $sLogsDirectory; return true; } /** * Устанавливает приоритет для воркерных процессов * * @return void */ public function setWorkersPriority($iWorkerPriority) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "set workers priority" because workers already run' ); return false; } $this->iWorkerPriority = (int) $iWorkerPriority; return true; } /** * Устанавливает обработчики сигналов * * @return void */ private function setSignalHandlers() { pcntl_signal(SIGTERM, array(&$this, "sigHandler")); // сигнал завершения работы pcntl_signal(SIGHUP, array(&$this, "sigHandler")); // закрытия консоли pcntl_signal(SIGINT, array(&$this, "sigHandler")); // ctrl-c c консоли pcntl_signal(SIGALRM, array(&$this, "sigHandler")); // alarm pcntl_signal(SIGVTALRM, array(&$this, "sigHandler")); // alarm pcntl_signal(SIGCHLD, array(&$this, "sigHandler")); // сигналы завершения дочернего процессв pcntl_signal(SIGTSTP, array(&$this, "sigHandler")); // сигналы остановки с консоли ctrl-z pcntl_signal(SIGCONT, array(&$this, "sigHandler")); // продолжение работы } /** * Переопределяет потоки ввода/вывода * * @param $sInstanceName * @return void */ private function setStreamsIO($sInstanceName = null) { if (!$this->bSTDInConsole) { if (!$sInstanceName) $this->writeInLog($this->STD['OUT'], 'Reassignment STD streams'); ini_set('display_errors', 'off'); ini_set( 'error_log', $this->sLogsDirectory . DIRECTORY_SEPARATOR . $this->sFilesBasename . '.error.log' ); $sInstanceName = ($sInstanceName) ? '.' . $sInstanceName : null; // закрываем потоки fclose($this->STD['IN']); fclose($this->STD['OUT']); fclose($this->STD['ERR']); // переопределяем $this->STD['IN'] = fopen( '/dev/null', 'r' ); $this->STD['OUT'] = fopen( $this->sLogsDirectory . DIRECTORY_SEPARATOR . $this->sFilesBasename . $sInstanceName . '.application.log', 'ab' ); $this->STD['ERR'] = fopen( $this->sLogsDirectory . DIRECTORY_SEPARATOR . $this->sFilesBasename . $sInstanceName . '.daemon.log', 'ab' ); // переобпределяем зависимое свойство $this->rVerboseStream = $this->bVerboseInOUT ? $this->STD['OUT'] : $this->STD['ERR']; } } /** * Устанавливает приоритет для дочерних процессов * * @param integer $iWorkerPriority * @return boolean */ private function setPriority($iWorkerPriority) { return $iWorkerPriority ? pcntl_setpriority($iWorkerPriority) : false; } /** * Записывает начальную мета-информацию * * @return void */ private function setStartMeta() { $this->aMeta['time']['start'] = round(microtime(true), 2); } /** * Записывает конечную мета-информацию * * @return void */ private function setStopMeta() { $this->aMeta['time']['stop'] = round(microtime(true), 2); $this->aMeta['execution_time'] = $this->aMeta['time']['stop'] - $this->aMeta['time']['start']; $this->aMeta['load_average'] = sys_getloadavg(); } /** * Возвращает имена инстансов * * @return array */ private function getInstancesKeys() { $bIsAssoc = $this->isAssoc($this->aWorkers); $aKeys = array(); foreach ($this->aWorkersNames as $mKey) $aKeys[$bIsAssoc ? $mKey : $mKey + 1] = $bIsAssoc ? $mKey : $mKey + 1; return $aKeys; } /** * Обрабатывает строки, добавляя дату в начало строки * * @param string $sMessage * @return string */ private function getOutput($sMessage) { $aOutput = explode(PHP_EOL, $sMessage); $aOUT = array(); foreach ($aOutput as $sRow) { $aOUT[] = '[' . date('d-M-Y H:i:s e') . '] ' . rtrim($sRow); } return implode(PHP_EOL, $aOUT) . PHP_EOL; } /** * Возвращает PID из файла * * @return integer */ private function getPIDFromFile() { return (int) trim(file_get_contents($this->sPIDFilePath)); } /** * Возвращает PID родительского процесса * * @return integer */ private function getPID() { return (int) $this->iParentPID; } /** * Возвращает данные для использования в воркере * * @return mixed */ public function getWorkerData() { return $this->mInstanceData; } /** * Возвращает путь к каталогу временных файлов * * @return string */ public function getTempDirectory() { return $this->sTempDirectory; } /** * Возвращает путь к каталогу логов * * @return string */ public function getLogsDirectory() { return $this->sLogsDirectory; } /** * Возвращает префикс файлов (имя скрипта в котором работает демон) * * @return string */ public function getFilesBasename() { return $this->sFilesBasename; } /** * Возвращает путь к PID файлу * * @return string */ public function getPIDFilePath() { return $this->sPIDFilePath; } }
Bezk/Workers
src/Workers/Worker.php
PHP
mit
49,415
<?php namespace Mincer\Errors { class ClassNotRegisteredException extends \Exception { } }
emerido/mincer
src/Errors/ClassNotRegisteredException.php
PHP
mit
107
/* ** GENEREATED FILE - DO NOT MODIFY ** */ package com.wilutions.mslib.uccollaborationlib; import com.wilutions.com.*; /** * IRoomJoinStateChangedEventData. * IRoomJoinStateChangedEventData Interface */ @CoInterface(guid="{4D120020-CE64-43C5-9F84-7A7B2360388F}") public interface IRoomJoinStateChangedEventData extends IDispatch { static boolean __typelib__loaded = __TypeLib.load(); @DeclDISPID(1610743808) public RoomJoinState getJoinState() throws ComException; }
wolfgangimig/joa
java/joa-im/src-gen/com/wilutions/mslib/uccollaborationlib/IRoomJoinStateChangedEventData.java
Java
mit
491
package leetcode; /** * https://leetcode.com/problems/convert-1d-array-into-2d-array/ */ public class Problem2022 { public int[][] construct2DArray(int[] original, int m, int n) { if (m * n != original.length) { return new int[][]{}; } int[][] answer = new int[m][n]; int index = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { answer[i][j] = original[index++]; } } return answer; } }
fredyw/leetcode
src/main/java/leetcode/Problem2022.java
Java
mit
519
var UI = require('ui'); var ajax = require('ajax'); var Vector2 = require('vector2'); var webserver = decodeURIComponent(localStorage.getItem('webserver') ? localStorage.getItem('webserver') : 'webserver'); var qvserver = localStorage.getItem('qvserver') ? localStorage.getItem('qvserver') : 'qvserver'; var files = localStorage.getItem('files') ? localStorage.getItem('files') : 'files'; // Show splash screen while waiting for data var splashWindow = new UI.Window(); // Text element to inform user var text = new UI.Text({ position: new Vector2(0, 0), size: new Vector2(144, 168), text:'Downloading data...', font:'GOTHIC_28_BOLD', color:'black', textOverflow:'wrap', textAlign:'center', backgroundColor:'white' }); // Add to splashWindow and show splashWindow.add(text); splashWindow.show(); // Make request to the nodejs app //, webserver: test ajax( { url: webserver + '/getdata', method: 'post', data: {server: qvserver, files: files, webserver: webserver}, crossDomain: true }, function(data) { try { var items = []; data = JSON.parse(data); var areas = data.data; for(var i = 0; i < areas.length; i++) { items.push({ title:areas[i].name //,subtitle:time }); } var resultsMenu = new UI.Menu({ sections: [{ title: 'Areas', items: items }] }); resultsMenu.on('select', function(e) { var innerData = data.data[e.itemIndex].areadata; var title = data.data[e.itemIndex].name; var details = []; for(var d = 0; d < innerData.length; d++) { details.push({ title: innerData[d].category, subtitle: innerData[d].value }); } var detailsMenu = new UI.Menu({ sections: [{ title: title, items: details}] }); detailsMenu.show(); }); // Show the Menu, hide the splash resultsMenu.show(); splashWindow.hide(); } catch (err) { var text = new UI.Text({ position: new Vector2(0, 0), size: new Vector2(144, 168), text:'Error parsing the data', font:'GOTHIC_28_BOLD', color:'black', textOverflow:'wrap', textAlign:'center', backgroundColor:'white' }); // Add to splashWindow and show splashWindow.add(text); splashWindow.show(); } }, function(error) { var text = new UI.Text({ position: new Vector2(0, 0), size: new Vector2(144, 168), text:'Download failed :(', font:'GOTHIC_28_BOLD', color:'black', textOverflow:'wrap', textAlign:'center', backgroundColor:'white' }); // Add to splashWindow and show splashWindow.add(text); splashWindow.show(); }); Pebble.addEventListener('showConfiguration', function(e) { console.log("Showing configuration"); Pebble.openURL('https://googledrive.com/host/0BxjGsOE_3VoOU2RPQ3BjTlBfX0E'); }); Pebble.addEventListener('webviewclosed', function(e) { var options = JSON.parse(decodeURIComponent(e.response)); qvserver = encodeURIComponent(options.qvserver); webserver = encodeURIComponent(options.webserver); files = encodeURIComponent(options.files); if(qvserver == 'undefined') { qvserver = 'http://localhost:4799/QMS/Service'; } localStorage.setItem('qvserver', qvserver); localStorage.setItem('webserver', webserver); localStorage.setItem('files', files); //console.log("Configuration window returned: ", JSON.stringify(options)); }); //Send a string to Pebble var dict = { QVSERVER : qvserver, WEBSERVER: webserver, FILES: files }; Pebble.sendAppMessage(dict, function(e) { console.log("Send successful."); }, function(e) { console.log("Send failed!"); });
countnazgul/QlikviewToPebble
QMSAPIStarter/pebbleapp/src/app.js
JavaScript
mit
3,891
import Ember from 'ember'; var PluginsPopularRoute = Ember.Route.extend({ titleToken: 'Popular' }); export default PluginsPopularRoute;
sergiolepore/hexo-plugin-site
app/routes/plugins/popular.js
JavaScript
mit
140
using System; using System.Web; using System.Web.UI; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Owin; using WebApplication2.Models; namespace WebApplication2.Account { public partial class ForgotPassword : Page { protected void Page_Load(object sender, EventArgs e) { } protected void Forgot(object sender, EventArgs e) { if (IsValid) { // Validate the user's email address var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); ApplicationUser user = manager.FindByName(Email.Text); if (user == null || !manager.IsEmailConfirmed(user.Id)) { FailureText.Text = "The user either does not exist or is not confirmed."; ErrorMessage.Visible = true; return; } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send email with the code and the redirect to reset password page //string code = manager.GeneratePasswordResetToken(user.Id); //string callbackUrl = IdentityHelper.GetResetPasswordRedirectUrl(code, Request); //manager.SendEmail(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>."); loginForm.Visible = false; DisplayEmail.Visible = true; } } } }
albinvinoy/MyClockIn
WebApplication2/WebApplication2/Account/Forgot.aspx.cs
C#
mit
1,630
/** * Created by Hernandes on 21/04/2016. */ function PessoaModel(m){ var self = this; var base = new BaseModel(); ko.utils.extend(self,base); self.PessoaID = ko.observable().defaultValue(0).extend({required:true}); self.Nome = ko.observable('').extend({required:true,editable:true}); self.Email = ko.observable('').extend({required:true,editable:true}); self.Enderecos = ko.observableArray([]).typeOf(EnderecoBaseModel); self.assignProperties(m); } define('pessoa-model',function() { return PessoaModel; });
Hernandesjunio/KnockoutModelChainValidation
Scripts/models/pessoa-model.js
JavaScript
mit
565
package net.nextpulse.jadmin.dao; import com.google.common.base.Joiner; import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.FormPostEntry; import org.apache.commons.dbutils.BasicRowProcessor; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * DAO implementation for resources backed by a SQL database. * * @author yholkamp */ public class GenericSQLDAO extends AbstractDAO { private static final Logger logger = LogManager.getLogger(); private final String tableName; private DataSource dataSource; public GenericSQLDAO(DataSource dataSource, String tableName) { this.dataSource = dataSource; this.tableName = tableName; } /** * @param keys primary key(s) * @return either an empty optional or one holding a DatabaseEntry matching the keys * @throws DataAccessException if an error occurs while accessing the database. */ @Override public Optional<DatabaseEntry> selectOne(Object[] keys) throws DataAccessException { logger.trace("Selecting one {}", tableName); Map<String, Object> editedObject = null; try(Connection conn = dataSource.getConnection()) { String conditions = resourceSchemaProvider.getKeyColumns().stream() .map(x -> String.format("%s = ?", x.getName())) .reduce((s, s2) -> s + " AND " + s2) .orElseThrow(() -> new DataAccessException("Could not generate SQL condition")); PreparedStatement statement = conn.prepareStatement(String.format("SELECT * FROM %s WHERE %s LIMIT 1", tableName, conditions)); for(int i = 1; i <= resourceSchemaProvider.getKeyColumns().size(); i++) { ColumnDefinition columnDefinition = resourceSchemaProvider.getKeyColumns().get(i - 1); setValue(statement, i, (String) keys[i - 1], columnDefinition, columnDefinition.getName()); } logger.debug("Executing statement {}", statement.toString()); ResultSet results = statement.executeQuery(); if(results.next()) { editedObject = new BasicRowProcessor().toMap(results); } } catch(SQLException e) { logger.error("Exception occurred while executing"); throw new DataAccessException(e); } return editedObject == null ? Optional.empty() : Optional.of(DatabaseEntry.buildFrom(editedObject)); } /** * @param offset number of objects to skip * @param count number of objects to retrieve * @param sortColumn column to sort the values by * @param sortDirection direction to sort, true for ascending, false for descending * @return list of entries of up to count long * @throws DataAccessException if an error occurs while accessing the database. */ @Override public List<DatabaseEntry> selectMultiple(long offset, long count, String sortColumn, boolean sortDirection) throws DataAccessException { logger.trace("Selecting multiple {}, {} offset, {} count", tableName, offset, count); List<DatabaseEntry> rows = new ArrayList<>(); try(Connection conn = dataSource.getConnection()) { // TODO: only select columns that are displayed or part of the primary key String sorting = sortDirection ? "asc" : "desc"; String query = String.format("SELECT * FROM %s ORDER BY %s %s LIMIT %d OFFSET %d", tableName, sortColumn, sorting, count, offset); logger.trace("Formatted selectMultiple query: {}", query); PreparedStatement statement = conn.prepareStatement(query); ResultSet results = statement.executeQuery(); while(results.next()) { Map<String, Object> row = new BasicRowProcessor().toMap(results); rows.add(DatabaseEntry.buildFrom(row)); } } catch(SQLException e) { throw new DataAccessException(e); } return rows; } /** * @param postEntry unfiltered user submitted data, must be used with caution * @throws DataAccessException if an error occurs while accessing the database. */ @Override public void insert(FormPostEntry postEntry) throws DataAccessException { logger.trace("Inserting a new {}", tableName); try(Connection conn = dataSource.getConnection()) { // construct the SQL query String query = createInsertStatement(postEntry); PreparedStatement statement = conn.prepareStatement(query); int index = 1; for(String columnName : postEntry.getKeyValues().keySet()) { setValue(statement, index++, postEntry.getKeyValues().get(columnName), getColumnDefinitions().get(columnName), columnName); } for(String columnName : postEntry.getValues().keySet()) { setValue(statement, index++, postEntry.getValues().get(columnName), getColumnDefinitions().get(columnName), columnName); } logger.debug("Prepared statement SQL: {}", query); int updatedRows = statement.executeUpdate(); if(updatedRows != 1) { throw new SQLException("Updated " + updatedRows + ", expected 1"); } } catch(SQLException e) { throw new DataAccessException(e); } } /** * @param postEntry unfiltered user submitted data, must be used with caution * @throws DataAccessException if an error occurs while accessing the database. */ @Override public void update(FormPostEntry postEntry) throws DataAccessException { logger.trace("Updating an existing {}", tableName); try(Connection conn = dataSource.getConnection()) { // construct the SQL query String query = createUpdateQuery(postEntry); logger.debug("Prepared statement SQL: {}", query); PreparedStatement statement = conn.prepareStatement(query); int index = 1; // first bind the SET field = ? portion for(String columnName : postEntry.getValues().keySet()) { setValue(statement, index++, postEntry.getValues().get(columnName), getColumnDefinitions().get(columnName), columnName); } // and next the WHERE field = ? part for(String columnName : postEntry.getKeyValues().keySet()) { setValue(statement, index++, postEntry.getKeyValues().get(columnName), getColumnDefinitions().get(columnName), columnName); } logger.debug("Query: {}", statement.toString()); int updatedRows = statement.executeUpdate(); if(updatedRows != 1) { throw new SQLException("Updated " + updatedRows + ", expected 1"); } } catch(SQLException e) { throw new DataAccessException(e); } } /** * Returns the number of entries in the database of the resource. * * @return number of entries * @throws DataAccessException if an SQL exception occurred */ @Override public int count() throws DataAccessException { try(Connection conn = dataSource.getConnection()) { PreparedStatement statement = conn.prepareStatement(String.format("SELECT COUNT(*) FROM %s", tableName)); ResultSet results = statement.executeQuery(); results.next(); return results.getInt(1); } catch(SQLException e) { throw new DataAccessException(e); } } @Override public void delete(Object... keys) throws DataAccessException { logger.trace("Updating an existing {}", tableName); try(Connection conn = dataSource.getConnection()) { // construct the SQL query String conditions = resourceSchemaProvider.getKeyColumns().stream() .map(x -> String.format("%s = ?", x.getName())) .reduce((s, s2) -> s + " AND " + s2) .orElseThrow(() -> new DataAccessException("Could not generate SQL condition")); PreparedStatement statement = conn.prepareStatement(String.format("DELETE FROM %s WHERE %s", tableName, conditions)); for(int i = 1; i <= resourceSchemaProvider.getKeyColumns().size(); i++) { ColumnDefinition columnDefinition = resourceSchemaProvider.getKeyColumns().get(i - 1); setValue(statement, i, (String) keys[i - 1], columnDefinition, columnDefinition.getName()); } logger.debug("Executing statement {}", statement.toString()); boolean results = statement.execute(); } catch(SQLException e) { throw new DataAccessException(e); } } /** * Creates an SQL update query for the provided postEntry. * * @param postEntry object to construct the update query for * @return update query with unbound parameters */ protected String createUpdateQuery(FormPostEntry postEntry) { String wherePortion = postEntry.getKeyValues().keySet().stream() .map(x -> x + " = ?") .reduce((s, s2) -> s + " AND " + s2).orElse(""); String setPortion = postEntry.getValues().keySet().stream() .map(x -> x + " = ?") .reduce((s, s2) -> s + "," + s2).orElse(""); return String.format("UPDATE %s SET %s WHERE %s", tableName, setPortion, wherePortion); } /** * Creates an SQL insert query for the provided postEntry. * * @param postEntry object to construct the insert query for * @return insert query with unbound parameters */ protected String createInsertStatement(FormPostEntry postEntry) { // obtain a list of all resource columns present in the post data List<String> columnSet = new ArrayList<>(postEntry.getKeyValues().keySet()); columnSet.addAll(postEntry.getValues().keySet()); String parameters = Joiner.on(",").join(Collections.nCopies(columnSet.size(), "?")); String parameterString = Joiner.on(",").join(columnSet); return String.format("INSERT INTO %s (%s) VALUES (%s)", tableName, parameterString, parameters); } /** * Query updater that attempts to use the most specific setX method based on the provided input. * * @param statement statement to fill * @param index index of the parameter to configure * @param value user-provided value * @param columnDefinition column definition, used to obtain type information * @param columnName name of the column being set * @throws DataAccessException exception that may be thrown by {@link PreparedStatement#setObject(int, Object)} and others */ protected void setValue(PreparedStatement statement, int index, String value, ColumnDefinition columnDefinition, String columnName) throws DataAccessException { if(columnDefinition == null) { throw new DataAccessException("Found no column definition for column " + columnName + ", value " + value); } try { if(StringUtils.isEmpty(value)) { // TODO: use setNull here logger.trace("Setting null for column {}", columnDefinition.getName()); statement.setObject(index, null); } else { switch(columnDefinition.getType()) { case integer: statement.setInt(index, Integer.valueOf(value)); break; case bool: statement.setBoolean(index, Boolean.valueOf(value)); break; case datetime: // TODO: handle input-to-date conversion SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date date = format.parse(value); statement.setDate(index, new java.sql.Date(date.getTime())); } catch(ParseException e) { logger.error("Could not parse the provided datetime string: {}", value, e); } break; case string: case text: statement.setString(index, value); break; default: logger.error("Unsupported column definition type {} found, setting without type checking", columnDefinition.getType()); statement.setObject(index, value); break; } } } catch(SQLException e) { logger.error("Could not set {}.{} (type {}) to {}", tableName, columnDefinition.getName(), columnDefinition.getType(), value); throw new DataAccessException(e); } } }
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/dao/GenericSQLDAO.java
Java
mit
12,211
goog.provide('ol.DeviceOrientation'); goog.provide('ol.DeviceOrientationProperty'); goog.require('goog.events'); goog.require('goog.math'); goog.require('ol.Object'); goog.require('ol.has'); /** * @enum {string} */ ol.DeviceOrientationProperty = { ALPHA: 'alpha', BETA: 'beta', GAMMA: 'gamma', HEADING: 'heading', TRACKING: 'tracking' }; /** * @classdesc * The ol.DeviceOrientation class provides access to DeviceOrientation * information and events, see the [HTML 5 DeviceOrientation Specification]( * http://www.w3.org/TR/orientation-event/) for more details. * * Many new computers, and especially mobile phones * and tablets, provide hardware support for device orientation. Web * developers targetting mobile devices will be especially interested in this * class. * * Device orientation data are relative to a common starting point. For mobile * devices, the starting point is to lay your phone face up on a table with the * top of the phone pointing north. This represents the zero state. All * angles are then relative to this state. For computers, it is the same except * the screen is open at 90 degrees. * * Device orientation is reported as three angles - `alpha`, `beta`, and * `gamma` - relative to the starting position along the three planar axes X, Y * and Z. The X axis runs from the left edge to the right edge through the * middle of the device. Similarly, the Y axis runs from the bottom to the top * of the device through the middle. The Z axis runs from the back to the front * through the middle. In the starting position, the X axis points to the * right, the Y axis points away from you and the Z axis points straight up * from the device lying flat. * * The three angles representing the device orientation are relative to the * three axes. `alpha` indicates how much the device has been rotated around the * Z axis, which is commonly interpreted as the compass heading (see note * below). `beta` indicates how much the device has been rotated around the X * axis, or how much it is tilted from front to back. `gamma` indicates how * much the device has been rotated around the Y axis, or how much it is tilted * from left to right. * * For most browsers, the `alpha` value returns the compass heading so if the * device points north, it will be 0. With Safari on iOS, the 0 value of * `alpha` is calculated from when device orientation was first requested. * ol.DeviceOrientation provides the `heading` property which normalizes this * behavior across all browsers for you. * * It is important to note that the HTML 5 DeviceOrientation specification * indicates that `alpha`, `beta` and `gamma` are in degrees while the * equivalent properties in ol.DeviceOrientation are in radians for consistency * with all other uses of angles throughout OpenLayers. * * @see http://www.w3.org/TR/orientation-event/ * * @constructor * @extends {ol.Object} * @fires change Triggered when the device orientation changes. * @param {olx.DeviceOrientationOptions=} opt_options Options. * @api */ ol.DeviceOrientation = function(opt_options) { goog.base(this); var options = goog.isDef(opt_options) ? opt_options : {}; /** * @private * @type {goog.events.Key} */ this.listenerKey_ = null; goog.events.listen(this, ol.Object.getChangeEventType(ol.DeviceOrientationProperty.TRACKING), this.handleTrackingChanged_, false, this); this.setTracking(goog.isDef(options.tracking) ? options.tracking : false); }; goog.inherits(ol.DeviceOrientation, ol.Object); /** * @inheritDoc */ ol.DeviceOrientation.prototype.disposeInternal = function() { this.setTracking(false); goog.base(this, 'disposeInternal'); }; /** * @private * @param {goog.events.BrowserEvent} browserEvent Event. */ ol.DeviceOrientation.prototype.orientationChange_ = function(browserEvent) { var event = /** @type {DeviceOrientationEvent} */ (browserEvent.getBrowserEvent()); if (goog.isDefAndNotNull(event.alpha)) { var alpha = goog.math.toRadians(event.alpha); this.set(ol.DeviceOrientationProperty.ALPHA, alpha); // event.absolute is undefined in iOS. if (goog.isBoolean(event.absolute) && event.absolute) { this.set(ol.DeviceOrientationProperty.HEADING, alpha); } else if (goog.isDefAndNotNull(event.webkitCompassHeading) && goog.isDefAndNotNull(event.webkitCompassAccuracy) && event.webkitCompassAccuracy != -1) { var heading = goog.math.toRadians(event.webkitCompassHeading); this.set(ol.DeviceOrientationProperty.HEADING, heading); } } if (goog.isDefAndNotNull(event.beta)) { this.set(ol.DeviceOrientationProperty.BETA, goog.math.toRadians(event.beta)); } if (goog.isDefAndNotNull(event.gamma)) { this.set(ol.DeviceOrientationProperty.GAMMA, goog.math.toRadians(event.gamma)); } this.dispatchChangeEvent(); }; /** * @return {number|undefined} The euler angle in radians of the device from the * standard Z axis. * @observable * @api */ ol.DeviceOrientation.prototype.getAlpha = function() { return /** @type {number|undefined} */ ( this.get(ol.DeviceOrientationProperty.ALPHA)); }; goog.exportProperty( ol.DeviceOrientation.prototype, 'getAlpha', ol.DeviceOrientation.prototype.getAlpha); /** * @return {number|undefined} The euler angle in radians of the device from the * planar X axis. * @observable * @api */ ol.DeviceOrientation.prototype.getBeta = function() { return /** @type {number|undefined} */ ( this.get(ol.DeviceOrientationProperty.BETA)); }; goog.exportProperty( ol.DeviceOrientation.prototype, 'getBeta', ol.DeviceOrientation.prototype.getBeta); /** * @return {number|undefined} The euler angle in radians of the device from the * planar Y axis. * @observable * @api */ ol.DeviceOrientation.prototype.getGamma = function() { return /** @type {number|undefined} */ ( this.get(ol.DeviceOrientationProperty.GAMMA)); }; goog.exportProperty( ol.DeviceOrientation.prototype, 'getGamma', ol.DeviceOrientation.prototype.getGamma); /** * @return {number|undefined} The heading of the device relative to north, in * radians, normalizing for different browser behavior. * @observable * @api */ ol.DeviceOrientation.prototype.getHeading = function() { return /** @type {number|undefined} */ ( this.get(ol.DeviceOrientationProperty.HEADING)); }; goog.exportProperty( ol.DeviceOrientation.prototype, 'getHeading', ol.DeviceOrientation.prototype.getHeading); /** * Are we tracking the device's orientation? * @return {boolean} The status of tracking changes to alpha, beta and gamma. * If true, changes are tracked and reported immediately. * @observable * @api */ ol.DeviceOrientation.prototype.getTracking = function() { return /** @type {boolean} */ ( this.get(ol.DeviceOrientationProperty.TRACKING)); }; goog.exportProperty( ol.DeviceOrientation.prototype, 'getTracking', ol.DeviceOrientation.prototype.getTracking); /** * @private */ ol.DeviceOrientation.prototype.handleTrackingChanged_ = function() { if (ol.has.DEVICE_ORIENTATION) { var tracking = this.getTracking(); if (tracking && goog.isNull(this.listenerKey_)) { this.listenerKey_ = goog.events.listen(goog.global, 'deviceorientation', this.orientationChange_, false, this); } else if (!tracking && !goog.isNull(this.listenerKey_)) { goog.events.unlistenByKey(this.listenerKey_); this.listenerKey_ = null; } } }; /** * Enable or disable tracking of DeviceOrientation events. * @param {boolean} tracking The status of tracking changes to alpha, beta and * gamma. If true, changes are tracked and reported immediately. * @observable * @api */ ol.DeviceOrientation.prototype.setTracking = function(tracking) { this.set(ol.DeviceOrientationProperty.TRACKING, tracking); }; goog.exportProperty( ol.DeviceOrientation.prototype, 'setTracking', ol.DeviceOrientation.prototype.setTracking);
Koriyama-City/papamama
js/v3.0.0/ol/ol/deviceorientation.js
JavaScript
mit
8,345
var send = require("./index") module.exports = sendJson /* sendJson := (HttpRequest, HttpResponse, Value | { body: Value, headers?: Object<String, String>, statusCode?: Number }) */ function sendJson(req, res, value, replacer, space) { if (!value || (!value.statusCode && !value.headers)) { value = { body: value } } value.headers = value.headers || {} value.body = JSON.stringify(value.body, replacer, space) value.headers["Content-Type"] = "application/json" send(req, res, value) }
robertjd/send-data
json.js
JavaScript
mit
550
package moltin.example_moltin.activities; import android.content.Context; import android.content.Intent; import android.graphics.Point; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBar; import android.view.Display; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu; import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity; import org.json.JSONObject; import java.util.ArrayList; import moltin.android_sdk.Moltin; import moltin.android_sdk.utilities.Constants; import moltin.example_moltin.R; import moltin.example_moltin.data.CartItem; import moltin.example_moltin.data.CollectionItem; import moltin.example_moltin.data.TotalCartItem; import moltin.example_moltin.fragments.CartFragment; import moltin.example_moltin.fragments.CollectionFragment; public class CollectionActivity extends SlidingFragmentActivity implements CollectionFragment.OnCollectionFragmentPictureDownloadListener, CartFragment.OnFragmentUpdatedListener, CartFragment.OnFragmentChangeListener, CollectionFragment.OnCollectionFragmentInteractionListener { private Moltin moltin; private ArrayList<CollectionItem> items; private ArrayList<CartItem> itemsForCart; private TotalCartItem cart; public static CollectionActivity instance = null; private SlidingMenu menu; private android.app.Fragment mContent; private CartFragment menuFragment; private Point screenSize; private int position=0; private LinearLayout layIndex; private int currentOffset=0; private int limit=20; private boolean endOfList=false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); instance = this; moltin = new Moltin(this); menu = getSlidingMenu(); menu.setShadowWidth(20); menu.setBehindWidth(getListviewWidth()-50); menu.setTouchModeBehind(SlidingMenu.TOUCHMODE_FULLSCREEN); menu.setMode(SlidingMenu.RIGHT); menu.setFadeEnabled(false); menu.setBehindScrollScale(0.5f); setSlidingActionBarEnabled(true); currentOffset=0; endOfList=false; items=new ArrayList<CollectionItem>(); if (savedInstanceState != null) mContent = getFragmentManager().getFragment(savedInstanceState, "mContentCollection"); if (mContent == null) { mContent = CollectionFragment.newInstance(items,getListviewWidth(),currentOffset); } setContentView(R.layout.activity_collection); getFragmentManager() .beginTransaction() .replace(R.id.container, mContent) .commit(); itemsForCart=new ArrayList<CartItem>(); cart=new TotalCartItem(new JSONObject()); cart.setItems(itemsForCart); setBehindContentView(R.layout.cart_content_frame); menuFragment = CartFragment.newInstance(cart, getApplicationContext()); getFragmentManager() .beginTransaction() .replace(R.id.cart_content_frame, menuFragment) .commit(); ((TextView)findViewById(R.id.txtActivityTitle)).setTypeface(Typeface.createFromAsset(getResources().getAssets(), getString(R.string.font_regular))); ((TextView)findViewById(R.id.txtActivityTitleCart)).setTypeface(Typeface.createFromAsset(getResources().getAssets(), getString(R.string.font_regular))); try { moltin.authenticate(getString(R.string.moltin_api_key), new Handler.Callback() { @Override public boolean handleMessage(Message msg) { if (msg.what == Constants.RESULT_OK) { try { getCollections(); } catch (Exception e) { e.printStackTrace(); } return true; } else { return false; } } }); } catch (Exception e) { e.printStackTrace(); } } public void setInitialPosition() { layIndex = (LinearLayout)findViewById(R.id.layIndex); if(((LinearLayout) layIndex).getChildCount() > 0) ((LinearLayout) layIndex).removeAllViews(); for(int i=0;i<items.size();i++) { ImageView img=new ImageView(this); if(position==i) img.setImageDrawable(getResources().getDrawable(R.drawable.circle_active)); else img.setImageDrawable(getResources().getDrawable(R.drawable.circle_inactive)); final float scale = getApplicationContext().getResources().getDisplayMetrics().density; ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams( (int)(12*scale + 0.5f), (int)(12*scale + 0.5f)); params.leftMargin = (int)(5*scale + 0.5f); params.rightMargin = (int)(5*scale + 0.5f); params.topMargin = (int)(5*scale + 0.5f); params.bottomMargin = (int)(40*scale + 0.5f); img.setLayoutParams(params); layIndex.addView(img); } } public void setPosition(int newPosition) { if(newPosition!=position) { if(((LinearLayout) layIndex).getChildCount() > 0) { ((ImageView)layIndex.getChildAt(position)).setImageDrawable(getResources().getDrawable(R.drawable.circle_inactive)); ((ImageView)layIndex.getChildAt(newPosition)).setImageDrawable(getResources().getDrawable(R.drawable.circle_active)); position=newPosition; } } } public void getNewPage(int currentNumber) { currentOffset=currentNumber; try { getCollections(); } catch (Exception e) { e.printStackTrace(); } } private int getListviewWidth() { Display display = getWindowManager().getDefaultDisplay(); screenSize = new Point(); display.getSize(screenSize); return screenSize.x; } public void onItemClickHandler(View view) { try { Intent intent = new Intent(this, ProductActivity.class); intent.putExtra("ID",view.getTag(R.id.txtDescription).toString()); intent.putExtra("COLLECTION",view.getTag(R.id.txtCollectionName).toString()); startActivity(intent); } catch (Exception e) { e.printStackTrace(); } } public void onClickHandler(View view) { try { switch (view.getId()) { case R.id.btnPlus: ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.VISIBLE); moltin.cart.update(menuFragment.cart.getItems().get((int)view.getTag()).getItemIdentifier(),new String[][]{{"quantity",""+(menuFragment.cart.getItems().get((int)view.getTag()).getItemQuantity()+1)}}, new Handler.Callback() {//"wf60kt82vtzkjIMslZ1FmDyV8WUWNQlLxUiRVLS4", new Handler.Callback() { @Override public boolean handleMessage(Message msg) { menuFragment.refresh(); if (msg.what == Constants.RESULT_OK) { try { } catch (Exception e) { e.printStackTrace(); } return true; } else { ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.GONE); return false; } } }); break; case R.id.btnMinus: ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.VISIBLE); moltin.cart.update(menuFragment.cart.getItems().get((int)view.getTag()).getItemIdentifier(),new String[][]{{"quantity",""+(menuFragment.cart.getItems().get((int)view.getTag()).getItemQuantity()-1)}}, new Handler.Callback() {//"wf60kt82vtzkjIMslZ1FmDyV8WUWNQlLxUiRVLS4", new Handler.Callback() { @Override public boolean handleMessage(Message msg) { menuFragment.refresh(); if (msg.what == Constants.RESULT_OK) { try { } catch (Exception e) { e.printStackTrace(); } return true; } else { ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.GONE); return false; } } }); break; case R.id.btnDelete: ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.VISIBLE); moltin.cart.remove(menuFragment.cart.getItems().get((int)view.getTag()).getItemIdentifier(), new Handler.Callback() {//"wf60kt82vtzkjIMslZ1FmDyV8WUWNQlLxUiRVLS4", new Handler.Callback() { @Override public boolean handleMessage(Message msg) { menuFragment.refresh(); if (msg.what == Constants.RESULT_OK) { try { } catch (Exception e) { e.printStackTrace(); } return true; } else { ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.GONE); return false; } } }); break; case R.id.btnCheckout: if(menuFragment.cart!=null && menuFragment.cart.getItemTotalNumber()!=null && menuFragment.cart.getItemTotalNumber()>0) { Intent intent = new Intent(this, BillingActivity.class); intent.putExtra("JSON",menuFragment.cart.getItemJson().toString()); startActivity(intent); } else { Toast.makeText(getApplicationContext(), getString(R.string.alert_cart_is_empty), Toast.LENGTH_LONG).show(); } break; case R.id.btnMenu: onHomeClicked(); break; case R.id.btnCart: onHomeClicked(); break; } } catch (Exception e) { e.printStackTrace(); } } public void onHomeClicked() { toggle(); } private void getCollections() throws Exception { if(endOfList) return; ((LinearLayout)findViewById(R.id.layMainLoading)).setVisibility(View.VISIBLE); moltin.collection.listing(new String[][]{{"limit",Integer.toString(limit)},{"offset",Integer.toString(currentOffset)}},new Handler.Callback() { @Override public boolean handleMessage(Message msg) { if (msg.what == Constants.RESULT_OK) { try { JSONObject json=(JSONObject)msg.obj; if(json.has("status") && json.getBoolean("status") && json.has("result") && json.getJSONArray("result").length()>0) { for(int i=0;i<json.getJSONArray("result").length();i++) { items.add(new CollectionItem(json.getJSONArray("result").getJSONObject(i))); } } if(items.size()==json.getJSONObject("pagination").getInt("total")) endOfList=true; else endOfList=false; if(currentOffset>0) { onCollectionFragmentPictureDownloadListener(); } ((CollectionFragment)mContent).customRecyclerView.getAdapter().notifyDataSetChanged(); setInitialPosition(); } catch (Exception e) { e.printStackTrace(); } return true; } else { return false; } } }); } @Override public void onFragmentInteractionForCollectionItem(String itemId) { } @Override protected void onDestroy() { try { instance=null; } catch (Exception e) { e.printStackTrace(); } super.onDestroy(); } @Override protected void onResume() { try { menuFragment.refresh(); } catch (Exception e) { e.printStackTrace(); } super.onResume(); } @Override public void onFragmentChangeForCartItem(TotalCartItem cart) { ((TextView)findViewById(R.id.txtTotalPrice)).setText(cart.getItemTotalPrice()); } @Override public void onFragmentUpdatedForCartItem() { ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.GONE); } @Override public void onCollectionFragmentPictureDownloadListener() { try { ((LinearLayout) findViewById(R.id.layMainLoading)).setVisibility(View.GONE); } catch (Exception e) { e.printStackTrace(); } } }
moltin/android-example
app/src/main/java/moltin/example_moltin/activities/CollectionActivity.java
Java
mit
14,543
//--------------------------------------------------------------------------- // // <copyright file="CanExecuteChangedEventManager.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: Manager for the CanExecuteChanged event in the "weak event listener" // pattern. See WeakEventTable.cs for an overview. // //--------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; // ConditionalWeakTable using System.Windows; // WeakEventManager using MS.Internal; // NamedObject namespace System.Windows.Input { /// <summary> /// Manager for the ICommand.CanExecuteChanged event. /// </summary> public class CanExecuteChangedEventManager : WeakEventManager { #region Constructors // // Constructors // private CanExecuteChangedEventManager() { } #endregion Constructors #region Public Methods // // Public Methods // /// <summary> /// Add a handler for the given source's event. /// </summary> public static void AddHandler(ICommand source, EventHandler<EventArgs> handler) { if (source == null) throw new ArgumentNullException("source"); if (handler == null) throw new ArgumentNullException("handler"); CurrentManager.PrivateAddHandler(source, handler); } /// <summary> /// Remove a handler for the given source's event. /// </summary> public static void RemoveHandler(ICommand source, EventHandler<EventArgs> handler) { if (source == null) throw new ArgumentNullException("source"); if (handler == null) throw new ArgumentNullException("handler"); CurrentManager.PrivateRemoveHandler(source, handler); } #endregion Public Methods #region Protected Methods // // Protected Methods // /// <summary> /// Listen to the given source for the event. /// </summary> protected override void StartListening(object source) { // never called } /// <summary> /// Stop listening to the given source for the event. /// </summary> protected override void StopListening(object source) { // never called } protected override bool Purge(object source, object data, bool purgeAll) { ICommand command = source as ICommand; List<HandlerSink> list = data as List<HandlerSink>; List<HandlerSink> toRemove = null; bool foundDirt = false; bool removeList = purgeAll || source == null; // find dead entries to be removed from the list if (!removeList) { foreach (HandlerSink sink in list) { if (sink.IsInactive) { if (toRemove == null) { toRemove = new List<HandlerSink>(); } toRemove.Add(sink); } } removeList = (toRemove != null && toRemove.Count == list.Count); } if (removeList) { toRemove = list; } foundDirt = (toRemove != null); // if the whole list is going away, remove the data (unless parent table // is already doing that for us - purgeAll=true) if (removeList && !purgeAll && source != null) { Remove(source); } // remove and detach the dead entries if (foundDirt) { foreach (HandlerSink sink in toRemove) { EventHandler<EventArgs> handler = sink.Handler; sink.Detach(); if (!removeList) // if list is going away, no need to remove from it { list.Remove(sink); } if (handler != null) { RemoveHandlerFromCWT(handler, _cwt); } } } return foundDirt; } #endregion Protected Methods #region Private Properties // // Private Properties // // get the event manager for the current thread private static CanExecuteChangedEventManager CurrentManager { get { Type managerType = typeof(CanExecuteChangedEventManager); CanExecuteChangedEventManager manager = (CanExecuteChangedEventManager)GetCurrentManager(managerType); // at first use, create and register a new manager if (manager == null) { manager = new CanExecuteChangedEventManager(); SetCurrentManager(managerType, manager); } return manager; } } #endregion Private Properties #region Private Methods // // Private Methods // private void PrivateAddHandler(ICommand source, EventHandler<EventArgs> handler) { // get the list of sinks for this source, creating if necessary List<HandlerSink> list = (List<HandlerSink>)this[source]; if (list == null) { list = new List<HandlerSink>(); this[source] = list; } // add a new sink to the list HandlerSink sink = new HandlerSink(this, source, handler); list.Add(sink); // keep the handler alive AddHandlerToCWT(handler, _cwt); } private void PrivateRemoveHandler(ICommand source, EventHandler<EventArgs> handler) { // get the list of sinks for this source List<HandlerSink> list = (List<HandlerSink>)this[source]; if (list != null) { HandlerSink sinkToRemove = null; bool foundDirt = false; // look for the given sink on the list foreach (HandlerSink sink in list) { if (sink.Matches(source, handler)) { sinkToRemove = sink; break; } else if (sink.IsInactive) { foundDirt = true; } } // remove the sink (outside the loop, to avoid re-entrancy issues) if (sinkToRemove != null) { list.Remove(sinkToRemove); sinkToRemove.Detach(); RemoveHandlerFromCWT(handler, _cwt); } // if we noticed any stale sinks, schedule a purge if (foundDirt) { ScheduleCleanup(); } } } // add the handler to the CWT - this keeps the handler alive throughout // the lifetime of the target, without prolonging the lifetime of // the target void AddHandlerToCWT(Delegate handler, ConditionalWeakTable<object, object> cwt) { object value; object target = handler.Target; if (target == null) target = StaticSource; if (!cwt.TryGetValue(target, out value)) { // 99% case - the target only listens once cwt.Add(target, handler); } else { // 1% case - the target listens multiple times // we store the delegates in a list List<Delegate> list = value as List<Delegate>; if (list == null) { // lazily allocate the list, and add the old handler Delegate oldHandler = value as Delegate; list = new List<Delegate>(); list.Add(oldHandler); // install the list as the CWT value cwt.Remove(target); cwt.Add(target, list); } // add the new handler to the list list.Add(handler); } } void RemoveHandlerFromCWT(Delegate handler, ConditionalWeakTable<object, object> cwt) { object value; object target = handler.Target; if (target == null) target = StaticSource; if (_cwt.TryGetValue(target, out value)) { List<Delegate> list = value as List<Delegate>; if (list == null) { // 99% case - the target is removing its single handler _cwt.Remove(target); } else { // 1% case - the target had multiple handlers, and is removing one list.Remove(handler); if (list.Count == 0) { _cwt.Remove(target); } } } } #endregion Private Methods #region Private Data ConditionalWeakTable<object, object> _cwt = new ConditionalWeakTable<object, object>(); static readonly object StaticSource = new NamedObject("StaticSource"); #endregion Private Data #region HandlerSink // Some sources delegate their CanExecuteChanged event to another event // on a different object. For example, RoutedCommands delegate to // CommandManager.RequerySuggested, as do some custom commands (dev11 281808). // Similarly, some 3rd-party commands delegate to a custom class (dev11 449384). // The standard weak-event pattern won't work in these cases. It registers // the source at AddHandler-time, and uses the 'sender' argument at event-delivery // time to look up the relevant information; if these are different, we won't find // the information and therefore won't deliver the event to the intended listeners. // // To cope with this, we use the HandlerSink class. Each call to AddHandler // creates a new HandlerSink, in which we record the original source and // handler, and register a local listener. When the event is raised to a // sink's local listener, the sink merely passes the event along to the original // handler. With judicious use of WeakReference and ConditionalWeakTable, // we can do this without extending the lifetime of the original source or // listener, and without leaking any of the internal data structures. // Here's a diagram illustrating a Button listening to CanExecuteChanged from // a Command that delegates to some other event Proxy.Foo. // // Button --*--> OriginalHandler <---o--- Sink --------o------------> Command // ^ | ^ ^ // --------------------- | | // List ------- ----> LocalHandler <---- Proxy.Foo // Table: (Command) ---^ // // Legend: Weak reference: --o--> // CWT reference: --*--> // Strong reference: -----> // // For each source (i.e. Command), the Manager stores a list of Sinks pertaining // to that Command. Each Sink remembers (weakly) its original source and handler, // and registers for the Command.CanExecuteChanged event in the normal way. // The event may be raised from a different place (Proxy.Foo), but the Sink // knows to pass the event along to the original handler. The Manager uses a // ConditionalWeakTable to keep the original handlers alive, and the Sink // keeps its local handler alive with a local strong reference. // The internal data structures (Sink, List entry, LocalHandler) can be purged // when either the Button or the Command is GC'd. Both conditions are // testable by querying the Sink's weak references. private class HandlerSink { public HandlerSink(CanExecuteChangedEventManager manager, ICommand source, EventHandler<EventArgs> originalHandler) { _manager = manager; _source = new WeakReference(source); _originalHandler = new WeakReference(originalHandler); // In WPF 4.0, elements with commands (Button, Hyperlink, etc.) listened // for CanExecuteChanged and also stored a strong reference to the handler // (in an uncommon field). Some third-party commands relied on this // undocumented implementation detail by storing a weak reference to // the handler. (One such example is Win8 Server Manager's DelegateCommand - // Microsoft.Management.UI.DelegateCommand<T> - see Win8 Bugs 588129.) // // Commands that do this won't work with normal listeners: the listener // simply calls command.CanExecuteChanged += new EventHandler(MyMethod); // the command stores a weak-ref to the handler, no one has a strong-ref // so the handler is soon GC'd, after which the event doesn't get // delivered to the listener. // // In WPF 4.5, Button et al. use this weak event manager to listen to // CanExecuteChanged, indirectly. Only the manager actually listens // directly to the command's event. For compat, the manager stores a // strong reference to its handler. The only reason for this is to // support those commands that relied on the 4.0 implementation. _onCanExecuteChangedHandler = new EventHandler(OnCanExecuteChanged); // BTW, the reason commands used weak-references was to avoid leaking // the Button - see Dev11 267916. This is fixed in 4.5, precisely // by using the weak-event pattern. Commands can now implement // the CanExecuteChanged event the default way - no need for any // fancy weak-reference tricks (which people usually get wrong in // general, as in the case of DelegateCommand<T>). // register the local listener source.CanExecuteChanged += _onCanExecuteChangedHandler; } public bool IsInactive { get { return _source == null || !_source.IsAlive || _originalHandler == null || !_originalHandler.IsAlive; } } public EventHandler<EventArgs> Handler { get { return (_originalHandler != null) ? (EventHandler<EventArgs>)_originalHandler.Target : null; } } public bool Matches(ICommand source, EventHandler<EventArgs> handler) { return (_source != null && (ICommand)_source.Target == source) && (_originalHandler != null && (EventHandler<EventArgs>)_originalHandler.Target == handler); } public void Detach() { if (_source != null) { ICommand source = (ICommand)_source.Target; if (source != null) { source.CanExecuteChanged -= _onCanExecuteChangedHandler; } _source = null; _originalHandler = null; } } void OnCanExecuteChanged(object sender, EventArgs e) { // this protects against re-entrancy: a purge happening // while a CanExecuteChanged event is being delivered if (_source == null) return; // if the sender is our own CommandManager, the original // source delegated is CanExecuteChanged event to // CommandManager.RequerySuggested. We use the original // source as the sender when passing the event along, so that // listeners can distinguish which command is changing. // We could do that for 3rd-party commands that delegate as // well, but we don't for compat with 4.0. if (sender is CommandManager) { sender = _source.Target; } // pass the event along to the original listener EventHandler<EventArgs> handler = (EventHandler<EventArgs>)_originalHandler.Target; if (handler != null) { handler(sender, e); } else { // listener has been GC'd - schedule a purge _manager.ScheduleCleanup(); } } CanExecuteChangedEventManager _manager; WeakReference _source; WeakReference _originalHandler; EventHandler _onCanExecuteChangedHandler; // see remarks in the constructor } #endregion HandlerSink } }
mind0n/hive
Cache/Libs/net46/wpf/src/Core/CSharp/System/Windows/Input/Command/CanExecuteChangedEventManager.cs
C#
mit
18,139
/* Revise Listing 3.8, Lottery.java, to generate a lottery of a three-digit number. The program prompts the user to enter a three-digit number and determines whether the user wins according to the following rules: 1. If the user input matches the lottery number in the exact order, the award is $10,000. 2. If all digits in the user input match all digits in the lottery number, the award is $3,000. 3. If one digit in the user input matches a digit in the lottery number, the award is $1,000. */ import java.util.Scanner; public class E3_15 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a three-digit number: "); String numString = input.nextLine(); displayLotteryOutcome(numString); } private static void displayLotteryOutcome(String numString) { int a = Integer.parseInt(numString.charAt(0) + ""); int b = Integer.parseInt(numString.charAt(1) + ""); int c = Integer.parseInt(numString.charAt(2) + ""); int x = generateLottery(); int y = generateLottery(); int z = generateLottery(); StringBuilder output = new StringBuilder(); if (a == x && b == y && c == z) { output.append("Matched exact order: you win $10,000"); } else if ((a == x && c == y && b == z) || (b == x && c == y && a == z) || (b == x && a == y && c == z) || (c == x && a == y && b == z) || (c == x && b == y && a == z)) { output.append("All digits match: you win $3,000"); } else if ((a == x || a == y || a == z) || (b == x || b == y || b == z) || (c == x || c == y || c == z)) { output.append("At least one digit matches: you win $1,000"); } else { output.append("Too bad! You win nothing!"); } System.out.println("Lottery: " + x + y + z); System.out.println(output); } private static int generateLottery() { return (int)(Math.random() * 10); } }
maxalthoff/intro-to-java-exercises
03/E3_15/E3_15.java
Java
mit
2,006
var duplex = require('duplexer') var through = require('through') module.exports = function (counter) { var countries = {} function count(input) { countries[input.country] = (countries[input.country] || 0) + 1 } function end() { counter.setCounts(countries) } return duplex(through(count, end), counter) }
hkhamm/nodejs_stream_adventure
duplexer_redux.js
JavaScript
mit
330
<?php /** * Entity factory * * @package Walmart API PHP Client * @author Piotr Gadzinski <dev@gadoma.com> * @copyright Copyright (c) 2016 * @license MIT * @since 05/04/2016 */ namespace WalmartApiClient\Factory; class EntityFactory implements EntityFactoryInterface { /** * {@inheritdoc} */ public function instance($className, array $entityData = []) { if (!class_exists($className)) { throw new \InvalidArgumentException("Class $className does not exist."); } $reflector = new \ReflectionClass($className); return $reflector->newInstanceArgs([$entityData]); } }
Gadoma/walmart-api-php-client
src/WalmartApiClient/Factory/EntityFactory.php
PHP
mit
667
// Copyright (c) Christophe Gondouin (CGO Conseils). All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; namespace XrmFramework { [AttributeUsage(AttributeTargets.Field)] public class ExternalValueAttribute : Attribute { public ExternalValueAttribute(string externalValue) { ExternalValue = externalValue; } public string ExternalValue { get; } } }
cgoconseils/XrmFramework
src/XrmFramework/Attributes/ExternalValueAttribute.cs
C#
mit
494
module Keisan module Functions class ExpressionFunction < Function attr_reader :arguments, :expression def initialize(name, arguments, expression, transient_definitions) super(name, arguments.count) if expression.is_a?(::String) @expression = AST::parse(expression) else @expression = expression.deep_dup end @arguments = arguments @transient_definitions = transient_definitions end def freeze @arguments.freeze @expression.freeze super end def call(context, *args) validate_arguments!(args.count) local = local_context_for(context) arguments.each.with_index do |arg_name, i| local.register_variable!(arg_name, args[i]) end expression.value(local) end def value(ast_function, context = nil) validate_arguments!(ast_function.children.count) context ||= Context.new argument_values = ast_function.children.map {|child| child.value(context)} call(context, *argument_values) end def evaluate(ast_function, context = nil) validate_arguments!(ast_function.children.count) context ||= Context.new local = local_context_for(context) argument_values = ast_function.children.map {|child| child.evaluate(context)} arguments.each.with_index do |arg_name, i| local.register_variable!(arg_name, argument_values[i].evaluate(context)) end expression.evaluated(local) end def simplify(ast_function, context = nil) validate_arguments!(ast_function.children.count) ast_function.instance_variable_set( :@children, ast_function.children.map {|child| child.evaluate(context)} ) if ast_function.children.all? {|child| child.is_a?(AST::ConstantLiteral)} value(ast_function, context).to_node.simplify(context) else ast_function end end # Multi-argument functions work as follows: # Given f(x, y), in general we will take the derivative with respect to t, # and x = x(t), y = y(t). For instance d/dt f(2*t, t+1). # In this case, chain rule gives derivative: # dx(t)/dt * f_x(x(t), y(t)) + dy(t)/dt * f_y(x(t), y(t)), # where f_x and f_y are the x and y partial derivatives respectively. def differentiate(ast_function, variable, context = nil) validate_arguments!(ast_function.children.count) local = local_context_for(context) argument_values = ast_function.children.map {|child| child.evaluated(local)} argument_derivatives = ast_function.children.map do |child| child.differentiated(variable, context) end partial_derivatives = calculate_partial_derivatives(context) AST::Plus.new( argument_derivatives.map.with_index {|argument_derivative, i| partial_derivative = partial_derivatives[i] argument_variables.each.with_index {|argument_variable, j| partial_derivative = partial_derivative.replaced(argument_variable, argument_values[j]) } AST::Times.new([argument_derivative, partial_derivative]) } ) end private def argument_variables arguments.map {|argument| AST::Variable.new(argument)} end def calculate_partial_derivatives(context) argument_variables.map.with_index do |variable, i| partial_derivative = expression.differentiated(variable, context) end end def local_context_for(context = nil) context ||= Context.new context.spawn_child(definitions: @transient_definitions, shadowed: @arguments, transient: true) end end end end
project-eutopia/keisan
lib/keisan/functions/expression_function.rb
Ruby
mit
3,851
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package zmarkdown.javaeditor; import org.python.util.PythonInterpreter; import org.python.core.*; /** * * @author firm1 */ public class EMarkdown{ PythonInterpreter interp; public EMarkdown() { interp = new PythonInterpreter(); interp.exec("from markdown import Markdown"); interp.exec("from markdown.extensions.zds import ZdsExtension"); interp.exec("from smileys_definition import smileys"); } public String html(String chaine) { interp.set("text", chaine); interp.exec("render = Markdown(extensions=(ZdsExtension({'inline': False, 'emoticons': smileys}),),safe_mode = 'escape', enable_attributes = False, tab_length = 4, output_format = 'html5', smart_emphasis = True, lazy_ol = True).convert(text)"); PyString render = interp.get("render", PyString.class); return render.toString(); } }
firm1/zmarkdown-editor
src/zmarkdown/javaeditor/EMarkdown.java
Java
mit
1,070
using System; using NetOffice; using NetOffice.Attributes; namespace NetOffice.OfficeApi.Enums { /// <summary> /// SupportByVersion Office 12, 14, 15, 16 /// </summary> ///<remarks> MSDN Online Documentation: <see href="https://docs.microsoft.com/en-us/office/vba/api/Office.SignatureType"/> </remarks> [SupportByVersion("Office", 12,14,15,16)] [EntityType(EntityType.IsEnum)] public enum SignatureType { /// <summary> /// SupportByVersion Office 12, 14, 15, 16 /// </summary> /// <remarks>0</remarks> [SupportByVersion("Office", 12,14,15,16)] sigtypeUnknown = 0, /// <summary> /// SupportByVersion Office 12, 14, 15, 16 /// </summary> /// <remarks>1</remarks> [SupportByVersion("Office", 12,14,15,16)] sigtypeNonVisible = 1, /// <summary> /// SupportByVersion Office 12, 14, 15, 16 /// </summary> /// <remarks>2</remarks> [SupportByVersion("Office", 12,14,15,16)] sigtypeSignatureLine = 2, /// <summary> /// SupportByVersion Office 12, 14, 15, 16 /// </summary> /// <remarks>3</remarks> [SupportByVersion("Office", 12,14,15,16)] sigtypeMax = 3 } }
NetOfficeFw/NetOffice
Source/Office/Enums/SignatureType.cs
C#
mit
1,139
export default function() { let directive = { restrict: 'E', replace: true, scope: { ad: '=' }, templateUrl: './directives/adCard/template.html', controller: ['$scope', ($scope) => { if ($scope.ad.thumbnail) { $scope.ad.previewImg = `${$scope.ad.thumbnail.base_url}/card/${$scope.ad.thumbnail.path}`; } else { $scope.ad.previewImg = '/src/images/car2.png'; } if (120 <= $scope.ad.body.length) { $scope.ad.shortBody = `${$scope.ad.body.slice(0, 119).trim()}...`; } else { $scope.ad.shortBody = $scope.ad.body; } }] }; return directive; }
angeldaniel-adcm/segunda-mano
app/directives/adCard/directive.js
JavaScript
mit
598
<?php /** * Get Partial * Get and render a partial template file. * * @since 1.0.0 * * $part: (string) name of the partial, relative to * the _templates/partials directory. */ function get_partial( $part ) { # Get theme object global $_theme; return $_theme->get_partial($part); } /** * Get Header * Get header partial. * * @since 1.0.0 * * $name: (string) name of custom header file. */ function get_header( $name = 'header' ) { return get_partial($name); } /** * Get Footer * Get footer partial. * * @since 1.0.0 * * $name: (string) name of custom footer file. */ function get_footer( $name = 'footer' ) { return get_partial($name); } /** * Get Sidebar * Get sidebar partial. * * @since 1.0.0 * * $name: (string) name of custom sidebar file. */ function get_sidebar( $name = 'sidebar' ) { return get_partial($name); } /** * Theme Add Meta * * @since 1.0.1 * * $meta: (array) meta tags to add (key => value) */ function theme_add_meta( array $meta = array() ) { # Get Page Array $page = get('page'); # Merge New Data $page = array_merge($page, $meta); # Update Page Array set('page', $page); # Return updated array return $page; } /** * Theme Remove Meta * * @since 1.0.1 * * $key: (string) key of the meta data to remove */ function theme_remove_meta( $key ) { # Get Page Array $page = get('page'); # Protected Keys $protected = array( 'is_home', 'path', 'slug' ); # Check Key is not protected if ( in_array($key, $protected) ) { return false; } # Check Key exists if ( isset($page[$key]) ) { # Remove value unset($page[$key]); # Update Page Array set('page', $page); return $page; } return false; } /** * Assets Dir * Return location of assets relative to * the ROOT_DIR. * * @since 1.0.1 * * $prefix: (string) string to prepend to the returned value. * $print: (bool) print the value to the screen */ function assets_dir( $prefix = '/', $print = true ) { # Get Theme global $_theme; # Get Current Theme Location $location = $_theme->prop('dir'); if ( $print === true ) { echo $prefix . $location . '/assets'; } else { return $prefix . $location . '/assets'; } }
chrismademe/ga
_includes/core/functions/theme.php
PHP
mit
2,362
var app = require('app'); // Module to control application life. var BrowserWindow = require('browser-window'); // Module to create native browser window. // Report crashes to our server. require('crash-reporter').start(); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. var mainWindow = null; // Quit when all windows are closed. app.on('window-all-closed', function() { 'use strict'; // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit(); } }); // This method will be called when Electron has finished // initialization and is ready to create browser windows. app.on('ready', function() { 'use strict'; // Create the browser window. mainWindow = new BrowserWindow({ width: 1024, height: 768, title: 'Build & Deploy', 'auto-hide-menu-bar': true }); // and load the index.html of the app. mainWindow.loadUrl('file://' + __dirname + '/index.html'); // Emitted when the window is closed. mainWindow.on('closed', function() { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; }); });
KillerCodeMonkey/angularjs-electron-app
main.js
JavaScript
mit
1,497
using System.Collections.Generic; using System.Linq; using ThoughtWorks.ConferenceTrackManager.Models; namespace ThoughtWorks.ConferenceTrackManager.App { public interface ITalkDistributor { bool DistributeTalksAcrossSessions(IList<IConferenceSession> sessions, IList<ITalk> allTalks); } public class TalkDistributor : ITalkDistributor { public bool DistributeTalksAcrossSessions(IList<IConferenceSession> sessions, IList<ITalk> talks) { var successfullyDistributedTalks = true; var sortedTalks = talks.OrderByDescending(t => t.LengthInMinutes).ToList(); var talkIndex = 0; while (talkIndex < sortedTalks.Count()) { var successfullyAddedTalkToSession = false; foreach (var session in sessions) { successfullyAddedTalkToSession = session.TryIncludeTalkInSession(sortedTalks[talkIndex]); if (successfullyAddedTalkToSession) { talkIndex = talkIndex + 1; } } if (!successfullyAddedTalkToSession) { successfullyDistributedTalks = false; talkIndex = talkIndex + 1; } } return successfullyDistributedTalks; } } }
EvanPalmer/TWConferenceTrackManager
src/ThoughtWorks.ConferenceTrackManager/App/TalkDistributor.cs
C#
mit
1,410
import React from 'react'; import styled from 'styled-components'; import Item from './Item'; import parchment from '../assets/parchment.png'; import chest from '../assets/chest.png'; const Container = styled.div` background: url(${parchment}); position: relative; height: 286px; width: 303px; align-self: center; margin: 10px; `; const Items = styled.div` position: absolute; display: flex; flex-direction: row; flex-wrap: wrap; align-items: center; top: 78px; left: 130px; width: 108px; `; const Chest = styled.div` position: absolute; background: url(${chest}); image-rendering: pixelated; width: 92px; height: 92px; top: 138px; left: 34px; `; const Clue = ({ rewards, className, style }) => ( <Container className={className} style={style}> <Items> {rewards.map(reward => ( <Item key={reward.id} id={reward.id} amount={reward.amount} /> ))} </Items> <Chest /> </Container> ); export default Clue;
FakeYou/treasure-trails
src/components/Clue.js
JavaScript
mit
946
/* cryptr is a simple aes-256-gcm encrypt and decrypt module for node.js Copyright (c) 2014 Maurice Butler 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. */ const crypto = require("crypto"); const algorithm = "aes-256-gcm"; const ivLength = 16; const saltLength = 64; const tagLength = 16; const tagPosition = saltLength + ivLength; const encryptedPosition = tagPosition + tagLength; function Cryptr(secret) { if (!secret || typeof secret !== "string") { throw new Error("Cryptr: secret must be a non-0-length string"); } function getKey(salt) { return crypto.pbkdf2Sync(secret, salt, 100000, 32, "sha512"); } this.encrypt = function encrypt(value) { if (value == null) { throw new Error("value must not be null or undefined"); } const iv = crypto.randomBytes(ivLength); const salt = crypto.randomBytes(saltLength); const key = getKey(salt); const cipher = crypto.createCipheriv(algorithm, key, iv); const encrypted = Buffer.concat([cipher.update(String(value), "utf8"), cipher.final()]); const tag = cipher.getAuthTag(); return Buffer.concat([salt, iv, tag, encrypted]).toString("hex"); }; this.decrypt = function decrypt(value) { if (value == null) { throw new Error("value must not be null or undefined"); } const stringValue = Buffer.from(String(value), "hex"); const salt = stringValue.slice(0, saltLength); const iv = stringValue.slice(saltLength, tagPosition); const tag = stringValue.slice(tagPosition, encryptedPosition); const encrypted = stringValue.slice(encryptedPosition); const key = getKey(salt); const decipher = crypto.createDecipheriv(algorithm, key, iv); decipher.setAuthTag(tag); return decipher.update(encrypted) + decipher.final("utf8"); }; } module.exports = Cryptr;
xtremespb/zoia
src/shared/lib/cryptr.js
JavaScript
mit
2,906
'use strict'; /* global Parse */ angular.module('main').factory('ParseFile', function ($q) { return { upload: function (base64) { var defer = $q.defer(); var parseFile = new Parse.File('image.jpg', { base64: base64 }); parseFile.save({ success: function (savedFile) { defer.resolve(savedFile); }, error: function (error) { defer.reject(error); } }); return defer.promise; }, uploadFile: function (file) { var defer = $q.defer(); var parseFile = new Parse.File('image.jpg', file); parseFile.save({ success: function (savedFile) { defer.resolve(savedFile); }, error: function (error) { defer.reject(error); } }); return defer.promise; }, }; });
CONDACORE/fahndo-app
app/main/services/ParseFileService.js
JavaScript
mit
836
package com.sparta.is.entity.driveables.types; import java.util.ArrayList; import java.util.HashMap; public class TypeFile { public EnumType type; public String name, contentPack; public ArrayList<String> lines; public static HashMap<EnumType, ArrayList<TypeFile>> files; private int readerPosition = 0; static { files = new HashMap<EnumType, ArrayList<TypeFile>>(); for(EnumType type: EnumType.values()) { files.put(type, new ArrayList<TypeFile>()); } } public TypeFile(String contentPack, EnumType t, String s) { this(contentPack, t, s, true); } public TypeFile(String contentPack, EnumType t, String s, boolean addToTypeFileList) { type = t; name = s; this.contentPack = contentPack; lines = new ArrayList<String>(); if(addToTypeFileList) { files.get(type).add(this); } } public String readLine() { if(readerPosition == lines.size()) { return null; } return lines.get(readerPosition++); } }
Alex-BusNet/InfiniteStratos
src/main/java/com/sparta/is/entity/driveables/types/TypeFile.java
Java
mit
1,134
package com.google.common.collect; import java.util.Collection; import java.util.Map; import java.util.SortedSet; import java.util.SortedMap; import java.util.Comparator; class TestCollect { String taint() { return "tainted"; } void sink(Object o) {} <T> T element(Collection<T> c) { return c.iterator().next(); } <K,V> K mapKey(Map<K,V> m) { return element(m.keySet()); } <K,V> V mapValue(Map<K,V> m) { return element(m.values()); } <K,V> K multimapKey(Multimap<K,V> m) { return element(m.keySet()); } <K,V> V multimapValue(Multimap<K,V> m) { return element(m.values()); } <R,C,V> R tableRow(Table<R,C,V> t) { return element(t.rowKeySet()); } <R,C,V> C tableColumn(Table<R,C,V> t) { return element(t.columnKeySet()); } <R,C,V> V tableValue(Table<R,C,V> t) { return element(t.values()); } void test1() { String x = taint(); ImmutableSet<String> xs = ImmutableSet.of(x, "y", "z"); sink(element(xs.asList())); // $numValueFlow=1 ImmutableSet<String> ys = ImmutableSet.of("a", "b", "c"); sink(element(Sets.filter(Sets.union(xs, ys), y -> true))); // $numValueFlow=1 sink(element(Sets.newHashSet("a", "b", "c", "d", x))); // $numValueFlow=1 } void test2() { sink(element(ImmutableList.of(taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint()))); // $numValueFlow=16 sink(element(ImmutableSet.of(taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint()))); // $numValueFlow=16 sink(mapKey(ImmutableMap.of(taint(), taint(), taint(), taint()))); // $numValueFlow=2 sink(mapValue(ImmutableMap.of(taint(), taint(), taint(), taint()))); // $numValueFlow=2 sink(multimapKey(ImmutableMultimap.of(taint(), taint(), taint(), taint()))); // $numValueFlow=2 sink(multimapValue(ImmutableMultimap.of(taint(), taint(), taint(), taint()))); // $numValueFlow=2 sink(tableRow(ImmutableTable.of(taint(), taint(), taint()))); // $numValueFlow=1 sink(tableColumn(ImmutableTable.of(taint(), taint(), taint()))); // $numValueFlow=1 sink(tableValue(ImmutableTable.of(taint(), taint(), taint()))); // $numValueFlow=1 } void test3() { String x = taint(); ImmutableList.Builder<String> b = ImmutableList.builder(); b.add("a"); sink(b); b.add(x); sink(element(b.build())); // $numValueFlow=1 b = ImmutableList.builder(); b.add("a").add(x); sink(element(b.build())); // $numValueFlow=1 sink(ImmutableList.builder().add("a").add(x).build().toArray()[0]); // $numValueFlow=1 ImmutableMap.Builder<String, String> b2 = ImmutableMap.builder(); b2.put(x,"v"); sink(mapKey(b2.build())); // $numValueFlow=1 b2.put("k",x); sink(mapValue(b2.build())); // $numValueFlow=1 } void test4(Table<String, String, String> t1, Table<String, String, String> t2, Table<String, String, String> t3) { String x = taint(); t1.put(x, "c", "v"); sink(tableRow(t1)); // $numValueFlow=1 t1.put("r", x, "v"); sink(tableColumn(t1)); // $numValueFlow=1 t1.put("r", "c", x); sink(tableValue(t1)); // $numValueFlow=1 sink(mapKey(t1.row("r"))); // $numValueFlow=1 sink(mapValue(t1.row("r"))); // $numValueFlow=1 t2.putAll(t1); for (Table.Cell<String,String,String> c : t2.cellSet()) { sink(c.getValue()); // $numValueFlow=1 } sink(t1.remove("r", "c")); // $numValueFlow=1 t3.row("r").put("c", x); sink(tableValue(t3)); // $ MISSING:numValueFlow=1 // depends on aliasing } void test5(Multimap<String, String> m1, Multimap<String, String> m2, Multimap<String, String> m3, Multimap<String, String> m4, Multimap<String, String> m5){ String x = taint(); m1.put("k", x); sink(multimapValue(m1)); // $numValueFlow=1 sink(element(m1.get("k"))); // $numValueFlow=1 m2.putAll("k", ImmutableList.of("a", x, "b")); sink(multimapValue(m2)); // $numValueFlow=1 m3.putAll(m1); sink(multimapValue(m3)); // $numValueFlow=1 m4.replaceValues("k", m1.replaceValues("k", ImmutableList.of("a"))); for (Map.Entry<String, String> e : m4.entries()) { sink(e.getValue()); // $numValueFlow=1 } m5.asMap().get("k").add(x); sink(multimapValue(m5)); // $ MISSING:numValueFlow=1 // depends on aliasing } void test6(Comparator<String> comp, SortedSet<String> sorS, SortedMap<String, String> sorM) { ImmutableSortedSet<String> s = ImmutableSortedSet.of(taint()); sink(element(s)); // $numValueFlow=1 sink(element(ImmutableSortedSet.copyOf(s))); // $numValueFlow=1 sink(element(ImmutableSortedSet.copyOf(comp, s))); // $numValueFlow=1 sorS.add(taint()); sink(element(ImmutableSortedSet.copyOfSorted(sorS))); // $numValueFlow=1 sink(element(ImmutableList.sortedCopyOf(s))); // $numValueFlow=1 sink(element(ImmutableList.sortedCopyOf(comp, s))); // $numValueFlow=1 ImmutableSortedMap<String, String> m = ImmutableSortedMap.of("k", taint()); sink(mapValue(m)); // $numValueFlow=1 sink(mapValue(ImmutableSortedMap.copyOf(m))); // $numValueFlow=1 sink(mapValue(ImmutableSortedMap.copyOf(m, comp))); // $numValueFlow=1 sorM.put("k", taint()); sink(mapValue(ImmutableSortedMap.copyOfSorted(sorM))); // $numValueFlow=1 } }
github/codeql
java/ql/test/library-tests/frameworks/guava/handwritten/TestCollect.java
Java
mit
5,835
using NAudio.Wave; using NAudio.WindowsMediaFormat; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WavToWma.WindowsMediaFormat { internal static class FromProfileGuid { internal static WmaWriter BuildWmaWriter(FileStream wmaFileStream, WaveFormat waveFormat) { // Get system profile GUID, then load profile Guid WMProfile_V80_288MonoAudio = new Guid("{7EA3126D-E1BA-4716-89AF-F65CEE0C0C67}"); Guid wmaSystemProfileGuid = WMProfile_V80_288MonoAudio; IWMProfile wmaProfile = null; WM.ProfileManager.LoadProfileByID(ref wmaSystemProfileGuid, out wmaProfile); try { WmaWriter wmaWriter = new WmaWriter(wmaFileStream, waveFormat, wmaProfile); return wmaWriter; } catch (Exception ex) { throw; } } } }
BrainCrumbz/NAudio-WavToWma
src/WavToWma/WavToWma/WindowsMediaFormat/FromProfileGuid.cs
C#
mit
1,018
import { Component, Input, ContentChild, ViewChildren, QueryList } from 'angular2/core'; import template from './card-list.html!text'; import { CardHeader } from './header/card-header'; import { CardBody } from './body/card-body'; import { Card } from './card/card'; export { CardHeader, CardBody }; @Component({ selector: 'conf-card-list', template: template, directives: [Card], }) export class CardList { @Input() source: any[]; @ContentChild(CardHeader) head: CardHeader; @ContentChild(CardBody) body: CardBody; @ViewChildren(Card) cards: QueryList<Card>; collapseAll() { this.cards.map((card: Card) => card.close()); } }
SonofNun15/conf-template-components
components/card-list/card-list.ts
TypeScript
mit
651
// Type definitions for react-particles-js v3.0.0 // Project: https://github.com/wufe/react-particles-js // Definitions by: Simone Bembi <https://github.com/wufe> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="react" /> import { ComponentClass } from "react"; import { Container } from "tsparticles/Core/Container"; import { ISourceOptions } from "tsparticles"; export type IParticlesParams = ISourceOptions; export * from 'tsparticles/Enums'; export * from "tsparticles/Plugins/Absorbers/Enums"; export * from "tsparticles/Plugins/Emitters/Enums"; export * from "tsparticles/Plugins/PolygonMask/Enums"; export interface ParticlesProps { width?: string; height?: string; params?: IParticlesParams; style?: any; className?: string; canvasClassName?: string; particlesRef?: React.RefObject<Container>; } type Particles = ComponentClass<ParticlesProps>; declare const Particles: Particles; export default Particles;
Wufe/react-particles-js
index.d.ts
TypeScript
mit
989
<?php class Email extends CI_Controller { public function __construct() { parent:: __construct(); $this->load->database(); $this->load->model('Emailinfo'); $this->load->library(array('session','form_validation')); $this->load->helper(array('form','url','date')); } public function index() { $data['emailInformation']=$this->Emailinfo->getEmailList($_SESSION['id']); $data['title']="Email List"; $this->load->view('templates/header', $data); $this->load->view('email_index', $data); $this->load->view('templates/footer', $data); } public function view ($id,$user) { $this->Emailinfo->update_status($id,$_SESSION['id']); $data['emailDetail']=$this->Emailinfo->getEmailDetail($id,$user); $data['title']="Email Detail"; $this->load->view('templates/header', $data); $this->load->view('email_information', $data); $this->load->view('templates/footer', $data); } public function create() { $this->load->library('form_validation'); $this->load->helper('form'); $data['title'] = 'Create a news email'; $this->form_validation->set_rules('sendTo','Email Receiver','callback_receiver_check'); $this->form_validation->set_rules('title','Email Title','required'); $this->form_validation->set_rules('content','Email Content','required'); if ($this->form_validation->run()==FALSE) { $this->load->view('templates/header', $data); $this->load->view('create_email', $_SESSION['id']); $this->load->view('templates/footer', $data); } else { $name = $this->input->post('sendTo'); $query = $this->db->get_where('IndividualUser', array('username' => $name)); $result = $query->row(); $id = $result->id; $this->Emailinfo->createEmail($_SESSION['id'],$id); redirect('Email/'); } } public function unread() { $data['emailInformation'] = $this->Emailinfo->unreadEmail($_SESSION['id']); $data['title']="Unread Email List"; $this->load->view('templates/header', $data); $this->load->view('email_index', $data); $this->load->view('templates/footer', $data); } public function receiver_check($name) { $receiver = $this->Emailinfo->receiver($name); if($receiver > 0) { return TRUE; } else{ return FALSE; } } public function sendNotification() { $data['title'] = "Send Notification"; $this->load->view('templates/header', $data); $this->load->view('send_notification'); $this->load->view('templates/footer'); } public function notificationSubmit() { $title = $_POST['title']; $content = $_POST['content']; $this->Emailinfo->addNotification($title, $content); redirect('/email'); } }
lyuyue/DBproject
application/controllers/Email.php
PHP
mit
2,612
<?php require_once 'responseClasses.php'; header('Content-Type: text/html; charset=utf-8'); if ($_GET['latitude'] != null && $_GET['longitude']) { $lat = $_GET['latitude']; $long = $_GET['longitude']; } else { $lat = 0; $long = 0; } $openWeatherMapApiKey = 'd8bc1c0a60e836388802191cb80c95e8'; $url = 'http://api.openweathermap.org/data/2.5/weather?units=metric&lat='.$lat.'&lon='.$long.'&APPID='.$openWeatherMapApiKey; $json = file_get_contents( $url ); $data = json_decode($json); // var_dump($data); $weather = new Weather(); $weather->temperature = $data->main->temp; $weather->description = $data->weather[0]->description; echo json_encode($weather);
alexkrause/geotracer
app/weather.php
PHP
mit
666
var Counter = require('./counterEvented.js'); var c = new Counter(1); c.increment(); c.on('even', function(){ console.log('even! ' + c.count); return; });
nimhawk/node_playground
app-evented.js
JavaScript
mit
159