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
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NegativeFirstDimensionOfArray { class Program { static void Main(string[] args) { int neg = -7; int pos = 15; int sum = 7; long n = Math.Abs(neg) + Math.Abs(sum) + 1; long[,] array = new long[2, n]; for (int i = 0; i < n; i++) { array[0, i] = neg + i; } for (int row = 0; row < 2; row++) { for (int j = 0; j < n; j++) { Console.Write(array[row, j] + " "); } Console.WriteLine(); } } } }
vladislav-karamfilov/TelerikAcademy
C# Projects/TempSolution-Exam/NegativeFirstDimensionOfArray/Program.cs
C#
mit
787
const BaseXform = require('../base-xform'); /** https://en.wikipedia.org/wiki/Office_Open_XML_file_formats#DrawingML */ const EMU_PER_PIXEL_AT_96_DPI = 9525; class ExtXform extends BaseXform { constructor(options) { super(); this.tag = options.tag; this.map = {}; } render(xmlStream, model) { xmlStream.openNode(this.tag); const width = Math.floor(model.width * EMU_PER_PIXEL_AT_96_DPI); const height = Math.floor(model.height * EMU_PER_PIXEL_AT_96_DPI); xmlStream.addAttribute('cx', width); xmlStream.addAttribute('cy', height); xmlStream.closeNode(); } parseOpen(node) { if (node.name === this.tag) { this.model = { width: parseInt(node.attributes.cx || '0', 10) / EMU_PER_PIXEL_AT_96_DPI, height: parseInt(node.attributes.cy || '0', 10) / EMU_PER_PIXEL_AT_96_DPI, }; return true; } return false; } parseText(/* text */) {} parseClose(/* name */) { return false; } } module.exports = ExtXform;
guyonroche/exceljs
lib/xlsx/xform/drawing/ext-xform.js
JavaScript
mit
1,011
const test = require('ava') const { convert, convertWithMap } = require('../helper/spec') test('(convert) it works for an anonymous module', assert => { assert.truthy(convert('amdjs-api/anonymous-module')) }) test('(convert) it works for a dependency free module', assert => { assert.truthy(convert('amdjs-api/dependency-free-module')) }) test('(convert) it works for named module', assert => { assert.truthy(convert('amdjs-api/named-module')) }) test('(convert) it works for named module with arrow function', assert => { assert.truthy(convert('amdjs-api/named-module-arrow-fn')) }) test('(convert) it works for simple define statements', assert => { assert.truthy(convert('rjs-examples/simple-define')) }) test('(convert) it works for named dependencies', assert => { assert.truthy(convert('rjs-examples/function-wrapping')) }) test('(convert) it converts empty array in define correctly', assert => { assert.truthy(convert('define/callback-empty-array')) }) test('(convert) it converts empty array in define with array function correctly', assert => { assert.truthy(convert('define/arrow-function-callback-empty-array')) }) test('(convert) it converts define with callback only correctly using the built in parser', assert => { assert.truthy(convert('define/callback-only')) }) test('(convert) it converts empty define with arrow function correctly', assert => { assert.truthy(convert('define/arrow-function-callback-only')) }) test('(convert) it converts define with deps correctly', assert => { assert.truthy(convert('define/arrow-function-callback-with-deps')) }) test('(convert) it converts define with arrow function with immediate return', assert => { assert.truthy(convert('define/arrow-function-immediate-return')) }) test('(convert) it converts define with arrow function with immediate function return', assert => { assert.truthy(convert('define/arrow-function-immediate-return-function')) }) test('(convert) it converts define with deps with arrow function correctly', assert => { assert.truthy(convert('define/callback-with-deps')) }) test('(convert) it converts modules wrapped with iife correctly', assert => { assert.truthy(convert('define/iife')) }) test('(convert) it converts quotes correctly', assert => { assert.truthy(convert('define/quotes')) }) test.skip('(convert) it converts single quotes correctly', assert => { assert.truthy(convert('quotes/single', { quotes: 'single' })) }) test.skip('(convert) it converts double quotes correctly', assert => { assert.truthy(convert('quotes/double', { quotes: 'double' })) }) test('(convert) it converts auto quotes correctly', assert => { assert.truthy(convert('quotes/auto', { quotes: 'auto' })) }) test('(convert) it converts define with an object in callback only correctly', assert => { assert.truthy(convert('define/object-only')) }) test("(convert) it shouldn't convert files with no define", assert => { assert.truthy(convert('define/no-define')) }) test('(convert) it converts define with unused deps correctly', assert => { assert.truthy(convert('define/callback-with-mismatch-deps')) }) test('(convert) it keeps dependencies with side effects (behavior 1)', assert => { assert.truthy(convert('app/behavior_1')) }) test('(convert) it keeps dependencies with side effects (behavior 2)', assert => { assert.truthy(convert('app/behavior_2')) }) test('(convert) it converts controllers correctly', assert => { assert.truthy(convert('app/controller_1')) }) test('(convert) it keeps dependencies with side effects (controller 2)', assert => { assert.truthy(convert('app/controller_2')) }) test('(convert) it works with const', assert => { assert.truthy(convert('app/controller_3')) }) test('(convert) it works with let', assert => { assert.truthy(convert('app/controller_4')) }) test('(convert) it keeps custom object assignments', assert => { assert.truthy(convert('app/enum_1')) }) test('(convert) it leaves empty var statements (helper 1)', assert => { assert.truthy(convert('app/helper_1')) }) test('(convert) it leaves empty var statements (helper 2)', assert => { assert.truthy(convert('app/helper_2')) }) test('(convert) it works for named dependencies (helper 3)', assert => { assert.truthy(convert('app/helper_3')) }) test('(convert) it leaves empty var statements (model 1)', assert => { assert.truthy(convert('app/model_1')) }) test('(convert) it handles returns of objects', assert => { assert.truthy(convert('app/model_2')) }) test('(convert) it converts views correctly', assert => { assert.truthy(convert('app/view_1')) }) test('(convert) it converts modules with functions after the return correctly', assert => { assert.truthy(convert('app/view_2')) }) test('(convert) it converts modules with constructors assigned to variables correctly', assert => { assert.truthy(convert('app/view_3')) }) test('(convert) it handles a var declaration which is moved to a separate line', assert => { assert.truthy(convert('app/view_4')) }) test('(convert) it drops an empty define', assert => { assert.truthy(convert('app/view_spec_1')) }) test('(convert) it converts subapps correctly', assert => { assert.truthy(convert('app/subapp_1')) }) test('(convert) it converts subapp specs correctly', assert => { assert.truthy(convert('app/subapp_spec_1', { quotes: 'double' })) }) test('(convert) it converts modules with one require sugar call expression correctly', assert => { assert.truthy(convert('app/module_1')) }) test('(convert) it converts modules with multiple require sugar call expressions correctly', assert => { assert.truthy(convert('app/module_2')) }) test('(convert) it converts module specs correctly', assert => { assert.truthy(convert('app/module_spec_1')) }) test('(convert) it converts troopjs components correctly (troopjs 1)', assert => { assert.truthy(convert('web-examples/troopjs_component_1')) }) test('(convert) it converts troopjs components correctly (troopjs 2)', assert => { assert.truthy(convert('web-examples/troopjs_component_2')) }) test('(convert) it converts require sugar correctly', assert => { assert.truthy(convert('define/require-sugar')) }) test('(convert) it converts require sugar proxy correctly', assert => { assert.truthy(convert('define/require-sugar-proxy')) }) test('(convert) it converts require sugar proxy with member expression correctly', assert => { assert.truthy(convert('define/require-sugar-proxy-inline')) }) test('(convert) it converts require sugar proxy with nested member expressions correctly', assert => { assert.truthy(convert('define/require-sugar-proxy-inline-nested')) }) test('(convert) it converts require sugar with side effects correctly', assert => { assert.truthy(convert('define/require-sugar-with-side-effect')) }) test('(convert) it converts require with property assignment correctly', assert => { assert.truthy(convert('define/require-sugar-with-property-assignment')) }) test('(convert) it converts todomvc backbone requirejs example correctly (backbone 1)', assert => { assert.truthy(convert('web-examples/todomvc_backbone_requirejs_1')) }) test('(convert) it converts todomvc backbone requirejs example correctly (backbone 2)', assert => { assert.truthy(convert('web-examples/todomvc_backbone_requirejs_2')) }) test('(convert) it converts todomvc backbone requirejs example correctly (backbone 3)', assert => { assert.truthy(convert('web-examples/todomvc_backbone_requirejs_3')) }) test('(convert) it converts todomvc angular requirejs example correctly (angular 1)', assert => { assert.truthy(convert('web-examples/todomvc_angularjs_requirejs_1')) }) test('(convert) it converts todomvc angular requirejs example correctly (angular 2)', assert => { assert.truthy(convert('web-examples/todomvc_angularjs_requirejs_2')) }) test('(convert) it converts todomvc angular requirejs example correctly (angular 3)', assert => { assert.truthy(convert('web-examples/todomvc_angularjs_requirejs_3')) }) test('(convert) it converts todomvc knockout requirejs example correctly', assert => { assert.truthy(convert('web-examples/todomvc_knockout_requirejs_1')) }) test('(convert) it converts todomvc lavaca requirejs example correctly', assert => { assert.truthy(convert('web-examples/todomvc_lavaca_requirejs_1')) }) test('(convert) it converts todomvc somajs requirejs example correctly (soma 1)', assert => { assert.truthy(convert('web-examples/todomvc_somajs_requirejs_1')) }) test('(convert) it converts todomvc somajs requirejs example correctly (soma 2)', assert => { assert.truthy(convert('web-examples/todomvc_somajs_requirejs_2')) }) test('(convert) it returns sourcemaps', assert => { assert.truthy(convertWithMap('source-maps/unnamed', { sourceMap: true })) }) test('(convert) it handles destructuring', assert => { assert.truthy(convert('define/destructuring')) }) test('(convert) it handles destructuring for multiple keys', assert => { assert.truthy(convert('define/destructuring-multiple-keys')) }) test('(convert) it handles destructuring for named keys', assert => { assert.truthy(convert('define/destructuring-named-keys')) }) test('(convert) it handles destructuring for require sugar', assert => { assert.truthy(convert('define/require-sugar-destructuring')) }) test('(convert) it handles destructuring for require sugar with many variables', assert => { assert.truthy(convert('define/require-sugar-destructuring-many-variables')) }) test('(convert) it works for simplified commonjs wrapping', assert => { assert.truthy(convert('amdjs-api/simplified-commonjs-wrapping')) }) test('(convert) it works for simplified commonjs wrapping that returns a literal', assert => { assert.truthy(convert('amdjs-api/simplified-commonjs-wrapping-returns-literal')) }) test('(convert) it works for named simplified commonjs wrapping', assert => { assert.truthy(convert('amdjs-api/named-simplified-commonjs-wrapping')) }) test('(convert) it works for named simplified commonjs wrapping with sugar', assert => { assert.truthy(convert('amdjs-api/named-simplified-commonjs-wrapping-with-sugar')) }) test('(convert) it works for named simplified commonjs wrapping with sugar (2)', assert => { assert.truthy(convert('amdjs-api/named-simplified-commonjs-wrapping-with-sugar-second')) }) test('(convert) it handles anonymous imports', assert => { assert.truthy(convert('define/imports-anonymous')) }) test('(convert) it converts exports.default correctly', assert => { assert.truthy(convert('define/exports-default')) }) test('(convert) it removes code that defines the __esModule property', assert => { assert.truthy(convert('define/exports-object-define-property')) }) test('(convert) it does not remove code that defines other properties', assert => { assert.truthy(convert('define/exports-object-define-property-keep')) }) test('(convert) it handles multiple exports assignments to undefined', assert => { assert.truthy(convert('define/exports-overrides')) }) test('(convert) it handles exports with same names', assert => { assert.truthy(convert('define/exports-same')) }) test('(convert) it handles multiple exports assignments', assert => { assert.truthy(convert('define/exports-multiple')) }) test('(convert) it handles exports with condition', assert => { assert.truthy(convert('define/exports-with-condition')) }) test('(convert) it handles exports with condition and multiple overrides', assert => { assert.truthy(convert('define/exports-with-condition-and-overrides')) }) test('(convert) it works for multiple returns', assert => { assert.truthy(convert('define/multiple-returns')) }) test('(convert) it is a noop for files with dynamic imports', assert => { assert.truthy(convert('noop/dynamic-import')) }) test('(convert) it does not break on files with dynamic import', assert => { assert.truthy(convert('define/dynamic-import')) }) test('(convert) it does not break on files with async await', assert => { assert.truthy(convert('define/async-await')) }) test('(convert) it does not create multiple default exports', assert => { assert.truthy(convert('define/if-statement-and-exports-default')) }) test.skip('(convert) it handles optional chaining', assert => { assert.truthy(convert('define/optional-chaining')) }) test.skip('it leaves single line comments if required', assert => { assert.truthy(convert('define/single-line-comments', { comments: true })) }) test.skip('it leaves multi line comments if required', assert => { assert.truthy(convert('define/multi-line-comments', { comments: true })) }) test.skip('it leaves single line comments in code if required', assert => { assert.truthy(convert('define/comments', { comments: true })) }) test.skip('it handles jsx', assert => { assert.truthy(convert('jsx/react', { jsx: true })) })
buxlabs/buxlabs.amd-to-es6
test/spec/convert.js
JavaScript
mit
12,870
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Balanced { public class Order : Resource { [JsonIgnore] public static string resource_href { get { return "/orders"; } } // fields [ResourceField] public string description { get; set; } [ResourceField] public Dictionary<string, string> delivery_address { get; set; } // attributes [ResourceField(serialize = false)] public int amount { get; set; } [ResourceField(serialize = false)] public int amount_escrowed { get; set; } [ResourceField(serialize = false)] public string currency { get; set; } [ResourceField(field = "orders.buyers", link = true, serialize = false)] public Customer.Collection customers { get; set; } [ResourceField(field = "orders.credits", link = true, serialize = false)] public Credit.Collection credits { get; set; } [ResourceField(field = "orders.debits", link = true, serialize = false)] public Debit.Collection debits { get; set; } [ResourceField(field = "orders.merchant", link = true, serialize = false)] public Customer merchant { get; set; } [ResourceField(field = "orders.refunds", link = true, serialize = false)] public Refund.Collection refunds { get; set; } [ResourceField(field = "orders.reversals", link = true, serialize = false)] public Refund.Collection reversals { get; set; } public Order() { } public Order(Dictionary<string, object> payload) { } public static Order Fetch(string href) { return Resource.Fetch<Order>(href); } public void Save() { this.Save<Order>(); } public void Reload() { this.Reload<Order>(); } public Debit DebitFrom(FundingInstrument fi, Dictionary<string, object> options) { options.Add("order", this.href); return fi.Debit(options); } public Credit CreditTo(BankAccount ba, Dictionary<string, object> options) { options.Add("order", this.href); return ba.Credit(options); } public class Collection : ResourceCollection<Order> { public Collection() : base(resource_href) { } public Collection(string href) : base(href) { } } public static ResourceQuery<Order> Query() { return new ResourceQuery<Order>(resource_href); } } }
balanced/balanced-csharp
Balanced/Order.cs
C#
mit
2,724
package Is_test import "testing" import "is.go/src" func TestLowercase(t *testing.T) { message := Is.Lowercase("NOT Lower") if message { t.Error("It's lowercase text") } message = Is.Lowercase("yes lower") if !message { t.Error("Yes it's not lowercase text") } } func TestUppercase(t *testing.T){ message := Is.Uppercase("not upper") if message { t.Error("Yeah! upper case dude.") } message = Is.Uppercase("YES UPPER") if !message { t.Error("Oha amk.") } } func TestCapitalized(t *testing.T){ message := Is.Capitalized("This Is Capitalized Text") if !message { t.Error("It's not capitalized text") } message = Is.Capitalized("this is not capitalized text") if message { t.Error("Oh Noo! Capitalized found.") } } func TestPalindrome(t *testing.T){ message := Is.Palindrome("makam") if !message{ t.Error("It's not palindrome") } message = Is.Palindrome("MakaM") if !message{ t.Error("It's not realy palindrome") } } func TestInclude(t *testing.T){ message := Is.Include("Follow the white rabbit","white") if !message{ t.Error("white not included") } message = Is.Include("Choose your destiny","white") if message { t.Error("white is included") } }
c1982/is.go
src/is_strings_test.go
GO
mit
1,224
<form role="search" method="get" class="woocommerce-product-search" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <label class="screen-reader-text sr-only" for="s"><?php _e( 'Search for:', 'woocommerce' ); ?></label> <div class="input-group"> <input type="search" class="search-field form-control" placeholder="<?php echo esc_attr_x( 'Search Products&hellip;', 'placeholder', 'woocommerce' ); ?>" value="<?php echo get_search_query(); ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label', 'woocommerce' ); ?>" /> <span class="input-group-btn"> <input type="submit" class="btn btn-default" value="<?php echo esc_attr_x( 'Search', 'submit button', 'woocommerce' ); ?>" /> </span> </div> <input type="hidden" name="post_type" value="product" /> </form>
harrygr/samarkand-2
woocommerce/product-searchform.php
PHP
mit
779
import angular from "angular"; import DefinitionCreatorComponent from "./definitionCreator.component"; let DefinitionCreatorModule = angular.module("DefinitionCreatorModule", []) .directive("sgDefinitionCreatorModal", DefinitionCreatorComponent); export default DefinitionCreatorModule;
booknds/sge
src/app/components/modals/definitionCreator/definitionCreator.js
JavaScript
mit
321
package main import ( "encoding/json" "fmt" "io/ioutil" "path/filepath" "strings" ) type Language struct { Image string `json:"image"` Command string `json:"command"` Format string `json:"format"` } var Extensions map[string]Language func ValidLanguage(ext string) bool { for k, _ := range Extensions { if k == ext { return true } } return false } func GetLanguageConfig(filename string) (*Language, error) { ext := filepath.Ext(strings.ToLower(filename)) if !ValidLanguage(ext) { return nil, fmt.Errorf("Extension is not supported: %s", ext) } lang := Extensions[ext] return &lang, nil } func LoadLanguages(file string) error { data, err := ioutil.ReadFile(file) if err != nil { return err } err = json.Unmarshal(data, &Extensions) return err }
lanastasov/bitrun-api
lang.go
GO
mit
791
module StyleguideHelper ## # Render a styleguide block def styleguide_block section, styleguide = @styleguide, &block section = styleguide.section section render :partial => 'styleguide/block', :locals => { :section => section, :example_html => capture(&block) } end end
cbeer/rails-styleguide
app/helpers/styleguide_helper.rb
Ruby
mit
288
<?php namespace AD7six\Dsn\Db; use AD7six\Dsn\DbDsn; /** * MongodbDsn * */ class MongodbDsn extends DbDsn { /** * defaultPort * * @var int 27017 */ protected $defaultPort = 27017; }
AD7six/php-dsn
src/Db/MongodbDsn.php
PHP
mit
197
from random import random from functools import partial import csv import json from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.uix.boxlayout import BoxLayout from kivy.uix.spinner import Spinner from kivy.graphics import Color, Line, Ellipse import tensorflow as tf import numpy as np maxLen = 60 class Gesture: def __init__(self): self.classId = 0 self.points = [] def from_points(self, input): for i in range(2, len(input), 2): self.points.append((input[i] - input[i-2], input[i+1]-input[i-1])) def to_dict(self): dict = { "classId" : self.classId, "points" : self.points } return dict def from_dict(dict): g = Gesture() g.classId = dict["classId"] g.points = dict["points"] return g def to_tensor(self): return self.points[:maxLen] + [self.points[-1]]*(maxLen - len(self.points)) class GestureBase: def __init__(self): self.gestures = [] self.gestureIds = {'None': 0} def save(self, path): print("Gestures %d" % len(self.gestures)) with open(path, 'w') as file: data = { "classes": self.gestureIds, "gestures": [g.to_dict() for g in self.gestures], } json.dump(data, file, indent=2) def load(self, path): with open(path, 'r') as file: data = json.load(file) self.gestureIds = data["classes"] self.gestures = [Gesture.from_dict(g) for g in data["gestures"]] def get_classes_in_order(self): items = sorted(self.gestureIds.items(), key=lambda p: p[1]) return [i[0] for i in items] def add_gesture(self, className, points): gesture = Gesture() if className not in self.gestureIds: self.gestureIds[className] = gesture.classId = len(self.gestureIds) else: gesture.classId = self.gestureIds[className] gesture.from_points(points) self.gestures.append(gesture) def to_tensor(self): return np.array([g.to_tensor() for g in self.gestures]) def classes_to_tensor(self): ret = [] for g in self.gestures: list = [0] * 10 list[g.classId] = 1 ret.append(list) return np.array(ret) def lengths_to_tensor(self): ret = [len(g.points) for g in self.gestures] return np.array(ret) #return [100 for g in self.gestures] class GestureRecognizer: numberOfExamples = None #dynamic sampleVectorLen = 2 # x, y coords numMemCells = 24 def __init__(self): self.inputData = tf.placeholder(tf.float32, [None, maxLen, self.sampleVectorLen]) self.expectedClasses = tf.placeholder(tf.float32, [None, 10]) self.inputLengths = tf.placeholder(tf.int32, [None]) cell = tf.contrib.rnn.LSTMCell(self.numMemCells, state_is_tuple=True) cellOut, cellState = tf.nn.dynamic_rnn( cell, self.inputData, dtype=tf.float32, sequence_length=self.inputLengths) batchSize = tf.shape(cellOut)[0] index = tf.range(0, batchSize) * maxLen + (self.inputLengths - 1) flat = tf.reshape(cellOut, [-1, self.numMemCells]) last = tf.gather(flat, index) print(last.get_shape()) weight = tf.Variable(tf.truncated_normal([self.numMemCells, int(self.expectedClasses.get_shape()[1])], stddev = 0.1)) bias = tf.Variable(tf.constant(0.1, shape=[self.expectedClasses.get_shape()[1]])) #prediction = tf.nn.softmax(tf.matmul(last, weight) + bias) prediction = tf.matmul(last, weight) + bias cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=self.expectedClasses)) #cross_entropy = -tf.reduce_sum(self.expectedClasses * tf.log(tf.clip_by_value(prediction,1e-10,1.0))) optimizer = tf.train.GradientDescentOptimizer(0.1) self.trainer = optimizer.minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(self.expectedClasses,1)) self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) self.predictionMax = tf.argmax(prediction, 1) self.classifier = tf.nn.softmax(prediction) self.sess = tf.Session() init_op = tf.global_variables_initializer() self.sess.run(init_op) def train(self, base): examples = base.to_tensor() labels = base.classes_to_tensor() lengths = base.lengths_to_tensor() feed = {self.inputData: examples, self.expectedClasses: labels, self.inputLengths: lengths} for i in range(1000): self.sess.run(self.trainer, feed) if i % 10 == 0: print("Epoch %d" % i) print(self.sess.run(self.accuracy, feed)) print("Trained") def classify(self, points): gesture = Gesture() gesture.from_points(points) feed = {self.inputData: [gesture.to_tensor()], self.inputLengths: [len(gesture.points)]} index, prob = self.sess.run([self.predictionMax, self.classifier], feed) index = index[0] print("Class Id %d" % index) prob = prob[0][index] print("Probability {:.1%}".format(prob)) class ToolBar(BoxLayout): def __init__(self, **kwargs): self.controller = kwargs.pop("controller") super(ToolBar, self).__init__(**kwargs) self.add_widget(Label(text='Class:')) self.classesSpinner = Spinner(values=['None'], text='None') self.classesSpinner.bind(text=self.select_class) self.add_widget(self.classesSpinner) self.add_widget(Label(text='Add new')) self.classInput = TextInput(multiline=False) self.classInput.bind(on_text_validate=self.add_class) self.add_widget(self.classInput) self.saveButton = Button(text='Save Gestures') self.saveButton.bind(on_release=self.save_gestures) self.add_widget(self.saveButton) self.loadButton = Button(text='Load Gestures') self.loadButton.bind(on_release=self.load_gestures) self.add_widget(self.loadButton) self.learnButton = Button(text='Learn') self.learnButton.bind(on_release=self.learn_gestures) self.add_widget(self.learnButton) self.toggleModeButton = Button(text='Adding') self.toggleModeButton.bind(on_release=self.toggle_mode) self.add_widget(self.toggleModeButton) def save_gestures(self, button): self.controller.save() def load_gestures(self, button): self.controller.load() def learn_gestures(self, button): self.controller.learn() def classify_gestures(self, button): self.controller.classify() def toggle_mode(self, button): button.text = self.controller.toggle_mode() def add_class(self, text): self.classesSpinner.values.append(text.text) text.text = '' def select_class(self, spinner, text): self.controller.className = text class MyPaintWidget(Widget): previousLine = None controller = None def __init__(self, **kwargs): super(MyPaintWidget, self).__init__(**kwargs) def on_touch_down(self, touch): self.p = (touch.x, touch.y) if self.collide_point(*self.p): self.canvas.clear() color = (random(), 1, 1) with self.canvas: Color(*color, mode='hsv') touch.ud['line'] = Line(points=[touch.x, touch.y]) Ellipse(pos=[touch.x - 2, touch.y - 2], size=[4, 4]) def on_touch_move(self, touch): if 'line' in touch.ud: p = [touch.x, touch.y] if ((np.linalg.norm(np.subtract(p, self.p))) > 20): with self.canvas: Ellipse(pos=[touch.x - 2, touch.y - 2], size=[4, 4]) line = touch.ud['line'] line.points += p self.p = p def on_touch_up(self, touch): if 'line' in touch.ud: line = touch.ud['line'] self.previousLine = line self.controller.handle_gesture(line.points) print(len(line.points)) class GestureApp(App): def build(self): layout = BoxLayout(orientation='vertical') self.toolBar = ToolBar(size_hint=(1, None), height=40, controller=self) layout.add_widget(self.toolBar) mainArea = MyPaintWidget(size_hint=(1, 1)) mainArea.controller = self layout.add_widget(mainArea) return layout def clear_canvas(self, obj): self.painter.canvas.clear() def __init__(self, **kwargs): super(GestureApp, self).__init__(**kwargs) self.handle_gesture = self.add_gesture_from_points self.gestureRecognizer = GestureRecognizer() self.base = GestureBase() self.className = 'None' def add_gesture_from_points(self, points): self.base.add_gesture(self.className, points) def save(self): self.base.save("Gestures.json") def load(self): self.base.load("Gestures.json") asd = self.base.get_classes_in_order() print(asd) self.toolBar.classesSpinner.values = self.base.get_classes_in_order() def learn(self): self.gestureRecognizer.train(self.base) def classify(self, points): self.gestureRecognizer.classify(points) def toggle_mode(self): if(self.handle_gesture == self.add_gesture_from_points): self.handle_gesture = self.classify return "Classifying" else: self.handle_gesture = self.add_gesture_from_points return "Adding" if __name__ == '__main__': GestureApp().run()
romanchom/GestureRecognitionVR
MouseGestures/App.py
Python
mit
8,792
require './spec/spec_helper' describe Hasten::Command do it "strips whitespace from sql" do subject << " SET TIME_ZONE='+00:00'; " expect(subject.sql).to eq "SET TIME_ZONE='+00:00'" end it "extracts conditional sql" do subject << "/*!40103 SET TIME_ZONE='+00:00' */;" expect(subject.sql).to eq "SET TIME_ZONE='+00:00'" end it "considers comments complete" do subject << "-- Server version 5.6.22" expect(subject.complete?).to be_true end it "considers semicolon terminated lines complete" do subject << "DROP TABLE IF EXISTS `test`;" expect(subject.complete?).to be_true end it "considers lines without semicolons incomplete" do subject << "DROP TABLE IF EXISTS `test`" expect(subject.complete?).to be_false end it "parses multiline sql" do subject << <<-EOC SELECT * FROM `test` WHERE c1 = 'name'; EOC expect(subject.complete?).to be_true end it "identifies Table definitions" do subject << <<-EOC CREATE TABLE `test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `q1` int(11) DEFAULT NULL, `q2` int(11) DEFAULT NULL, PRIMARY KEY (`id`), ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; EOC expect(subject.type).to eq('Table') end it "identifies View definitions" do subject << <<-EOC CREATE VIEW `test` AS SELECT * FROM `section1` UNION SELECT * FROM `section2`; EOC expect(subject.type).to eq('View') end it "identifies Insert statements" do subject << <<-EOC INSERT INTO `contact_fields` VALUES (1,'Name',0), (2,'Address',0), (3,'Phone',0); EOC expect(subject.type).to eq('Insert') end it "accepts other commands" do command1 = Hasten::Command.new command1 << "line 1" command1 << "line 2" command2 = Hasten::Command.new command2 << command1 expect(command2.sql).to eq command1.sql end end
thirtysixthspan/hasten
spec/command_spec.rb
Ruby
mit
1,988
/// <reference path="../Interfaces/IDisposable.ts" /> /// <reference path="../Interfaces/ITyped.ts" /> /// <reference path="LooperCallback.ts" />
NTaylorMullen/EndGate
EndGate/EndGate.Core.JS/Loopers/ILooper.js
JavaScript
mit
146
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2017-02-22 15:14 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='deployment', name='platform_id', ), migrations.RemoveField( model_name='deployment', name='platform_ip', ), migrations.AlterField( model_name='deployment', name='sensor_id', field=models.TextField(unique=True), ), ]
cloudcomputinghust/IoT
co-ordinator/api/migrations/0002_auto_20170222_1514.py
Python
mit
664
var class_predicate2_test = [ [ "SetUp", "class_predicate2_test.html#a9778563daf4846327d32061c1a8ccba0", null ], [ "TearDown", "class_predicate2_test.html#a7379f8f7772af6b4c76edcc90b6aaaeb", null ] ];
bhargavipatel/808X_VO
docs/html/class_predicate2_test.js
JavaScript
mit
208
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h(h.f, null, h("path", { d: "M5 19h14V5H5v14zm5-11l5 4-5 4V8z", opacity: ".3" }), h("path", { d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14zM10 8v8l5-4z" })), 'SlideshowTwoTone');
AlloyTeam/Nuclear
components/icon/esm/slideshow-two-tone.js
JavaScript
mit
340
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE typedef unsigned __int16 PROPVAR_PAD1; END_ATF_NAMESPACE
goodwinxp/Yorozuya
library/ATF/PROPVAR_PAD1.hpp
C++
mit
233
<?php namespace Skalda\TestLinkAPI; class TestLinkAPIException extends \Exception { }
Skalda/TestLinkAPI
src/TestLinkAPIException.php
PHP
mit
88
module MigrateSafely class MigrationOutliner Action = Struct.new(:version, :action, :name) def self.pending_actions(target_version = nil) current_version = ActiveRecord::Migrator.current_version return [] if current_version == 0 && target_version == 0 direction = case when target_version.nil? :up when current_version > target_version :down else :up end migrations = ActiveRecord::Migrator.migrations(ActiveRecord::Migrator.migrations_paths) runnable_migrations = ActiveRecord::Migrator.new(direction, migrations, target_version).runnable action = direction == :up ? "apply" : "revert" runnable_migrations.map do |m| Action.new(m.version, action, m.name) end end end end
remind101/migrate_safely
lib/migrate_safely/migration_outliner.rb
Ruby
mit
796
<?php /* * This file is part of the CRUDlex package. * * (c) Philip Lehmann-Böhm <philip@philiplb.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace CRUDlexTests; use CRUDlexTestEnv\TestDBSetup; use CRUDlex\EntityValidator; use PHPUnit\Framework\TestCase; class EntityValidatorTest extends TestCase { protected $dataBook; protected $dataLibrary; protected function setUp() { $crudService = TestDBSetup::createService(); $this->dataBook = $crudService->getData('book'); $this->dataLibrary = $crudService->getData('library'); } public function testValidate() { $entityLibrary1 = $this->dataLibrary->createEmpty(); $entityLibrary1->set('name', 'lib a'); $this->dataLibrary->create($entityLibrary1); $entityBook = $this->dataBook->createEmpty(); $entityBook->set('title', 'title'); $entityBook->set('author', 'author'); $entityBook->set('pages', 111); $entityBook->set('library', ['id' => $entityLibrary1->get('id')]); $entityBook->set('secondLibrary', ['id' => $entityLibrary1->get('id')]); $entityBook->set('cover', 'cover'); $entityBook->set('price', 3.99); $valid = [ 'valid' => true, 'errors' => [] ]; $invalid = $valid; $invalid['valid'] = false; $validatorBook = new EntityValidator($entityBook); $read = $validatorBook->validate($this->dataBook, 0); $expected = $valid; $this->assertSame($read, $expected); $entityBook->set('title', null); $read = $validatorBook->validate($this->dataBook, 0); $expected = $invalid; $expected['errors']['title'] = ['required']; $this->assertSame($read, $expected); $entityBook->set('title', 'title'); // Fixed values should override this. $entityBook->set('title', null); $this->dataBook->getDefinition()->setField('title', 'value', 'abc'); $read = $validatorBook->validate($this->dataBook, 0); $expected = $valid; $this->assertSame($read, $expected); $entityBook->set('title', 'title'); $this->dataBook->getDefinition()->setField('title', 'value', null); $invalidLibrary = $valid; $invalidLibrary['valid'] = false; $entityLibrary2 = $this->dataLibrary->createEmpty(); $entityLibrary2->set('name', 'lib a'); $validatorLibrary2 = new EntityValidator($entityLibrary2); $read = $validatorLibrary2->validate($this->dataLibrary, 0); $expected = $invalidLibrary; $expected['errors']['name'] = ['unique']; $this->assertSame($read, $expected); $entityLibrary1->set('type', 'large'); $validatorLibrary1 = new EntityValidator($entityLibrary1); $read = $validatorLibrary1->validate($this->dataLibrary, 0); $expected = $valid; $this->assertSame($read, $expected); $entityLibrary1->set('type', 'foo'); $read = $validatorLibrary1->validate($this->dataLibrary, 0); $expected = $invalidLibrary; $expected['errors']['type'] = ['inSet']; $this->assertSame($read, $expected); $entityLibrary1->set('type', null); $entityLibrary1->set('opening', '2014-08-31 12:00'); $read = $validatorLibrary1->validate($this->dataLibrary, 0); $expected = $valid; $this->assertSame($read, $expected); $entityLibrary1->set('opening', '2014-08-31 12:00:00'); $read = $validatorLibrary1->validate($this->dataLibrary, 0); $expected = $valid; $this->assertSame($read, $expected); $entityLibrary1->set('opening', 'foo'); $read = $validatorLibrary1->validate($this->dataLibrary, 0); $expected = $invalidLibrary; $expected['errors']['opening'] = [['or' => ['dateTime', 'dateTime']]]; $this->assertSame($read, $expected); $entityLibrary1->set('opening', null); $read = $validatorLibrary1->validate($this->dataLibrary, 0); $expected = $valid; $this->assertSame($read, $expected); $entityLibrary2->set('name', 'lib b'); $this->dataLibrary->create($entityLibrary2); $expected = $valid; $this->assertSame($read, $expected); $entityLibrary2->set('name', 'lib a'); $read = $validatorLibrary2->validate($this->dataLibrary, 0); $expected = $invalidLibrary; $expected['errors']['name'] = ['unique']; $this->assertSame($read, $expected); $entityBook->set('pages', 'abc'); $read = $validatorBook->validate($this->dataBook, 0); $expected = $invalid; $expected['errors']['pages'] = ['integer']; $this->assertSame($read, $expected); $entityBook->set('pages', 111); $entityBook->set('pages', 0); $read = $validatorBook->validate($this->dataBook, 0); $expected = $valid; $this->assertSame($read, $expected); $entityBook->set('pages', 111); $entityBook->set('pages', null); $read = $validatorBook->validate($this->dataBook, 0); $expected = $invalid; $expected['errors']['pages'] = ['required']; $this->assertSame($read, $expected); $entityBook->set('pages', 111); $entityBook->set('price', 'abc'); $read = $validatorBook->validate($this->dataBook, 0); $expected = $invalid; $expected['errors']['price'] = ['floating']; $this->assertSame($read, $expected); $entityBook->set('price', 3.99); $entityBook->set('price', 0); $read = $validatorBook->validate($this->dataBook, 0); $expected = $valid; $this->assertSame($read, $expected); $entityBook->set('price', 3.99); $entityBook->set('price', null); $read = $validatorBook->validate($this->dataBook, 0); $expected = $valid; $this->assertSame($read, $expected); $entityBook->set('price', 3.99); $entityBook->set('release', 'abc'); $read = $validatorBook->validate($this->dataBook, 0); $expected = $invalid; $expected['errors']['release'] = ['dateTime']; $this->assertSame($read, $expected); $entityBook->set('release', '2014-08-31'); $entityBook->set('library', ['id' => 666]); $read = $validatorBook->validate($this->dataBook, 0); $expected = $invalid; $expected['errors']['library'] = ['reference']; $this->assertSame($read, $expected, 0); $entityBook->set('library', $entityLibrary1->get('id')); } }
philiplb/CRUDlex
tests/CRUDlexTests/EntityValidatorTest.php
PHP
mit
6,726
<?php // src/Clc/TodosBundle/Controller/TodosController.php namespace Clc\TodosBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Clc\TodosBundle\Form\Type\TaskType; use Clc\TodosBundle\Entity\task; class TodosController extends Controller { public function indexAction($state) { return $this->render('ClcTodosBundle::layout.html.twig', array( 'coloc_task'=> $this->getByColocAction($state), 'user_task' => $this->getMineAction(0), 'state' => $state, )); } public function newAction() { $user = $this->getUser(); $coloc = $user->getColoc(); // initialisez simplement un objet $task $task = new task(); $task->setState(0); $task->setDate(new \DateTime('now')); $task->setDueDate(new \DateTime('tomorrow')); $task->setAuthor($user); $task->setColoc($coloc); $usersQuery = function(\Clc\UserBundle\Entity\UserRepository $ur) use ($coloc) { return $ur->createQueryBuilder('u') ->where('u.coloc = :coloc and u.enabled = :enabled') ->setParameters(array('coloc' => $coloc, 'enabled' => 1)) ->orderBy('u.nickname', 'ASC'); }; $form = $this->createFormBuilder($task) ->add('task', 'text') ->add('owner', 'entity', array( 'class' => 'ClcUserBundle:User', 'property' => 'nickname', 'query_builder' => $usersQuery, 'required' => false, )) ->getForm(); $request = $this->get('request'); if ($request->isMethod('POST')) { $form->bind($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($task); $em->flush(); $url = $this->getRequest()->headers->get("referer"); return $this->redirect($url); } } return $this->render('ClcTodosBundle:Default:new.html.twig', array( 'form' => $form->createView(), )); } public function editAction($id) { $user = $this->getUser(); $coloc = $user->getColoc(); $em = $this->getDoctrine()->getEntityManager(); $task = $em->getRepository('ClcTodosBundle:task')->find($id); $usersQuery = function(\Clc\UserBundle\Entity\UserRepository $ur) use ($coloc) { return $ur->createQueryBuilder('u') ->where('u.coloc = :coloc and u.enabled = :enabled') ->setParameters(array('coloc' => $coloc, 'enabled' => 1)) ->orderBy('u.nickname', 'ASC'); }; $form = $this->createFormBuilder($task) ->add('task', 'text') ->add('owner', 'entity', array( 'class' => 'ClcUserBundle:User', 'property' => 'nickname', 'query_builder' => $usersQuery, 'required' => false, )) ->getForm(); $request = $this->get('request'); if ($request->isMethod('POST')) { $form->bind($request); if ($form->isValid()) { $em->flush(); $url = $this->get('router')->generate('clc_todos_homepage', array('state' => 0)); return $this->redirect($url); } } return $this->render('ClcTodosBundle:Default:edit.html.twig', array( 'form' => $form->createView(), 'id' => $id, )); } public function getByColocAction($state) { $user = $this->getUser(); $coloc = $user->getColoc(); $td = $this->container->get('clc_todos.todos'); $task_list = $td->getByColoc($coloc, $state); return $task_list; } public function getMineAction($state) { $user = $this->getUser(); $td = $this->container->get('clc_todos.todos'); $task_list = $td->getMine($user, $state); return $task_list; } public function removeAction($id) { $em = $this->getDoctrine() ->getEntityManager(); $task = $em->getRepository('ClcTodosBundle:task') ->find($id); $em->remove($task); $em->flush(); $url = $this->getRequest()->headers->get("referer"); return $this->redirect($url); } public function checkAction($id) { $em = $this->getDoctrine() ->getEntityManager(); $task = $em->getRepository('ClcTodosBundle:task') ->find($id); $task->setState(1); $em->flush(); $url = $this->getRequest()->headers->get("referer"); return $this->redirect($url); } public function uncheckAction($id) { $em = $this->getDoctrine() ->getEntityManager(); $task = $em->getRepository('ClcTodosBundle:task') ->find($id); $task->setState(0); $em->flush(); $url = $this->getRequest()->headers->get("referer"); return $this->redirect($url); } }
JulesMarcil/colocall
src/Clc/TodosBundle/Controller/TodosController.php
PHP
mit
5,807
<?php namespace Heyday\Beam; use Heyday\Beam\Config\ValueInterpolator; use Heyday\Beam\DeploymentProvider\DeploymentProvider; use Heyday\Beam\DeploymentProvider\DeploymentResult; use Heyday\Beam\Exception\Exception; use Heyday\Beam\Exception\InvalidArgumentException; use Heyday\Beam\Exception\RuntimeException; use Heyday\Beam\VcsProvider\Git; use Heyday\Beam\VcsProvider\GitLikeVcsProvider; use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Process\Process; /** * Class Beam * @package Heyday\Component */ class Beam { /** * @var array */ protected $config; /** * @var array */ protected $options; /** * @var bool */ protected $prepared = false; /** * An config in the format defined in BeamConfiguration * @param array $config * @param array $options */ public function __construct( array $config, array $options ) { // Perform initial setup and validation $this->config = $config; $this->setup($options); // Apply variable interpolation config after initial checks $this->config = $this->replaceConfigVariables($config); } /** * Uses the options resolver to set the options to the object from an array * * Any dynamic options are set in this method and then validated manually * This method can be called multiple times, each time it is run it will validate * the array provided and set the appropriate options. * * This might be useful if you prep the options for a command via a staged process * for example an interactive command line tool * @param $options * @throws InvalidArgumentException */ public function setup($options) { $this->options = $this->getOptionsResolver()->resolve($options); if (!$this->isWorkingCopy() && !$this->options['vcsprovider']->exists()) { throw new InvalidArgumentException("You can't use beam without a vcs."); } if (!$this->isWorkingCopy() && !$this->options['ref']) { if ($this->isServerLocked()) { $this->options['ref'] = $this->getServerLockedBranch(); } else { $this->options['ref'] = $this->options['vcsprovider']->getCurrentBranch(); } } $this->validateSetup(); } /** * Validates dynamic options or options that the options resolver can't validate * @throws InvalidArgumentException */ protected function validateSetup() { // Prevent a server with empty options being used $requiredKeys = array( 'host', 'webroot' ); $server = $this->getServer(); $emptyKeys = array(); foreach ($requiredKeys as $key) { if (empty($server[$key])) { $emptyKeys[] = $key; } } if (count($emptyKeys)) { $options = implode(', ', $emptyKeys); throw new InvalidArgumentException("The server '{$this->options['target']}' has empty values for required options: $options"); } if ($this->options['ref']) { // TODO: Allow refs from the same branch (ie master~1) when locked. Git can show what branches a ref is in by using: git branch --contains [ref] if ($this->isServerLocked() && $this->options['ref'] !== $this->getServerLockedBranch()) { throw new InvalidArgumentException( sprintf( 'Specified ref "%s" doesn\'t match the locked branch "%s"', $this->options['ref'], $this->getServerLockedBranch() ) ); } if (!$this->options['vcsprovider']->isValidRef($this->options['ref'])) { $branches = $this->options['vcsprovider']->getAvailableBranches(); throw new InvalidArgumentException( sprintf( 'Ref "%s" is not valid. Available branches are: %s', $this->options['ref'], '\'' . implode('\', \'', $branches) . '\'' ) ); } } if ($this->isWorkingCopy()) { if ($this->isTargetLockedRemote()) { throw new InvalidArgumentException('Working copy can\'t be used with a locked remote branch'); } } else { if (!is_writable($this->getLocalPathFolder())) { throw new InvalidArgumentException( sprintf('The local path "%s" is not writable', $this->getLocalPathFolder()) ); } } $limitations = $this->options['deploymentprovider']->getLimitations(); if (is_array($limitations)) { // Check if remote commands defined when not available if ($this->hasRemoteCommands() && in_array(DeploymentProvider::LIMITATION_REMOTECOMMAND, $limitations)) { throw new InvalidConfigurationException( "Commands are to run on the location 'target' but the deployment provider '{$server['type']}' cannot execute remote commands." ); } } } /** * @param \Heyday\Beam\DeploymentProvider\DeploymentResult $deploymentResult * @param \Closure $deploymentCallback - callback to run immediately after deployment, before commands * @return mixed */ public function doRun(DeploymentResult $deploymentResult = null, $deploymentCallback = null) { if ($this->isUp()) { $this->prepareLocalPath(); $this->runPreTargetCommands(); $deploymentResult = $this->options['deploymentprovider']->up( $this->options['deploymentoutputhandler'], false, $deploymentResult ); if (is_callable($deploymentCallback)) { $deploymentCallback(); } if (!$this->isWorkingCopy()) { $this->runPostLocalCommands(); } $this->runPostTargetCommands(); } else { $deploymentResult = $this->options['deploymentprovider']->down( $this->options['deploymentoutputhandler'], false, $deploymentResult ); } return $deploymentResult; } /** * @return mixed */ public function doDryrun() { if ($this->isUp()) { $this->prepareLocalPath(); $deploymentResult = $this->options['deploymentprovider']->up( $this->options['deploymentoutputhandler'], true ); } else { $deploymentResult = $this->options['deploymentprovider']->down( $this->options['deploymentoutputhandler'], true ); } return $deploymentResult; } /** * Ensures that the correct content is at the local path */ protected function prepareLocalPath() { if (!$this->isPrepared() && !$this->isWorkingCopy() && !$this->isDown()) { $this->runOutputHandler( $this->options['outputhandler'], array( 'Preparing local deploy path' ) ); if ($this->isTargetLockedRemote()) { $this->runOutputHandler( $this->options['outputhandler'], array( 'Updating remote branch' ) ); $this->options['vcsprovider']->updateBranch($this->options['ref']); } $this->runOutputHandler( $this->options['outputhandler'], array( 'Exporting ref' ) ); $this->options['vcsprovider']->exportRef( $this->options['ref'], $this->getLocalPath() ); $this->setPrepared(true); $this->runPreLocalCommands(); $this->writeLog(); } } public function configureDeploymentProvider(OutputInterface $output) { $this->options['deploymentprovider']->configure($output); } /** * Gets the from location for rsync * * Takes the form "path" * @return string */ public function getLocalPath() { if ($this->isWorkingCopy() || $this->isDown()) { $path = $this->options['srcdir']; } else { $path = sprintf( '/tmp/%s', $this->getLocalPathname() ); } return sprintf( '%s', $path ); } /** * @return string */ public function getLocalPathname() { return sprintf( 'beam-%s', md5($this->options['srcdir']) ); } /** * @return mixed */ public function getTargetPath() { return $this->options['deploymentprovider']->getTargetAsText(); } /** * @param boolean $prepared */ public function setPrepared($prepared) { $this->prepared = $prepared; } /** * @param $key * @param $value * @return void */ public function setOption($key, $value) { $this->options = $this->getOptionsResolver()->resolve( array_merge( $this->options, array( $key => $value ) ) ); } /** * @return boolean */ public function isPrepared() { return $this->prepared; } /** * Returns whether or not files are being sent to the target * @return bool */ public function isUp() { return $this->options['direction'] === 'up'; } /** * Returns whether or not files are being sent to the local * @return bool */ public function isDown() { return $this->options['direction'] === 'down'; } /** * Returns whether or not beam is operating from a working copy * @return mixed */ public function isWorkingCopy() { return $this->options['working-copy']; } /** * Returns whether or not the server is locked to a branch * @return bool */ public function isServerLocked() { $server = $this->getServer(); return isset($server['branch']) && $server['branch']; } /** * Returns whether or not the server is locked to a remote branch * @return bool */ public function isTargetLockedRemote() { $server = $this->getServer(); return $this->isServerLocked() && $this->options['vcsprovider']->isRemote($server['branch']); } /** * Returns whether or not the branch is remote * @return bool */ public function isBranchRemote() { return $this->options['vcsprovider']->isRemote($this->options['ref']); } /** * A helper method for determining if beam is operating with a list of paths * @return bool */ public function hasPath() { return is_array($this->options['path']) && count($this->options['path']) > 0; } /** * Get the server config we are deploying to. * * This method is guaranteed to to return a server due to the options resolver and config * @return mixed */ public function getServer() { return $this->config['servers'][$this->options['target']]; } /** * Get the locked branch * @return mixed */ public function getServerLockedBranch() { $server = $this->getServer(); return $this->isServerLocked() ? $server['branch'] : false; } /** * @return string */ protected function getLocalPathFolder() { return dirname($this->options['srcdir']); } /** * A helper method that returns a process with some defaults * @param $commandline * @param null $cwd * @param int $timeout * @return Process */ protected function getProcess($commandline, $cwd = null, $timeout = null) { return new Process( $commandline, $cwd ? $cwd : $this->options['srcdir'], null, null, $timeout ); } /** * @param $option * @return mixed * @throws InvalidArgumentException */ public function getOption($option) { if (array_key_exists($option, $this->options)) { return $this->options[$option]; } else { throw new InvalidArgumentException( sprintf( 'Option \'%s\' doesn\'t exist', $option ) ); } } /** * @param $config * @return mixed * @throws InvalidArgumentException */ public function getConfig($config) { if (array_key_exists($config, $this->config)) { return $this->config[$config]; } else { throw new InvalidArgumentException( sprintf( 'Config \'%s\' doesn\'t exist', $config ) ); } } /** * Check if the deployment provider implements an interface * @param $interfaceName * @return bool */ public function deploymentProviderImplements($interfaceName) { $interfaces = class_implements( get_class($this->getOption('deploymentprovider')) ); return isset($interfaces[$interfaceName]); } /** * Set the deployment provider's result stream handler * This is only available if the deployment provider implements the * DeploymentProvider\ResultStream interface. */ public function setResultStreamHandler(\Closure $handler = null) { $this->getOption('deploymentprovider')->setStreamHandler($handler); } /** * A helper method that runs a process and checks its success, erroring if it failed * @param Process $process * @param callable $output * @throws RuntimeException */ protected function runProcess(Process $process, \Closure $output = null) { $process->run($output); if (!$process->isSuccessful()) { throw new RuntimeException($process->getErrorOutput()); } } /** * Runs commands specified in config in the pre phase on the local */ protected function runPreLocalCommands() { $this->runCommands( $this->getFilteredCommands('pre', 'local'), 'Running local pre-deployment commands', 'runLocalCommand' ); } /** * Runs commands specified in config in the pre phase on the target */ protected function runPreTargetCommands() { $this->runCommands( $this->getFilteredCommands('pre', 'target'), 'Running target pre-deployment commands', 'runTargetCommand' ); } /** * Runs commands specified in config in the post phase on the local */ protected function runPostLocalCommands() { $this->runCommands( $this->getFilteredCommands('post', 'local'), 'Running local post-deployment commands', 'runLocalCommand' ); } /** * Runs commands specified in config in the post phase on the target */ protected function runPostTargetCommands() { $this->runCommands( $this->getFilteredCommands('post', 'target'), 'Running target post-deployment commands', 'runTargetCommand' ); } /** * @param $commands * @param $message * @param $method */ protected function runCommands($commands, $message, $method) { if (count($commands)) { $this->runOutputHandler( $this->options['outputhandler'], array( $message ) ); foreach ($commands as $command) { $this->$method($command); } } } /** * @param $phase * @param $location * @return array */ protected function getFilteredCommands($phase, $location) { $commands = array(); foreach ($this->config['commands'] as $command) { if ($command['phase'] !== $phase) { continue; } if ($command['location'] !== $location) { continue; } if (count($command['servers']) !== 0 && !in_array($this->options['target'], $command['servers'])) { continue; } if (!$command['required']) { if ($command['tag'] && (count($this->options['command-tags']) === 0 || !$this->matchTag($command['tag']))) { continue; } if (is_callable($this->options['commandprompthandler']) && !$this->options['commandprompthandler']($command)) { continue; } } $commands[] = $command; } return $commands; } /** * Checks if a tag matches one passed on the command line. * Wildcard matching is supported supported * @param $tag * @return bool */ protected function matchTag($tag) { foreach ($this->options['command-tags'] as $pattern) { if (fnmatch($pattern, $tag)) { return true; } } return false; } /** * @param $command */ protected function runTargetCommand($command) { $this->runOutputHandler( $this->options['outputhandler'], array( $command['command'], 'command:target' ) ); $server = $this->getServer(); $userComponent = isset($server['user']) && $server['user'] <> '' ? $server['user'] . '@' : ''; $remoteCmd = sprintf( 'cd \'%s\' && %s', $server['webroot'], $command['command'] ); $args = array( // SSHPASS is set in \Heyday\Beam\DeploymentProvider\Rsync getenv('SSHPASS') === false ? 'ssh' : 'sshpass -e ssh', $command['tty'] ? '-t' : '', $userComponent . $server['host'], escapeshellcmd($remoteCmd) ); $command['command'] = implode(' ', $args); $this->doExecCommand($command, $this->options['targetcommandoutputhandler']); } /** * @param $command */ protected function runLocalCommand($command) { $this->runOutputHandler( $this->options['outputhandler'], array( $command['command'], 'command:local' ) ); $this->doExecCommand($command, $this->options['localcommandoutputhandler']); } /** * @param $command * @param $outputHandler * @throws RuntimeException */ protected function doExecCommand($command, $outputHandler) { try { $process = null; if ($command['tty']) { passthru(sprintf('%s; %s', "cd {$this->getLocalPath()}", $command['command'] ), $exit); if ($exit !== 0) { throw new RuntimeException("Command returned a non-zero exit status ($exit)"); } } else { $process = $this->getProcess( $command['command'], $this->getLocalPath() ); $this->runProcess( $process, $outputHandler ); } } catch (RuntimeException $exception) { if (!$this->promptCommandFailureContinue($command, $exception, $process)) { exit(1); } } } /** * @param $command * @param $exception * @param \Symfony\Component\Process\Process $process * @throws RuntimeException * @return mixed */ protected function promptCommandFailureContinue($command, $exception, Process $process = null) { if (!is_callable($this->options['commandfailurehandler'])) { throw $exception; } return $this->options['commandfailurehandler']($command, $exception, $process); } /** * @param $handler * @param $arguments * @return bool|mixed */ protected function runOutputHandler($handler, $arguments) { if (is_callable($handler)) { return call_user_func_array($handler, $arguments); } return false; } /** * Replace variable placeholders in config fields * * @param array $config * @return array * @throws Exception */ protected function replaceConfigVariables(array $config) { $vcs = $this->options['vcsprovider']; if ($vcs instanceof GitLikeVcsProvider) { $interpolator = new ValueInterpolator($vcs, $this->getOption('ref'), array( 'target' => $this->getOption('target') )); return $interpolator->process($config); } else { throw new Exception('Config interpolation is only possible using a Git-like VCS'); } } /** * This returns an options resolver that will ensure required options are set and that all options set are valid * @return OptionsResolver */ protected function getOptionsResolver() { $that = $this; $resolver = new OptionsResolver(); $resolver->setRequired( array( 'direction', 'target', 'srcdir', 'deploymentprovider' ) )->setOptional( array( 'ref', 'path', 'dry-run', 'working-copy', 'command-tags', 'vcsprovider', 'deploymentprovider', 'deploymentoutputhandler', 'localcommandoutputhandler', 'targetcommandoutputhandler', 'outputhandler' ) )->setAllowedValues( array( 'direction' => array( 'up', 'down' ), 'target' => array_keys($this->config['servers']) ) )->setDefaults( array( 'ref' => '', 'path' => array(), 'dry-run' => false, 'working-copy' => false, 'command-tags' => array(), 'vcsprovider' => function (Options $options) { return new Git($options['srcdir']); }, 'deploymentoutputhandler' => null, 'outputhandler' => null, 'localcommandoutputhandler' => null, 'targetcommandoutputhandler' => null, 'commandprompthandler' => null, 'commandfailurehandler' => null ) )->setAllowedTypes( array( 'ref' => 'string', 'srcdir' => 'string', 'dry-run' => 'bool', 'working-copy' => 'bool', 'command-tags' => 'array', 'vcsprovider' => __NAMESPACE__ . '\VcsProvider\VcsProvider', 'deploymentprovider' => __NAMESPACE__ . '\DeploymentProvider\DeploymentProvider', ) )->setNormalizers( array( 'ref' => function (Options $options, $value) { return trim($value); }, 'path' => function (Options $options, $value) { return is_array($value) ? array_map(function($value){ return trim($value, '/'); }, $value) : false; }, 'deploymentprovider' => function (Options $options, $value) use ($that) { if (is_callable($value)) { $value = $value($options); } $value->setBeam($that); return $value; }, 'deploymentoutputhandler' => function (Options $options, $value) { if ($value !== null && !is_callable($value)) { throw new InvalidArgumentException('Deployment output handler must be null or callable'); } return $value; }, 'outputhandler' => function (Options $options, $value) { if ($value !== null && !is_callable($value)) { throw new InvalidArgumentException('Output handler must be null or callable'); } return $value; }, 'localcommandoutputhandler' => function (Options $options, $value) { if ($value !== null && !is_callable($value)) { throw new InvalidArgumentException('Local command output handler must be null or callable'); } return $value; }, 'targetcommandoutputhandler' => function (Options $options, $value) { if ($value !== null && !is_callable($value)) { throw new InvalidArgumentException('Target command output handler must be null or callable'); } return $value; }, 'commandprompthandler' => function (Options $options, $value) { if ($value !== null && !is_callable($value)) { throw new InvalidArgumentException('Command prompt handler must be null or callable'); } return $value; }, 'commandfailurehandler' => function (Options $options, $value) { if ($value !== null && !is_callable($value)) { throw new InvalidArgumentException('Command failure handler must be null or callable'); } return $value; } ) ); return $resolver; } /** * Returns true if any commands to run on the remote ("target") are defined * @return boolean */ protected function hasRemoteCommands() { foreach ($this->config['commands'] as $command) { if ($command['location'] === 'target') { if (empty($command['tag'])) { return true; } else { return $this->matchTag($command['tag']); } } } return false; } /** * */ protected function writeLog() { file_put_contents( $this->getLocalPath() . '/.beamlog', $this->options['vcsprovider']->getLog($this->options['ref']) ); } }
stevie-mayhew/beam
src/Beam.php
PHP
mit
28,568
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.modules.home.config; import ninja.leaping.configurate.objectmapping.Setting; import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; @ConfigSerializable public class HomeConfig { @Setting(value = "use-safe-warp", comment = "config.home.safeTeleport") private boolean safeTeleport = true; @Setting(value = "respawn-at-home", comment = "config.home.respawnAtHome") private boolean respawnAtHome = false; @Setting(value = "prevent-home-count-overhang", comment = "config.home.overhang") private boolean preventHomeCountOverhang = true; @Setting(value = "only-same-dimension", comment = "config.home.onlySameDimension") private boolean onlySameDimension = false; public boolean isSafeTeleport() { return this.safeTeleport; } public boolean isRespawnAtHome() { return this.respawnAtHome; } public boolean isPreventHomeCountOverhang() { return this.preventHomeCountOverhang; } public boolean isOnlySameDimension() { return this.onlySameDimension; } }
OblivionNW/Nucleus
src/main/java/io/github/nucleuspowered/nucleus/modules/home/config/HomeConfig.java
Java
mit
1,269
#undef SEQAN_ENABLE_TESTING #define SEQAN_ENABLE_TESTING 1 #include <seqan/find.h> #include <seqan/sequence.h> #include <seqan/index.h> #include <seqan/seq_io.h> #include "demultiplex.h" using namespace seqan; SEQAN_DEFINE_TEST(findExactIndex_test) { StringSet<String<Dna> > barcodes; appendValue(barcodes, "AAAAAA"); appendValue(barcodes, "CCCCCC"); appendValue(barcodes, "GGGGGG"); appendValue(barcodes, "TTTTTT"); appendValue(barcodes, "ACGTAC"); StringSet<String<Dna5> > readPieces; appendValue(readPieces, "CCCCCC"); appendValue(readPieces, "AAAAAA"); appendValue(readPieces, "TTTTTT"); appendValue(readPieces, "GGGGGG"); appendValue(readPieces, "CCCNCC"); appendValue(readPieces, "GATACA"); appendValue(readPieces, "ACGTAC"); appendValue(readPieces, "ATGACNAANG"); //darf eigentlich eh nicht passieren Index<StringSet<String<Dna> >, IndexEsa<> > indexSet(barcodes); Finder<Index<StringSet<String<Dna> >, IndexEsa<> > > esaFinder(indexSet); int exspected[] = {1,0,3,2,-1,-1,4,-1}; for (unsigned i = 0; i < length(readPieces); ++i) { int res = findExactIndex(readPieces[i], esaFinder); SEQAN_ASSERT_EQ(exspected[i], res); } } SEQAN_DEFINE_TEST(findAllExactIndex_test) { StringSet<String<Dna> > barcodes; appendValue(barcodes, "AAAAAA"); appendValue(barcodes, "CCCCCC"); appendValue(barcodes, "GGGGGG"); appendValue(barcodes, "TTTTTT"); appendValue(barcodes, "ACGTAC"); StringSet<String<Dna5> > readPieces; appendValue(readPieces, "CCCCCC"); appendValue(readPieces, "AAAAAA"); appendValue(readPieces, "TTTTTT"); appendValue(readPieces, "GGGGGG"); appendValue(readPieces, "CCCNCC"); appendValue(readPieces, "GATACA"); appendValue(readPieces, "ACGTAC"); Index<StringSet<String<Dna> >, IndexEsa<> > indexSet(barcodes); Finder<Index<StringSet<String<Dna> >, IndexEsa<> > > esaFinder(indexSet); std::pair<unsigned, int> exspected[] = {std::make_pair(0,1),std::make_pair(1,0),std::make_pair(2,3),std::make_pair(3,2),std::make_pair(4,-1),std::make_pair(5,-1),std::make_pair(6,4)}; std::vector<std::pair<unsigned, int> > res = findAllExactIndex(readPieces, esaFinder); SEQAN_ASSERT_EQ(exspected, res); } SEQAN_BEGIN_TESTSUITE(test_my_app_funcs) { SEQAN_CALL_TEST(findExactIndex_test); SEQAN_CALL_TEST(findAllExactIndex_test); } SEQAN_END_TESTSUITE
bkahlert/seqan-research
raw/pmsb13/pmsb13-data-20130530/sources/24xc47o54r0zzgyu/2013-05-01T15-31-10.712+0200/sandbox/my_sandbox/apps/SeqDPT/demultiplex_test.cpp
C++
mit
2,305
package net.ilexiconn.magister.handler; import com.google.gson.Gson; import net.ilexiconn.magister.Magister; import net.ilexiconn.magister.container.Response; import net.ilexiconn.magister.exeption.PrivilegeException; import net.ilexiconn.magister.util.GsonUtil; import net.ilexiconn.magister.util.HttpUtil; import net.ilexiconn.magister.util.LogUtil; import java.io.IOException; import java.security.InvalidParameterException; import java.util.HashMap; import java.util.Map; /** * @since 0.1.2 */ public class PasswordHandler implements IHandler { private Gson gson = GsonUtil.getGson(); private Magister magister; public PasswordHandler(Magister magister) { this.magister = magister; } @Override public String getPrivilege() { return "WachtwoordWijzigen"; } /** * Change the password of the current profile. * * @param oldPassword the current password. * @param newPassword the new password. * @param newPassword2 the new password. * @return a String with the response. 'Successful' if the password changed successfully. * @throws IOException if there is no active internet connection. * @throws InvalidParameterException if one of the parameters is null or empty, or when the two new passwords aren't * the same. * @throws PrivilegeException if the profile doesn't have the privilege to perform this action. */ public String changePassword(String oldPassword, String newPassword, String newPassword2) throws IOException, InvalidParameterException, PrivilegeException { if (oldPassword == null || oldPassword.isEmpty() || newPassword == null || newPassword.isEmpty() || newPassword2 == null || newPassword2.isEmpty()) { throw new InvalidParameterException("Parameters can't be null or empty!"); } else if (!newPassword.equals(newPassword2)) { throw new InvalidParameterException("New passwords don't match!"); } Map<String, String> nameValuePairMap = new HashMap<String, String>(); nameValuePairMap.put("HuidigWachtwoord", oldPassword); nameValuePairMap.put("NieuwWachtwoord", newPassword); nameValuePairMap.put("PersoonId", magister.profile.id + ""); nameValuePairMap.put("WachtwoordBevestigen", newPassword2); Response response = gson.fromJson(HttpUtil.httpPost(magister.school.url + "/api/personen/account/wachtwoordwijzigen?persoonId=" + magister.profile.id, nameValuePairMap), Response.class); if (response == null) { magister.user.password = newPassword; return "Successful"; } else { LogUtil.printError(response.message, new InvalidParameterException()); return response.message; } } }
iLexiconn/Magister.java
src/main/java/net/ilexiconn/magister/handler/PasswordHandler.java
Java
mit
2,839
const debug = require('debug')('stuco:web:middleware:error') let errorCodes = { 'User Not Found': 0, 'Requesting User Not Found': 1, 'Event Not Found': 2, 'Invalid Location Data': 3, 'Google Token Validation Failed': 4, 'TokenIssuer is Invalid': 5, 'Invalid Token Certificate': 6, 'UserToken Has Expired': 7, 'Not At Event Location': 8, 'Already Checked Into Event': 9, 'Not During Event Time': 10, 'User File Empty': 11, 'Failed to Create User': 12, 'Invalid UserToken': 13, 'Permission Requirements Not Met': 14, 'Invalid Permission Type': 15, 'Badge Not Found': 16, 'DeprecationWarning': 17, 'Invalid Request Parameters': 18, 'Missing or Invalid Authentication Header': 19, 'Failed to Edit User': 20, 'Google Certificates Retrieval Error': 21, 'Certificate Parsing Error': 22, 'Invalid Email Domain': 23, 'Malformed UserToken': 24, 'Invalid API Key': 25, 'Unexpected Error': 26 } let error = (req, res, next) => { debug('initializing response error method') res.error = (error) => { debug('response error method called') if (error == null) { debug('assuming unxpected since error was null') error = 'Unexpected Error' } if (!(error instanceof Error)) { error = new Error(error.toString().replace(/(?:\r\n|\r|\n)/g, '').trim()) } return res.json({ error: error.message, errorid: errorCodes[error.message] == null ? -1 : errorCodes[error.message] }) } debug('initialized response error method') return next() } module.exports.inject = error module.exports.errorCodes = errorCodes
RSCodingClub/STUCO-Backend
web/middleware/error.js
JavaScript
mit
1,622
require 'spec_helper' require 'flico/flickr_command' describe Flico::FlickrCommand do let(:search_results) {[{"id"=>"33472607802", "owner"=>"78759190@N05", "secret"=>"42e011bcf5", "server"=>"2805", "farm"=>3, "title"=>"Volkswagen Golf in Luxembourg", "ispublic"=>1, "isfriend"=>0, "isfamily"=>0}]} let(:sizes_results) { [ {"label"=>"Square", "width"=>75, "height"=>75, "source"=>"https://farm3.staticflickr.com/2805/33472607802_42e011bcf5_s.jpg", "url"=>"https://farm3.staticflickr.com/2805/33472607802_42e011bcf5/sizes/sq/", "media"=>"photo"}, {"label"=>"Large Square", "width"=>"150", "height"=>"150", "source"=>"https://farm3.staticflickr.com/2805/33472607802_42e011bcf5_q.jpg", "url"=>"https://farm3.staticflickr.com/2805/33472607802_42e011bcf5/sizes/q/", "media"=>"photo"}, {"label"=>"Thumbnail", "width"=>"100", "height"=>"66", "source"=>"https://farm3.staticflickr.com/2805/33472607802_42e011bcf5_t.jpg", "url"=>"https://farm3.staticflickr.com/2805/33472607802_42e011bcf5/sizes/t/", "media"=>"photo"} ] } let(:subject) { described_class.new(search_command: search_command, sizes_command: sizes_command) } let(:search_command) { double('search', call: search_results ) } let(:sizes_command) { double('sizes', call: sizes_results)} context 'search success' do it 'should return image url for search keyword' do expect(subject.call 'Volkswagen Golf in Luxembourg').to eq('https://farm3.staticflickr.com/2805/33472607802_42e011bcf5_q.jpg') end end end
amandeepbhamra/flico
spec/flickr_command_spec.rb
Ruby
mit
1,520
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #nullable disable namespace StyleCop.Analyzers.Status.Generator { using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.MSBuild; /// <summary> /// A class that is used to parse the StyleCop.Analyzers solution to get an overview /// about the implemented diagnostics. /// </summary> public class SolutionReader { private static readonly Regex DiagnosticPathRegex = new Regex(@"(?<type>[A-Za-z]+)Rules\\(?<name>[A-Za-z0-9]+)\.cs$"); private INamedTypeSymbol diagnosticAnalyzerTypeSymbol; private INamedTypeSymbol noCodeFixAttributeTypeSymbol; private Solution solution; private Project analyzerProject; private Project codeFixProject; private MSBuildWorkspace workspace; private Assembly analyzerAssembly; private Assembly codeFixAssembly; private Compilation analyzerCompilation; private Compilation codeFixCompilation; private ITypeSymbol booleanType; private Type batchFixerType; private SolutionReader() { AppDomain.CurrentDomain.AssemblyResolve += (s, e) => { if (e.Name.Contains(this.AnalyzerProjectName)) { return this.analyzerAssembly; } return null; }; } private string SlnPath { get; set; } private string AnalyzerProjectName { get; set; } private string CodeFixProjectName { get; set; } private ImmutableArray<CodeFixProvider> CodeFixProviders { get; set; } /// <summary> /// Creates a new instance of the <see cref="SolutionReader"/> class. /// </summary> /// <param name="pathToSln">The path to the StyleCop.Analayzers solution.</param> /// <param name="analyzerProjectName">The project name of the analyzer project.</param> /// <param name="codeFixProjectName">The project name of the code fix project.</param> /// <returns>A <see cref="Task{TResult}"/> representing the asynchronous operation.</returns> public static async Task<SolutionReader> CreateAsync(string pathToSln, string analyzerProjectName = "StyleCop.Analyzers", string codeFixProjectName = "StyleCop.Analyzers.CodeFixes") { SolutionReader reader = new SolutionReader(); reader.SlnPath = pathToSln; reader.AnalyzerProjectName = analyzerProjectName; reader.CodeFixProjectName = codeFixProjectName; reader.workspace = MSBuildWorkspace.Create(); await reader.InitializeAsync().ConfigureAwait(false); return reader; } /// <summary> /// Analyzes the project and returns information about the diagnostics in it. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task<ImmutableList<StyleCopDiagnostic>> GetDiagnosticsAsync() { var diagnostics = ImmutableList.CreateBuilder<StyleCopDiagnostic>(); var syntaxTrees = this.analyzerCompilation.SyntaxTrees; foreach (var syntaxTree in syntaxTrees) { var match = DiagnosticPathRegex.Match(syntaxTree.FilePath); if (!match.Success) { continue; } string shortName = match.Groups["name"].Value; string noCodeFixReason = null; // Check if this syntax tree represents a diagnostic SyntaxNode syntaxRoot = await syntaxTree.GetRootAsync().ConfigureAwait(false); SemanticModel semanticModel = this.analyzerCompilation.GetSemanticModel(syntaxTree); SyntaxNode classSyntaxNode = syntaxRoot.DescendantNodes().FirstOrDefault(x => x.IsKind(SyntaxKind.ClassDeclaration)); if (classSyntaxNode == null) { continue; } INamedTypeSymbol classSymbol = semanticModel.GetDeclaredSymbol(classSyntaxNode) as INamedTypeSymbol; if (!this.InheritsFrom(classSymbol, this.diagnosticAnalyzerTypeSymbol)) { continue; } if (classSymbol.IsAbstract) { continue; } bool hasImplementation = HasImplementation(syntaxRoot); IEnumerable<DiagnosticDescriptor> descriptorInfos = this.GetDescriptor(classSymbol); foreach (var descriptorInfo in descriptorInfos) { var (codeFixStatus, fixAllStatus) = this.GetCodeFixAndFixAllStatus(descriptorInfo.Id, classSymbol, out noCodeFixReason); string status = this.GetStatus(classSymbol, syntaxRoot, semanticModel, descriptorInfo); if (descriptorInfo.CustomTags.Contains(WellKnownDiagnosticTags.NotConfigurable)) { continue; } var diagnostic = new StyleCopDiagnostic { Id = descriptorInfo.Id, Category = descriptorInfo.Category, HasImplementation = hasImplementation, Status = status, Name = shortName, Title = descriptorInfo.Title.ToString(), HelpLink = descriptorInfo.HelpLinkUri, CodeFixStatus = codeFixStatus, FixAllStatus = fixAllStatus, NoCodeFixReason = noCodeFixReason, }; diagnostics.Add(diagnostic); } } return diagnostics.ToImmutable(); } private static bool HasImplementation(SyntaxNode syntaxRoot) { bool hasImplementation = true; foreach (var trivia in syntaxRoot.DescendantTrivia()) { if (trivia.IsKind(SyntaxKind.SingleLineCommentTrivia)) { if (trivia.ToFullString().Contains("TODO: Implement analysis")) { hasImplementation = false; } } } return hasImplementation; } private async Task InitializeAsync() { this.solution = await this.workspace.OpenSolutionAsync(this.SlnPath).ConfigureAwait(false); this.analyzerProject = this.solution.Projects.First(x => x.Name == this.AnalyzerProjectName || x.AssemblyName == this.AnalyzerProjectName); this.analyzerCompilation = await this.analyzerProject.GetCompilationAsync().ConfigureAwait(false); this.analyzerCompilation = this.analyzerCompilation.WithOptions(this.analyzerCompilation.Options.WithOutputKind(OutputKind.DynamicallyLinkedLibrary)); this.codeFixProject = this.solution.Projects.First(x => x.Name == this.CodeFixProjectName || x.AssemblyName == this.CodeFixProjectName); this.codeFixCompilation = await this.codeFixProject.GetCompilationAsync().ConfigureAwait(false); this.codeFixCompilation = this.codeFixCompilation.WithOptions(this.codeFixCompilation.Options.WithOutputKind(OutputKind.DynamicallyLinkedLibrary)); this.booleanType = this.analyzerCompilation.GetSpecialType(SpecialType.System_Boolean); this.LoadAssemblies(); this.noCodeFixAttributeTypeSymbol = this.analyzerCompilation.GetTypeByMetadataName("StyleCop.Analyzers.NoCodeFixAttribute"); this.diagnosticAnalyzerTypeSymbol = this.analyzerCompilation.GetTypeByMetadataName(typeof(DiagnosticAnalyzer).FullName); this.batchFixerType = this.codeFixAssembly.GetType("StyleCop.Analyzers.Helpers.CustomBatchFixAllProvider"); this.InitializeCodeFixTypes(); } private void InitializeCodeFixTypes() { var codeFixTypes = this.codeFixAssembly.GetTypes().Where(x => x.FullName.EndsWith("CodeFixProvider")); this.CodeFixProviders = ImmutableArray.Create( codeFixTypes .Select(t => Activator.CreateInstance(t, true)) .OfType<CodeFixProvider>() .Where(x => x != null) .Where(x => x.GetType().Name != "SettingsFileCodeFixProvider") .ToArray()); } private void LoadAssemblies() { this.analyzerAssembly = this.GetAssembly(this.analyzerProject); this.codeFixAssembly = this.GetAssembly(this.codeFixProject); } private Assembly GetAssembly(Project project) { return Assembly.LoadFile(project.OutputFilePath); } private string GetStatus(INamedTypeSymbol classSymbol, SyntaxNode root, SemanticModel model, DiagnosticDescriptor descriptor) { // Some analyzers use multiple descriptors. We analyze the first one and hope that // thats enough. var members = classSymbol.GetMembers().Where(x => x.Name.Contains("Descriptor")).ToArray(); foreach (var member in members) { ObjectCreationExpressionSyntax initializer; SyntaxNode node = root.FindNode(member.Locations.FirstOrDefault().SourceSpan); if (node != null) { initializer = (node as PropertyDeclarationSyntax)?.Initializer?.Value as ObjectCreationExpressionSyntax; if (initializer == null) { initializer = (node as VariableDeclaratorSyntax)?.Initializer?.Value as ObjectCreationExpressionSyntax; if (initializer == null) { continue; } } } else { continue; } var firstArgument = initializer.ArgumentList.Arguments[0]; string constantValue = (string)model.GetConstantValue(firstArgument.Expression).Value; if (constantValue != descriptor.Id) { continue; } // We use the fact that the only parameter that returns a boolean is the one we are interested in var enabledByDefaultParameter = from argument in initializer.ArgumentList.Arguments where SymbolEqualityComparer.Default.Equals(model.GetTypeInfo(argument.Expression).Type, this.booleanType) select argument.Expression; var parameter = enabledByDefaultParameter.FirstOrDefault(); string parameterString = parameter.ToString(); var analyzerConstantLength = "AnalyzerConstants.".Length; if (parameterString.Length < analyzerConstantLength) { return parameterString; } return parameter.ToString().Substring(analyzerConstantLength); } return "Unknown"; } private IEnumerable<DiagnosticDescriptor> GetDescriptor(INamedTypeSymbol classSymbol) { var analyzer = (DiagnosticAnalyzer)Activator.CreateInstance(this.analyzerAssembly.GetType(classSymbol.ToString())); // This currently only supports one diagnostic for each analyzer. return analyzer.SupportedDiagnostics; } private (CodeFixStatus codeFixStatus, FixAllStatus fixAllStatus) GetCodeFixAndFixAllStatus(string diagnosticId, INamedTypeSymbol classSymbol, out string noCodeFixReason) { CodeFixStatus codeFixStatus; FixAllStatus fixAllStatus; noCodeFixReason = null; var noCodeFixAttribute = classSymbol .GetAttributes() .SingleOrDefault(x => SymbolEqualityComparer.Default.Equals(x.AttributeClass, this.noCodeFixAttributeTypeSymbol)); bool hasCodeFix = noCodeFixAttribute == null; if (!hasCodeFix) { codeFixStatus = CodeFixStatus.NotImplemented; fixAllStatus = FixAllStatus.None; if (noCodeFixAttribute.ConstructorArguments.Length > 0) { noCodeFixReason = noCodeFixAttribute.ConstructorArguments[0].Value as string; } } else { // Check if the code fix actually exists var codeFixes = this.CodeFixProviders .Where(x => x.FixableDiagnosticIds.Contains(diagnosticId)) .Select(x => this.IsBatchFixer(x)) .ToArray(); hasCodeFix = codeFixes.Length > 0; codeFixStatus = hasCodeFix ? CodeFixStatus.Implemented : CodeFixStatus.NotYetImplemented; if (codeFixes.Any(x => x ?? false)) { fixAllStatus = FixAllStatus.BatchFixer; } else if (codeFixes.Any(x => x != null)) { fixAllStatus = FixAllStatus.CustomImplementation; } else { fixAllStatus = FixAllStatus.None; } } return (codeFixStatus, fixAllStatus); } private bool? IsBatchFixer(CodeFixProvider provider) { var fixAllProvider = provider.GetFixAllProvider(); if (fixAllProvider == null) { return null; } else { return fixAllProvider.GetType() == this.batchFixerType; } } private bool InheritsFrom(INamedTypeSymbol declaration, INamedTypeSymbol possibleBaseType) { while (declaration != null) { if (SymbolEqualityComparer.Default.Equals(declaration, possibleBaseType)) { return true; } declaration = declaration.BaseType; } return false; } } }
DotNetAnalyzers/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers.Status.Generator/SolutionReader.cs
C#
mit
15,020
import org.basesource.reservoir.Streamer; import org.basesource.reservoir.impl.BaseStreamer; import org.basesource.reservoir.impl.HttpStreamer; import org.basesource.reservoir.impl.RandomSampler; import org.basesource.reservoir.impl.RandomStreamer; public class Main { public static void main(String[] args) { assert (args.length > 0) : "Please pass the first argument as sample size."; assert (args[0].trim().matches("^[1-9]+\\d*$")) : "Sample size should be numeric and greater than zero."; // default running state int samplesize = Integer.valueOf(args[0]); Streamer streamer = new RandomStreamer(samplesize); // input options if(args.length > 1 && !args[1].equalsIgnoreCase("-random")) { if(args[1].equalsIgnoreCase("-http") && args.length > 2) { streamer = new HttpStreamer(args[2]); } else { streamer = new BaseStreamer(args[1]); } } System.out.println("Result: " + new RandomSampler().sample(streamer, samplesize)); } }
leventgunay/experimental
reservoir-sampling/src/Main.java
Java
mit
1,083
package pow.backend.action; import pow.backend.GameBackend; import pow.backend.actors.Actor; import pow.backend.event.GameEvent; import java.util.Collections; public class Log implements Action { public Log() { } @Override public ActionResult process(GameBackend backend) { return ActionResult.succeeded(Collections.singletonList(GameEvent.LOG_UPDATE)); } @Override public Actor getActor() { return null; } @Override public boolean consumesEnergy() { return false; } }
jonathanacross/pow
src/main/java/pow/backend/action/Log.java
Java
mit
516
// RECEIVING USERNAME & PASSWORD DATA //var data = require('../public/js/data.json'); //var projects = require('../projects.json'); var global_datajson = require('../globaldata.json'); var models = require('../models'); // MAIN FUNCTION - RENDERS/SHOWS HTML exports.delMeal = function(req, res){ var type; var projectID = req.query.id; models.Project .find({"id": projectID}) .exec(before); function before (err, proj){ if (proj[0].color=='redish') { console.log('am here'); global_datajson[0].cheat_had = global_datajson[0].cheat_had-1; global_datajson[0].cheat_left = global_datajson[0].cheat_left+1 } } models.Project .find({"id": projectID}) .remove() .exec(afterRemove); function afterRemove (err, projects){ if(err) console.log(err); //res.send('ok'); } models.Project .find() .sort({"id":-1}) .exec( function before_renderProjects(err, projDB){ models.Project2 .find() .exec( function render2(err, cheats){ res.render('index', {"meal" : projDB, "total_cheat" : global_datajson[0].total_cheat, "cheat_left" : global_datajson[0].cheat_left, "cheat_had" : global_datajson[0].cheat_had}); }); }); }
srishtyagrawal/joy4-add1
routes/del.js
JavaScript
mit
1,176
import { ScrollGeomCache } from '../ScrollGeomCache' import { ElementScrollGeomCache } from '../ElementScrollGeomCache' import { WindowScrollGeomCache } from '../WindowScrollGeomCache' interface Edge { scrollCache: ScrollGeomCache name: 'top' | 'left' | 'right' | 'bottom' distance: number // how many pixels the current pointer is from the edge } // If available we are using native "performance" API instead of "Date" // Read more about it on MDN: // https://developer.mozilla.org/en-US/docs/Web/API/Performance const getTime = typeof performance === 'function' ? (performance as any).now : Date.now /* For a pointer interaction, automatically scrolls certain scroll containers when the pointer approaches the edge. The caller must call start + handleMove + stop. */ export class AutoScroller { // options that can be set by caller isEnabled: boolean = true scrollQuery: (Window | string)[] = [window, '.fc-scroller'] edgeThreshold: number = 50 // pixels maxVelocity: number = 300 // pixels per second // internal state pointerScreenX: number | null = null pointerScreenY: number | null = null isAnimating: boolean = false scrollCaches: ScrollGeomCache[] | null = null msSinceRequest?: number // protect against the initial pointerdown being too close to an edge and starting the scroll everMovedUp: boolean = false everMovedDown: boolean = false everMovedLeft: boolean = false everMovedRight: boolean = false start(pageX: number, pageY: number) { if (this.isEnabled) { this.scrollCaches = this.buildCaches() this.pointerScreenX = null this.pointerScreenY = null this.everMovedUp = false this.everMovedDown = false this.everMovedLeft = false this.everMovedRight = false this.handleMove(pageX, pageY) } } handleMove(pageX: number, pageY: number) { if (this.isEnabled) { let pointerScreenX = pageX - window.pageXOffset let pointerScreenY = pageY - window.pageYOffset let yDelta = this.pointerScreenY === null ? 0 : pointerScreenY - this.pointerScreenY let xDelta = this.pointerScreenX === null ? 0 : pointerScreenX - this.pointerScreenX if (yDelta < 0) { this.everMovedUp = true } else if (yDelta > 0) { this.everMovedDown = true } if (xDelta < 0) { this.everMovedLeft = true } else if (xDelta > 0) { this.everMovedRight = true } this.pointerScreenX = pointerScreenX this.pointerScreenY = pointerScreenY if (!this.isAnimating) { this.isAnimating = true this.requestAnimation(getTime()) } } } stop() { if (this.isEnabled) { this.isAnimating = false // will stop animation for (let scrollCache of this.scrollCaches!) { scrollCache.destroy() } this.scrollCaches = null } } requestAnimation(now: number) { this.msSinceRequest = now requestAnimationFrame(this.animate) } private animate = () => { if (this.isAnimating) { // wasn't cancelled between animation calls let edge = this.computeBestEdge( this.pointerScreenX! + window.pageXOffset, this.pointerScreenY! + window.pageYOffset, ) if (edge) { let now = getTime() this.handleSide(edge, (now - this.msSinceRequest!) / 1000) this.requestAnimation(now) } else { this.isAnimating = false // will stop animation } } } private handleSide(edge: Edge, seconds: number) { let { scrollCache } = edge let { edgeThreshold } = this let invDistance = edgeThreshold - edge.distance let velocity = // the closer to the edge, the faster we scroll ((invDistance * invDistance) / (edgeThreshold * edgeThreshold)) * // quadratic this.maxVelocity * seconds let sign = 1 switch (edge.name) { case 'left': sign = -1 // falls through case 'right': scrollCache.setScrollLeft(scrollCache.getScrollLeft() + velocity * sign) break case 'top': sign = -1 // falls through case 'bottom': scrollCache.setScrollTop(scrollCache.getScrollTop() + velocity * sign) break } } // left/top are relative to document topleft private computeBestEdge(left: number, top: number): Edge | null { let { edgeThreshold } = this let bestSide: Edge | null = null for (let scrollCache of this.scrollCaches!) { let rect = scrollCache.clientRect let leftDist = left - rect.left let rightDist = rect.right - left let topDist = top - rect.top let bottomDist = rect.bottom - top // completely within the rect? if (leftDist >= 0 && rightDist >= 0 && topDist >= 0 && bottomDist >= 0) { if ( topDist <= edgeThreshold && this.everMovedUp && scrollCache.canScrollUp() && (!bestSide || bestSide.distance > topDist) ) { bestSide = { scrollCache, name: 'top', distance: topDist } } if ( bottomDist <= edgeThreshold && this.everMovedDown && scrollCache.canScrollDown() && (!bestSide || bestSide.distance > bottomDist) ) { bestSide = { scrollCache, name: 'bottom', distance: bottomDist } } if ( leftDist <= edgeThreshold && this.everMovedLeft && scrollCache.canScrollLeft() && (!bestSide || bestSide.distance > leftDist) ) { bestSide = { scrollCache, name: 'left', distance: leftDist } } if ( rightDist <= edgeThreshold && this.everMovedRight && scrollCache.canScrollRight() && (!bestSide || bestSide.distance > rightDist) ) { bestSide = { scrollCache, name: 'right', distance: rightDist } } } } return bestSide } private buildCaches() { return this.queryScrollEls().map((el) => { if (el === window) { return new WindowScrollGeomCache(false) // false = don't listen to user-generated scrolls } return new ElementScrollGeomCache(el, false) // false = don't listen to user-generated scrolls }) } private queryScrollEls() { let els = [] for (let query of this.scrollQuery) { if (typeof query === 'object') { els.push(query) } else { els.push(...Array.prototype.slice.call(document.querySelectorAll(query))) } } return els } }
oleg-babintsev/fullcalendar
packages/interaction/src/dnd/AutoScroller.ts
TypeScript
mit
6,439
'use strict'; angular.module('aqbClient', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngResource', 'ui.router', 'ui.bootstrap']); angular.module('aqbClient') .config(function ($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: '/', templateUrl: 'app/main/main.html', controller: 'MainCtrl' }); $urlRouterProvider.otherwise('/'); });
spaztick256/aquariumbuddy
client/src/app/index.js
JavaScript
mit
506
package com.sunny.grokkingalgorithms.fasttrack.week1; /** * Created by sundas on 6/20/2018. */ public class SumOfUpperPyramindInAMatrix { /* Find sum of upper pyramid ina matrix */ /** * * @param matrix * @return */ public static int findSUmOfUpperPyramid(int[][] matrix){ int sum = 0; for(int i = 0 ; i < matrix.length ; i++){ for(int j = 0 ; j < matrix[i].length ; j++){ if(i >= j){ sum += matrix[i][j]; } } } return sum; } public static int findSUmOfUpperPyramidAlternate(int[][] matrix){ int sum = 0; for(int i = 0 ; i < matrix.length ; i++){ for(int j = i ; j < matrix[i].length ; j++){ //if(i >= j){ sum += matrix[i][j]; //} } } return sum; } /** * * @param args */ public static void main(String[] args) { int[][] matrix = new int[][]{ {1,2,3,4}, {5,6,7,8}, {8,7,6,5}, {4,3,2,1} }; /* answer should be 43 */ System.out.println(findSUmOfUpperPyramid(matrix)); System.out.println(findSUmOfUpperPyramidAlternate(matrix)); } }
sunnydas/grokkingalgos
src/main/java/com/sunny/grokkingalgorithms/fasttrack/week1/SumOfUpperPyramindInAMatrix.java
Java
mit
1,149
module ActiveReloader class Configuration @@paths = ["app"] def self.paths=(value) @@paths = value end def self.paths if @@paths.is_a?(String) @@paths = [@@paths] end @@paths end def self.update(&block) yield self end end end
ilatif/active_reloader_rb
lib/active_reloader/configuration.rb
Ruby
mit
265
<?php /** * Template Name: Contact Page */ if ( have_posts() ) the_post(); $errors = array(); $bot = false; if ( isset($_POST['gpk_cabatcha']) && $_POST['gpk_cabatcha'] ) { /** * Collect quick info */ $quickInfo = array( 'IP' => $_SERVER['REMOTE_ADDR'], 'USER_AGENT' => $_SERVER['USER_AGENT'] ); /** * Check if it is possible bot */ if ( isset($_POST[$_POST['gpk_cabatcha']]) && $_POST[$_POST['gpk_cabatcha']] ) { /** * Send alert email to admin */ wp_mail('admin@geography.pk', 'Attention: Possible bot detected - Geography of Pakistan', implode('<br />', $quickInfo)); $bot = true; } /** * Send email to admin with user enquiry */ else { $enquirer_name = isset($_POST['enquirer_name']) && $_POST['enquirer_name'] ? htmlentities($_POST['enquirer_name']) : ''; $email = isset($_POST['email']) && $_POST['email'] ? htmlentities($_POST['email']) : ''; $enquiry = isset($_POST['enquiry']) && $_POST['enquiry'] ? htmlentities($_POST['enquiry']) : ''; /** * Validation */ if ( ! $enquirer_name ) { $errors['name'] = 'Please provide your name.'; } elseif ( $enquirer_name && strlen($enquirer_name) > 100 ) { $errors['name'] = 'Given name is too long.'; } elseif ( ! $email || strlen($email) > 255 || ! filter_var($email, FILTER_VALIDATE_EMAIL) ) { $errors['email'] = 'A valid email is required.'; } elseif ( ! $enquiry ) { $errors['message'] = 'Your message is required.'; } elseif ( $enquiry && strlen($enquiry) > 5000 ) { $errors['message'] = 'Your message is bit too long... o.O'; } else { $enquiry .= '<br /><hr />'; $enquiry .= implode(PHP_EOL, $quickInfo); if ( wp_mail('admin@geography.pk', 'Message by ' . $enquirer_name . ' - Geography of Pakistan', $enquiry, 'From: ' . $enquirer_name . '<' . $email . '>' . "\r\n" ) ) { header('Location: thank-you/?done=1&lang=en'); } } } } get_header(); ?> <!-- contents --> <div class="gpk-content gpk-page gpk-template"> <div class="container"> <div class="row"> <div class="col-md-12 gpk-main" role="main"> <div class="page-header"> <h1 class="post-title"><?php the_title(); ?></h1> </div> <?php the_content(); ?> <div class="form-horizontal pkg-contact-form"> <form autocomplete="off" action="<?php echo htmlentities(get_bloginfo('url') . '/contact/'); ?>" method="POST" enctype="multiform/form-data"> <div class="form-group<?php if (isset($errors['name'])) echo ' has-error'; ?>"> <label for="nameField" class="col-sm-2 control-label">Name:</label> <div class="col-sm-8"> <input type="text" name="enquirer_name" id="nameField" value="<?php echo (isset($_POST['enquirer_name']) && $_POST['enquirer_name'] ? htmlentities($_POST['enquirer_name']) : ''); ?>" class="form-control" maxlength="100"> <?php if ( isset($errors['name']) ) echo '<p class="text-danger text-right gpk-form-alerts"><i class="fa fa-info-circle"></i> ' . $errors['name'] . '</p>'; ?> </div> </div> <div class="form-group<?php if (isset($errors['email'])) echo ' has-error'; ?>"> <label for="emailField" class="col-sm-2 control-label">Email:</label> <div class="col-sm-8"> <input type="text" name="email" id="emailField" value="<?php echo (isset($_POST['email']) && $_POST['email'] ? htmlentities($_POST['email']) : ''); ?>" class="form-control" maxlength="255"> <?php if ( isset($errors['email']) ) echo '<p class="text-danger text-right gpk-form-alerts"><i class="fa fa-info-circle"></i> ' . $errors['email'] . '</p>'; ?> </div> </div> <div class="form-group<?php if (isset($errors['message'])) echo ' has-error'; ?>"> <label for="enquiryField" class="col-sm-2 control-label">Message:</label> <div class="col-sm-8"> <textarea rows="10" name="enquiry" id="enquiryField" value="<?php echo (isset($_POST['enquiry']) && $_POST['enquiry'] ? htmlentities($_POST['enquiry']) : ''); ?>" class="form-control" placeholder="Enter your message here..." maxlength="5000"></textarea> <?php if ( isset($errors['message']) ) echo '<p class="text-danger text-right gpk-form-alerts"><i class="fa fa-info-circle"></i> ' . $errors['message'] . '</p>'; ?> </div> </div> <div class="form-group"> <div class="col-sm-8 col-sm-offset-2"> <input type="hidden" tabindex="-1" name="gpk_<?php echo sha1(time()); ?>" value="" class="cabatcha form-control"> <input type="hidden" tabindex="-1" name="gpk_cabatcha" value="gpk_<?php echo sha1(time()); ?>" class="form-control"> <button type="submit" id="submitEnquiry" class="btn btn-success">Send Enquiry &raquo;</button> <p class="gpk-contact-notice"> We may record and send information about your IP address and browser with this enquiry. Read our <a href="/about/privacy/">privacy policy</a> for more information. </p> </div> </div> </form> </div> </div> <?php # get_sidebar(); ?> </div> </div> </div> <?php get_footer(); ?>
pkgeography/geography.pk
wordpress/wp-content/themes/pkgeography/page-templates/contact-page.php
PHP
mit
5,073
import datetime from django.conf import settings from django import template from django.core.urlresolvers import reverse from django.utils.dateformat import format from schedule.conf.settings import CHECK_PERMISSION_FUNC from schedule.models import Calendar from schedule.periods import weekday_names, weekday_abbrs, Month register = template.Library() @register.inclusion_tag("schedule/_month_table.html", takes_context=True) def month_table(context, calendar, month, size="regular", shift=None): if shift: if shift == -1: month = month.prev() if shift == 1: month = month.next() if size == "small": context['day_names'] = weekday_abbrs else: context['day_names'] = weekday_names context['calendar'] = calendar context['month'] = month context['size'] = size return context @register.inclusion_tag("schedule/_day_cell.html", takes_context=True) def day_cell(context, calendar, day, month, size="regular" ): context.update({ 'calendar' : calendar, 'day' : day, 'month' : month, 'size' : size }) return context @register.inclusion_tag("schedule/_daily_table.html", takes_context=True) def daily_table( context, day, width, width_slot, height, start=8, end=20, increment=30): """ Display a nice table with occurrences and action buttons. Arguments: width - width of the table (px) width_slot - width of the slot column (px) height - height of the table start - hour at which the day starts end - hour at which the day ends increment - size of a time slot (in minutes) """ user = context['request'].user context['addable'] = CHECK_PERMISSION_FUNC(None, user) width_occ = width - width_slot day_part = day.get_time_slot(day.start + datetime.timedelta(hours=start), day.start + datetime.timedelta(hours=end)) occurrences = day_part.get_occurrences() occurrences = _cook_occurrences(day_part, occurrences, width_occ, height) # get slots to display on the left slots = _cook_slots(day_part, increment, width, height) context['occurrences'] = occurrences context['slots'] = slots context['width'] = width context['width_slot'] = width_slot context['width_occ'] = width_occ context['height'] = height return context @register.inclusion_tag("schedule/_event_title.html", takes_context=True) def title(context, occurrence ): context.update({ 'occurrence' : occurrence, }) return context @register.inclusion_tag("schedule/_event_options.html", takes_context=True) def options(context, occurrence ): context.update({ 'occurrence' : occurrence, 'MEDIA_URL' : getattr(settings, "MEDIA_URL"), }) context['view_occurrence'] = occurrence.get_absolute_url() user = context['request'].user if CHECK_PERMISSION_FUNC(occurrence.event, user): context['edit_occurrence'] = occurrence.get_edit_url() print context['edit_occurrence'] context['cancel_occurrence'] = occurrence.get_cancel_url() context['delete_event'] = reverse('delete_event', args=(occurrence.event.id,)) context['edit_event'] = reverse('edit_event', args=(occurrence.event.calendar.slug, occurrence.event.id,)) else: context['edit_event'] = context['delete_event'] = '' return context @register.inclusion_tag("schedule/_create_event_options.html", takes_context=True) def create_event_url(context, calendar, slot ): context.update ( { 'calendar' : calendar, 'MEDIA_URL' : getattr(settings, "MEDIA_URL"), }) lookup_context = { 'calendar_slug': calendar.slug, } context['create_event_url'] ="%s%s" % ( reverse( "calendar_create_event", kwargs=lookup_context), querystring_for_date(slot)) return context class CalendarNode(template.Node): def __init__(self, content_object, distinction, context_var, create=False): self.content_object = template.Variable(content_object) self.distinction = distinction self.context_var = context_var def render(self, context): calendar = Calendar.objects.get_calendar_for_object(self.content_object.resolve(context), self.distinction) context[self.context_var] = Calendar.objects.get_calendar_for_object(self.content_object.resolve(context), self.distinction) return '' def do_get_calendar_for_object(parser, token): contents = token.split_contents() if len(contents) == 4: tag_name, content_object, _, context_var = contents distinction = None elif len(contents) == 5: tag_name, content_object, distinction, _, context_var = token.split_contents() else: raise template.TemplateSyntaxError, "%r tag follows form %r <content_object> as <context_var>" % (token.contents.split()[0], token.contents.split()[0]) return CalendarNode(content_object, distinction, context_var) class CreateCalendarNode(template.Node): def __init__(self, content_object, distinction, context_var, name): self.content_object = template.Variable(content_object) self.distinction = distinction self.context_var = context_var self.name = name def render(self, context): context[self.context_var] = Calendar.objects.get_or_create_calendar_for_object(self.content_object.resolve(context), self.distinction, name = self.name) return '' def do_get_or_create_calendar_for_object(parser, token): contents = token.split_contents() if len(contents) > 2: tag_name = contents[0] obj = contents[1] if 'by' in contents: by_index = contents.index('by') distinction = contents[by_index+1] else: distinction = None if 'named' in contents: named_index = contents.index('named') name = contents[named_index+1] if name[0] == name[-1]: name = name[1:-1] else: name = None if 'as' in contents: as_index = contents.index('as') context_var = contents[as_index+1] else: raise template.TemplateSyntaxError, "%r tag requires an a context variable: %r <content_object> [named <calendar name>] [by <distinction>] as <context_var>" % (token.split_contents()[0], token.split_contents()[0]) else: raise template.TemplateSyntaxError, "%r tag follows form %r <content_object> [named <calendar name>] [by <distinction>] as <context_var>" % (token.split_contents()[0], token.split_contents()[0]) return CreateCalendarNode(obj, distinction, context_var, name) register.tag('get_calendar', do_get_calendar_for_object) register.tag('get_or_create_calendar', do_get_or_create_calendar_for_object) @register.simple_tag def querystring_for_date(date, num=6): query_string = '?' qs_parts = ['year=%d', 'month=%d', 'day=%d', 'hour=%d', 'minute=%d', 'second=%d'] qs_vars = (date.year, date.month, date.day, date.hour, date.minute, date.second) query_string += '&amp;'.join(qs_parts[:num]) % qs_vars[:num] return query_string @register.simple_tag def prev_url(target, slug, period): return '%s%s' % ( reverse(target, kwargs=dict(calendar_slug=slug)), querystring_for_date(period.prev().start)) @register.simple_tag def next_url(target, slug, period): return '%s%s' % ( reverse(target, kwargs=dict(calendar_slug=slug)), querystring_for_date(period.next().start)) @register.inclusion_tag("schedule/_prevnext.html") def prevnext( target, slug, period, fmt=None): if fmt is None: fmt = settings.DATE_FORMAT context = { 'slug' : slug, 'period' : period, 'period_name': format(period.start, fmt), 'target':target, 'MEDIA_URL': settings.MEDIA_URL, } return context @register.inclusion_tag("schedule/_detail.html") def detail( occurrence ): context = { 'occurrence' : occurrence, 'MEDIA_URL': settings.MEDIA_URL, } return context def _period_duration(period): "Return the number of seconds of specified period" duration = period.end - period.start return (duration.days * 24 * 60 * 60) + duration.seconds def _cook_occurrences(period, occs, width, height): """ Prepare occurrences to be displayed. Calculate dimensions and position (in px) for each occurrence. The algorithm tries to fit overlapping occurrences so that they require a minimum number of "columns". Arguments: period - time period for the whole series occs - occurrences to be displayed increment - slot size in minutes width - width of the occurrences column (px) height - height of the table (px) """ last = {} # find out which occurrences overlap for o in occs[:]: o.data = period.classify_occurrence(o) if not o.data: occs.remove(o) continue o.level = -1 o.max = 0 if not last: last[0] = o o.level = 0 else: for k in sorted(last.keys()): if last[k].end <= o.start: o.level = k last[k] = o break if o.level == -1: k = k + 1 last[k] = o o.level = k # calculate position and dimensions for o in occs: # number of overlapping occurrences o.max = len([n for n in occs if not(n.end<=o.start or n.start>=o.end)]) for o in occs: o.cls = o.data['class'] o.real_start = max(o.start, period.start) o.real_end = min(o.end, period.end) # number of "columns" is a minimum number of overlaps for each overlapping group o.max = min([n.max for n in occs if not(n.end<=o.start or n.start>=o.end)] or [1]) w = int(width / (o.max)) o.width = w - 2 o.left = w * o.level duration_seconds = _period_duration(period) o.top = int(height * (float((o.real_start - period.start).seconds) / duration_seconds)) o.height = int(height * (float((o.real_end - o.real_start).seconds) / duration_seconds)) o.height = min(o.height, height - o.top) # trim what extends beyond the area return occs def _cook_slots(period, increment, width, height): """ Prepare slots to be displayed on the left hand side calculate dimensions (in px) for each slot. Arguments: period - time period for the whole series increment - slot size in minutes width - width of the slot column (px) height - height of the table (px) """ tdiff = datetime.timedelta(minutes=increment) num = _period_duration(period)/tdiff.seconds s = period.start slots = [] for i in range(num): sl = period.get_time_slot(s, s + tdiff) sl.top = int(height / float(num)) * i sl.height = int(height / float(num)) slots.append(sl) s = s + tdiff return slots @register.simple_tag def hash_occurrence(occ): return '%s_%s' % (occ.start.strftime('%Y%m%d%H%M%S'), occ.event.id)
tscholze/py-hasi-home-analytical-system-interface
hasi/schedule/templatetags/scheduletags.py
Python
mit
11,258
# """Test for views creation and link to html pages.""" # from pyramid import testing # from pyramid_learning_journal.models import ( # Entry, # get_tm_session, # ) # from pyramid_learning_journal.models.meta import Base # from pyramid_learning_journal.views.notfound import notfound_view # from pyramid_learning_journal.views.default import ( # list_view, # create_view, # detail_view, # edit_view # ) # from pyramid.config import Configurator # from pyramid.httpexceptions import HTTPNotFound, HTTPFound # from faker import Faker # import pytest # import datetime # import transaction # import os # FAKE_STUFF = Faker() # FAKE_ENTRIES = [Entry( # title=FAKE_STUFF.text(20), # body=FAKE_STUFF.text(250), # creation_date=datetime.datetime.now(), # ) for x in range(25)] # @pytest.fixture # def dummy_request(db_session): # """Make a fake HTTP request.""" # return testing.DummyRequest(dbsession=db_session) # @pytest.fixture # def add_models(dummy_request): # """Add entries to a dummy request.""" # dummy_request.dbsession.add_all(FAKE_ENTRIES) # @pytest.fixture(scope="session") # def configuration(request): # """Set up a Configurator instance.""" # config = testing.setUp(settings={ # 'sqlalchemy.url': os.environ.get('TEST_DATABASE') # }) # config.include('pyramid_learning_journal.models') # config.include('pyramid_learning_journal.routes') # def teardown(): # testing.tearDown() # request.addfinalizer(teardown) # return config # @pytest.fixture # def db_session(configuration, request): # """Create a session for interacting with the test database.""" # SessionFactory = configuration.registry['dbsession_factory'] # session = SessionFactory() # engine = session.bind # Base.metadata.create_all(engine) # def teardown(): # session.transaction.rollback() # Base.metadata.drop_all(engine) # request.addfinalizer(teardown) # return session # @pytest.fixture(scope="session") # def testapp(request): # """Create a test application to use for functional tests.""" # from webtest import TestApp # def main(global_config, **settings): # """Function returns a fake Pyramid WSGI application.""" # settings['sqlalchemy.url'] = os.environ.get('TEST_DATABASE') # config = Configurator(settings=settings) # config.include('pyramid_jinja2') # config.include('pyramid_learning_journal.models') # config.include('pyramid_learning_journal.routes') # config.add_static_view(name='static', # path='pyramid_learning_journal:static') # config.scan() # return config.make_wsgi_app() # app = main({}) # testapp = TestApp(app) # SessionFactory = app.registry['dbsession_factory'] # engine = SessionFactory().bind # Base.metadata.create_all(bind=engine) # def teardown(): # Base.metadata.drop_all(bind=engine) # request.addfinalizer(teardown) # return testapp # @pytest.fixture # def fill_test_db(testapp): # """Set fake entries to the db for a session.""" # SessionFactory = testapp.app.registry['dbsession_factory'] # with transaction.manager: # dbsession = get_tm_session(SessionFactory, transaction.manager) # dbsession.add_all(FAKE_ENTRIES) # # import pdb; pdb.set_trace() # return dbsession # @pytest.fixture # def reset_db(testapp): # """Clear and start a new DB.""" # SessionFactory = testapp.app.registry['dbsession_factory'] # engine = SessionFactory().bind # Base.metadata.drop_all(bind=engine) # Base.metadata.create_all(bind=engine) # @pytest.fixture # def post_request(dummy_request): # """Make a fake HTTP POST request.""" # dummy_request.method = "POST" # return dummy_request # # # ----- Unit Tests ----- # # def test_filling_fake_db(fill_test_db, db_session): # """Check for entries added to db.""" # assert len(db_session.query(Entry).all()) == 25 # # def test_list_view_returns_dict(dummy_request): # # """Test list view returns a dict when called.""" # # assert type(list_view(dummy_request)) == dict # # def test_detail_view_with_id_raises_except(dummy_request): # # """Test proper error raising with non matching id on detail view.""" # # dummy_request.matchdict['id'] = '9000' # # with pytest.raises(HTTPNotFound): # # detail_view(dummy_request) # # def test_detail_view_returns_dict_with_db(db_session, dummy_request): # # """Test detail view returns a dict when called.""" # # fake = Entry( # # title=u'Stuff', # # body=u'Some thing goes here.', # # creation_date=datetime.datetime.now(), # # ) # # db_session.add(fake) # # fakeid = str(db_session.query(Entry)[0].id) # # dummy_request.matchdict['id'] = fakeid # # response = detail_view(dummy_request) # # assert type(response) == dict # # def test_create_view_returns_dict(dummy_request): # # """Test create view returns a dict when called.""" # # assert type(create_view(dummy_request)) == dict # # def test_edit_view_returns_dict_with_db(testapp, db_session): # # """Test edit view returns a dict when called with a db.""" # # fake = Entry( # # title=u'Stuff', # # body=u'Some thing goes here.', # # creation_date=datetime.datetime.now(), # # ) # # db_session.add(fake) # # fakeid = str(db_session.query(Entry)[0].id) # # dummy_request.matchdict['id'] = fakeid # # response = testapp.get('/journal/1/edit-entry') # # --------------------------- # # response = edit_view(dummy_request) # # assert type(response) == dict # # def test_db_gets_new_entry_with_content(dummy_request, db_session): # # """Test db gets entry with proper content.""" # # fake = Entry( # # title=u'Stuff', # # body=u'Some thing goes here.', # # creation_date=datetime.datetime.now(), # # ) # # db_session.add(fake) # # fakeid = str(db_session.query(Entry)[0].id) # # dummy_request.matchdict['id'] = fakeid # # response = detail_view(dummy_request) # # assert len(db_session.query(Entry).all()) == 1 # # assert fake.title in response['entry'].title # # assert fake.body in response['entry'].body # # def test_edit_view_with_id_raises_except(dummy_request): # # """Test proper error raising with non matching id on edit view.""" # # dummy_request.matchdict['id'] = '9000' # # with pytest.raises(HTTPNotFound): # # edit_view(dummy_request) # # def test_list_view_returns_empty_without_db(dummy_request): # # """Test list view returns a dict when called.""" # # response = list_view(dummy_request) # # assert len(response['posts']) == 0 # # #----- Functional Tests ----- # # # def test_home_route_has_home_contents(testapp, db_session): # # """Test list view is routed to home page.""" # # response = testapp.get('/') # # assert '<h1 class="blog-title">The Pyramid Blog</h1>' in response # # def test_home_view_returns_200(testapp, db_session): # # """.""" # # response = testapp.get('/') # # assert response.status_code == 200 # # # def test_home_route_has_list_of_entries(testapp, db_session): # # # """Test if there are the right amount of entries on the home page.""" # # # response = testapp.get('/') # # # num_posts = len(response.html.find_all('h2')) # # # print(response) # # # assert num_posts == 25 # # # def test_new_entry_view_returns_proper_content(testapp, db_session): # # # """New entry view returns the actual content from the html.""" # # # response = testapp.get('/journal/new-entry') # # # # html = response.html # # # # expected_text = '<h1 class="blog-title">Create New Entry!</h1>' # # # print(response) # # # # assert expected_text in str(html) # # # # response = testapp.get('/') # # # # assert '<h1 class="blog-title">The Pyramid Blog</h1>' in response # # #<h1 class="blog-title">Entry View</h1> # # # def test_detail_view_has_single_entry(testapp, db_session, fill_test_db): # # # """Test that the detail page only brings up one entry.""" # # # response = testapp.get('/journal/1') # # # html = response.html # # # assert html.find() # # # num_list_items = (len(html.find_all('h3'))) # # # assert num_list_items == 1 # # # def test_detail_view_returns_proper_content(testapp, db_session, fill_test_db): # # # """Entry view returns a Response object when given a request.""" # # # # import pdb; pdb.set_trace() # # # response = testapp.get('/journal/1') # # # html = response.html # # # assert html.find() # # # expected_text = '<div class="entries">' # # # assert expected_text in str(html) # # # def test_edit_view_has_single_entry(testapp, db_session, fill_test_db): # # # """Test that the detail page only brings up one entry.""" # # # response = testapp.get('/journal/1/edit-entry') # # # html = response.html # # # assert html.find() # # # num_list_items = (len(html.find_all('h3'))) # # # assert num_list_items == 1 # # # def test_edit_view_returns_proper_content(testapp, db_session, fill_test_db): # # # """Entry view returns a Response object when given a request.""" # # # response = testapp.get('/journal/1/edit-entry') # # # assert '<div class="titlearea">' in response.html.text # # # def test_detail_view_with_bad_id(testapp, db_session, fill_test_db): # # # """.""" # # # response = testapp.get('/journal/9001', status=404) # # # assert "These are not the pages you're looking for!" in response.text # # # def test_edit_view_with_bad_id(testapp, db_session, fill_test_db): # # # """.""" # # # response = testapp.get('/journal/9001/edit-entry', status=404) # # # assert "These are not the pages you're looking for!" in response.text
endere/pyramid-learning-journal
pyramid_learning_journal/pyramid_learning_journal/tests.py
Python
mit
9,988
# -*- test-case-name: xmantissa.test.test_sharing -*- """ This module provides various abstractions for sharing public data in Axiom. """ import os import warnings from zope.interface import implementedBy, directlyProvides, Interface from twisted.python.reflect import qual, namedAny from twisted.protocols.amp import Argument, Box, parseString from epsilon.structlike import record from axiom import userbase from axiom.item import Item from axiom.attributes import reference, text, AND from axiom.upgrade import registerUpgrader ALL_IMPLEMENTED_DB = u'*' ALL_IMPLEMENTED = object() class NoSuchShare(Exception): """ User requested an object that doesn't exist, was not allowed. """ class ConflictingNames(Exception): """ The same name was defined in two separate interfaces. """ class RoleRelationship(Item): """ RoleRelationship is a bridge record linking member roles with group roles that they are members of. """ schemaVersion = 1 typeName = 'sharing_relationship' member = reference( doc=""" This is a reference to a L{Role} which is a member of my 'group' attribute. """) group = reference( doc=""" This is a reference to a L{Role} which represents a group that my 'member' attribute is a member of. """) def _entuple(r): """ Convert a L{record} to a tuple. """ return tuple(getattr(r, n) for n in r.__names__) class Identifier(record('shareID localpart domain')): """ A fully-qualified identifier for an entity that can participate in a message either as a sender or a receiver. """ @classmethod def fromSharedItem(cls, sharedItem): """ Return an instance of C{cls} derived from the given L{Item} that has been shared. Note that this API does not provide any guarantees of which result it will choose. If there are are multiple possible return values, it will select and return only one. Items may be shared under multiple L{shareID}s. A user may have multiple valid account names. It is sometimes impossible to tell from context which one is appropriate, so if your application has another way to select a specific shareID you should use that instead. @param sharedItem: an L{Item} that should be shared. @return: an L{Identifier} describing the C{sharedItem} parameter. @raise L{NoSuchShare}: if the given item is not shared or its store does not contain any L{LoginMethod} items which would identify a user. """ localpart = None for (localpart, domain) in userbase.getAccountNames(sharedItem.store): break if localpart is None: raise NoSuchShare() for share in sharedItem.store.query(Share, Share.sharedItem == sharedItem): break else: raise NoSuchShare() return cls( shareID=share.shareID, localpart=localpart, domain=domain) def __cmp__(self, other): """ Compare this L{Identifier} to another object. """ # Note - might be useful to have this usable by arbitrary L{record} # objects. It can't be the default, but perhaps a mixin? if not isinstance(other, Identifier): return NotImplemented return cmp(_entuple(self), _entuple(other)) class IdentifierArgument(Argument): """ An AMP argument which can serialize and deserialize an L{Identifier}. """ def toString(self, obj): """ Convert the given L{Identifier} to a string. """ return Box(shareID=obj.shareID.encode('utf-8'), localpart=obj.localpart.encode('utf-8'), domain=obj.domain.encode('utf-8')).serialize() def fromString(self, inString): """ Convert the given string to an L{Identifier}. """ box = parseString(inString)[0] return Identifier(shareID=box['shareID'].decode('utf-8'), localpart=box['localpart'].decode('utf-8'), domain=box['domain'].decode('utf-8')) class Role(Item): """ A Role is an identifier for a group or individual which has certain permissions. Items shared within the sharing system are always shared with a particular role. """ schemaVersion = 1 typeName = 'sharing_role' externalID = text( doc=""" This is the external identifier which the role is known by. This field is used to associate users with their primary role. If a user logs in as bob@divmod.com, the sharing system will associate his primary role with the pre-existing role with the externalID of 'bob@divmod.com', or 'Everybody' if no such role exists. For group roles, the externalID is not currently used except as a display identifier. Group roles should never have an '@' character in them, however, to avoid confusion with user roles. """, allowNone=False) # XXX TODO: In addition to the externalID, we really need to have something # that identifies what protocol the user for the role is expected to log in # as, and a way to identify the way that their role was associated with # their login. For example, it might be acceptable for some security # applications (e.g. spam prevention) to simply use an HTTP cookie. For # others (accounting database manipulation) it should be possible to # require more secure methods of authentication, like a signed client # certificate. description = text( doc=""" This is a free-form descriptive string for use by users to explain the purpose of the role. Since the externalID is used by security logic and must correspond to a login identifier, this can be used to hold a user's real name. """) def becomeMemberOf(self, groupRole): """ Instruct this (user or group) Role to become a member of a group role. @param groupRole: The role that this group should become a member of. """ self.store.findOrCreate(RoleRelationship, group=groupRole, member=self) def allRoles(self, memo=None): """ Identify all the roles that this role is authorized to act as. @param memo: used only for recursion. Do not pass this. @return: an iterator of all roles that this role is a member of, including itself. """ if memo is None: memo = set() elif self in memo: # this is bad, but we have successfully detected and prevented the # only really bad symptom, an infinite loop. return memo.add(self) yield self for groupRole in self.store.query(Role, AND(RoleRelationship.member == self, RoleRelationship.group == Role.storeID)): for roleRole in groupRole.allRoles(memo): yield roleRole def shareItem(self, sharedItem, shareID=None, interfaces=ALL_IMPLEMENTED): """ Share an item with this role. This provides a way to expose items to users for later retrieval with L{Role.getShare}. @param sharedItem: an item to be shared. @param shareID: a unicode string. If provided, specify the ID under which the shared item will be shared. @param interfaces: a list of Interface objects which specify the methods and attributes accessible to C{toRole} on C{sharedItem}. @return: a L{Share} which records the ability of the given role to access the given item. """ if shareID is None: shareID = genShareID(sharedItem.store) return Share(store=self.store, shareID=shareID, sharedItem=sharedItem, sharedTo=self, sharedInterfaces=interfaces) def getShare(self, shareID): """ Retrieve a proxy object for a given shareID, previously shared with this role or one of its group roles via L{Role.shareItem}. @return: a L{SharedProxy}. This is a wrapper around the shared item which only exposes those interfaces explicitly allowed for the given role. @raise: L{NoSuchShare} if there is no item shared to the given role for the given shareID. """ shares = list( self.store.query(Share, AND(Share.shareID == shareID, Share.sharedTo.oneOf(self.allRoles())))) interfaces = [] for share in shares: interfaces += share.sharedInterfaces if shares: return SharedProxy(shares[0].sharedItem, interfaces, shareID) raise NoSuchShare() def asAccessibleTo(self, query): """ @param query: An Axiom query describing the Items to retrieve, which this role can access. @type query: an L{iaxiom.IQuery} provider. @return: an iterable which yields the shared proxies that are available to the given role, from the given query. """ # XXX TODO #2371: this method really *should* be returning an L{IQuery} # provider as well, but that is kind of tricky to do. Currently, doing # queries leaks authority, because the resulting objects have stores # and "real" items as part of their interface; having this be a "real" # query provider would obviate the need to escape the L{SharedProxy} # security constraints in order to do any querying. allRoles = list(self.allRoles()) count = 0 unlimited = query.cloneQuery(limit=None) for result in unlimited: allShares = list(query.store.query( Share, AND(Share.sharedItem == result, Share.sharedTo.oneOf(allRoles)))) interfaces = [] for share in allShares: interfaces += share.sharedInterfaces if allShares: count += 1 yield SharedProxy(result, interfaces, allShares[0].shareID) if count == query.limit: return class _really(object): """ A dynamic proxy for dealing with 'private' attributes on L{SharedProxy}, which overrides C{__getattribute__} itself. This is pretty syntax to avoid ugly references to __dict__ and super and object.__getattribute__() in dynamic proxy implementations. """ def __init__(self, orig): """ Create a _really object with a dynamic proxy. @param orig: an object that overrides __getattribute__, probably L{SharedProxy}. """ self.orig = orig def __setattr__(self, name, value): """ Set an attribute on my original, unless my original has not yet been set, in which case set it on me. """ try: orig = object.__getattribute__(self, 'orig') except AttributeError: object.__setattr__(self, name, value) else: object.__setattr__(orig, name, value) def __getattribute__(self, name): """ Get an attribute present on my original using L{object.__getattribute__}, not the overridden version. """ return object.__getattribute__(object.__getattribute__(self, 'orig'), name) ALLOWED_ON_PROXY = ['__provides__', '__dict__'] class SharedProxy(object): """ A shared proxy is a dynamic proxy which provides exposes methods and attributes declared by shared interfaces on a given Item. These are returned from L{Role.getShare} and yielded from L{Role.asAccessibleTo}. Shared proxies are unlike regular items because they do not have 'storeID' or 'store' attributes (unless explicitly exposed). They are designed to make security easy to implement: if you have a shared proxy, you can access any attribute or method on it without having to do explicit permission checks. If you *do* want to perform an explicit permission check, for example, to render some UI associated with a particular permission, it can be performed as a functionality check instead. For example, C{if getattr(proxy, 'feature', None) is None:} or, more formally, C{IFeature.providedBy(proxy)}. If your interfaces are all declared and implemented properly everywhere, these checks will work both with shared proxies and with the original Items that they represent (but of course, the original Items will always provide all of their features). (Note that object.__getattribute__ still lets you reach inside any object, so don't imagine this makes you bulletproof -- you have to cooperate with it.) """ def __init__(self, sharedItem, sharedInterfaces, shareID): """ Create a shared proxy for a given item. @param sharedItem: The original item that was shared. @param sharedInterfaces: a list of interfaces which C{sharedItem} implements that this proxy should allow access to. @param shareID: the external identifier that the shared item was shared as. """ rself = _really(self) rself._sharedItem = sharedItem rself._shareID = shareID rself._adapterCache = {} # Drop all duplicate shared interfaces. uniqueInterfaces = list(sharedInterfaces) # XXX there _MUST_ Be a better algorithm for this for left in sharedInterfaces: for right in sharedInterfaces: if left.extends(right) and right in uniqueInterfaces: uniqueInterfaces.remove(right) for eachInterface in uniqueInterfaces: if not eachInterface.providedBy(sharedItem): impl = eachInterface(sharedItem, None) if impl is not None: rself._adapterCache[eachInterface] = impl rself._sharedInterfaces = uniqueInterfaces # Make me look *exactly* like the item I am proxying for, at least for # the purposes of adaptation # directlyProvides(self, providedBy(sharedItem)) directlyProvides(self, uniqueInterfaces) def __repr__(self): """ Return a pretty string representation of this shared proxy. """ rself = _really(self) return 'SharedProxy(%r, %r, %r)' % ( rself._sharedItem, rself._sharedInterfaces, rself._shareID) def __getattribute__(self, name): """ @return: attributes from my shared item, present in the shared interfaces list for this proxy. @param name: the name of the attribute to retrieve. @raise AttributeError: if the attribute was not found or access to it was denied. """ if name in ALLOWED_ON_PROXY: return object.__getattribute__(self, name) rself = _really(self) if name == 'sharedInterfaces': return rself._sharedInterfaces elif name == 'shareID': return rself._shareID for iface in rself._sharedInterfaces: if name in iface: if iface in rself._adapterCache: return getattr(rself._adapterCache[iface], name) return getattr(rself._sharedItem, name) raise AttributeError("%r has no attribute %r" % (self, name)) def __setattr__(self, name, value): """ Set an attribute on the shared item. If the name of the attribute is in L{ALLOWED_ON_PROXY}, set it on this proxy instead. @param name: the name of the attribute to set @param value: the value of the attribute to set @return: None """ if name in ALLOWED_ON_PROXY: self.__dict__[name] = value else: raise AttributeError("unsettable: "+repr(name)) def _interfacesToNames(interfaces): """ Convert from a list of interfaces to a unicode string of names suitable for storage in the database. @param interfaces: an iterable of Interface objects. @return: a unicode string, a comma-separated list of names of interfaces. @raise ConflictingNames: if any of the names conflict: see L{_checkConflictingNames}. """ if interfaces is ALL_IMPLEMENTED: names = ALL_IMPLEMENTED_DB else: _checkConflictingNames(interfaces) names = u','.join(map(qual, interfaces)) return names class Share(Item): """ A Share is a declaration that users with a given role can access a given set of functionality, as described by an Interface object. They should be created with L{Role.shareItem} and retrieved with L{Role.asAccessibleTo} and L{Role.getShare}. """ schemaVersion = 2 typeName = 'sharing_share' shareID = text( doc=""" The shareID is the externally-visible identifier for this share. It is free-form text, which users may enter to access this share. Currently the only concrete use of this attribute is in HTTP[S] URLs, but in the future it will be used in menu entries. """, allowNone=False) sharedItem = reference( doc=""" The sharedItem attribute is a reference to the item which is being provided. """, allowNone=False, whenDeleted=reference.CASCADE) sharedTo = reference( doc=""" The sharedTo attribute is a reference to the Role which this item is shared with. """, allowNone=False) sharedInterfaceNames = text( doc=""" This is an internal implementation detail of the sharedInterfaces attribute. """, allowNone=False) def __init__(self, **kw): """ Create a share. Consider this interface private; use L{shareItem} instead. """ # XXX TODO: All I really want to do here is to have enforcement of # allowNone happen at the _end_ of __init__; axiom should probably do # that by default, since there are several __init__s like this which # don't really do anything scattered throughout the codebase. kw['sharedInterfaceNames'] = _interfacesToNames(kw.pop('sharedInterfaces')) super(Share, self).__init__(**kw) def sharedInterfaces(): """ This attribute is the public interface for code which wishes to discover the list of interfaces allowed by this Share. It is a list of Interface objects. """ def get(self): if not self.sharedInterfaceNames: return () if self.sharedInterfaceNames == ALL_IMPLEMENTED_DB: I = implementedBy(self.sharedItem.__class__) L = list(I) T = tuple(L) return T else: return tuple(map(namedAny, self.sharedInterfaceNames.split(u','))) def set(self, newValue): self.sharedAttributeNames = _interfacesToNames(newValue) return get, set sharedInterfaces = property( doc=sharedInterfaces.__doc__, *sharedInterfaces()) def upgradeShare1to2(oldShare): "Upgrader from Share version 1 to version 2." sharedInterfaces = [] attrs = set(oldShare.sharedAttributeNames.split(u',')) for iface in implementedBy(oldShare.sharedItem.__class__): if set(iface) == attrs or attrs == set('*'): sharedInterfaces.append(iface) newShare = oldShare.upgradeVersion('sharing_share', 1, 2, shareID=oldShare.shareID, sharedItem=oldShare.sharedItem, sharedTo=oldShare.sharedTo, sharedInterfaces=sharedInterfaces) return newShare registerUpgrader(upgradeShare1to2, 'sharing_share', 1, 2) def genShareID(store): """ Generate a new, randomized share-ID for use as the default of shareItem, if none is specified. @return: a random share-ID. @rtype: unicode. """ return unicode(os.urandom(16).encode('hex'), 'ascii') def getEveryoneRole(store): """ Get a base 'Everyone' role for this store, which is the role that every user, including the anonymous user, has. """ return store.findOrCreate(Role, externalID=u'Everyone') def getAuthenticatedRole(store): """ Get the base 'Authenticated' role for this store, which is the role that is given to every user who is explicitly identified by a non-anonymous username. """ def tx(): def addToEveryone(newAuthenticatedRole): newAuthenticatedRole.becomeMemberOf(getEveryoneRole(store)) return newAuthenticatedRole return store.findOrCreate(Role, addToEveryone, externalID=u'Authenticated') return store.transact(tx) def getPrimaryRole(store, primaryRoleName, createIfNotFound=False): """ Get Role object corresponding to an identifier name. If the role name passed is the empty string, it is assumed that the user is not authenticated, and the 'Everybody' role is primary. If the role name passed is non-empty, but has no corresponding role, the 'Authenticated' role - which is a member of 'Everybody' - is primary. Finally, a specific role can be primary if one exists for the user's given credentials, that will automatically always be a member of 'Authenticated', and by extension, of 'Everybody'. @param primaryRoleName: a unicode string identifying the role to be retrieved. This corresponds to L{Role}'s externalID attribute. @param createIfNotFound: a boolean. If True, create a role for the given primary role name if no exact match is found. The default, False, will instead retrieve the 'nearest match' role, which can be Authenticated or Everybody depending on whether the user is logged in or not. @return: a L{Role}. """ if not primaryRoleName: return getEveryoneRole(store) ff = store.findUnique(Role, Role.externalID == primaryRoleName, default=None) if ff is not None: return ff authRole = getAuthenticatedRole(store) if createIfNotFound: role = Role(store=store, externalID=primaryRoleName) role.becomeMemberOf(authRole) return role return authRole def getSelfRole(store): """ Retrieve the Role which corresponds to the user to whom the given store belongs. """ return getAccountRole(store, userbase.getAccountNames(store)) def getAccountRole(store, accountNames): """ Retrieve the first Role in the given store which corresponds an account name in C{accountNames}. Note: the implementation currently ignores all of the values in C{accountNames} except for the first. @param accountNames: A C{list} of two-tuples of account local parts and domains. @raise ValueError: If C{accountNames} is empty. @rtype: L{Role} """ for (localpart, domain) in accountNames: return getPrimaryRole(store, u'%s@%s' % (localpart, domain), createIfNotFound=True) raise ValueError("Cannot get named role for unnamed account.") def shareItem(sharedItem, toRole=None, toName=None, shareID=None, interfaces=ALL_IMPLEMENTED): """ Share an item with a given role. This provides a way to expose items to users for later retrieval with L{Role.getShare}. This API is slated for deprecation. Prefer L{Role.shareItem} in new code. @param sharedItem: an item to be shared. @param toRole: a L{Role} instance which represents the group that has access to the given item. May not be specified if toName is also specified. @param toName: a unicode string which uniquely identifies a L{Role} in the same store as the sharedItem. @param shareID: a unicode string. If provided, specify the ID under which the shared item will be shared. @param interfaces: a list of Interface objects which specify the methods and attributes accessible to C{toRole} on C{sharedItem}. @return: a L{Share} which records the ability of the given role to access the given item. """ warnings.warn("Use Role.shareItem() instead of sharing.shareItem().", PendingDeprecationWarning, stacklevel=2) if toRole is None: if toName is not None: toRole = getPrimaryRole(sharedItem.store, toName, True) else: toRole = getEveryoneRole(sharedItem.store) return toRole.shareItem(sharedItem, shareID, interfaces) def _linearize(interface): """ Return a list of all the bases of a given interface in depth-first order. @param interface: an Interface object. @return: a L{list} of Interface objects, the input in all its bases, in subclass-to-base-class, depth-first order. """ L = [interface] for baseInterface in interface.__bases__: if baseInterface is not Interface: L.extend(_linearize(baseInterface)) return L def _commonParent(zi1, zi2): """ Locate the common parent of two Interface objects. @param zi1: a zope Interface object. @param zi2: another Interface object. @return: the rightmost common parent of the two provided Interface objects, or None, if they have no common parent other than Interface itself. """ shorter, longer = sorted([_linearize(x)[::-1] for x in zi1, zi2], key=len) for n in range(len(shorter)): if shorter[n] != longer[n]: if n == 0: return None return shorter[n-1] return shorter[-1] def _checkConflictingNames(interfaces): """ Raise an exception if any of the names present in the given interfaces conflict with each other. @param interfaces: a list of Zope Interface objects. @return: None @raise ConflictingNames: if any of the attributes of the provided interfaces are the same, and they do not have a common base interface which provides that name. """ names = {} for interface in interfaces: for name in interface: if name in names: otherInterface = names[name] parent = _commonParent(interface, otherInterface) if parent is None or name not in parent: raise ConflictingNames("%s conflicts with %s over %s" % ( interface, otherInterface, name)) names[name] = interface def getShare(store, role, shareID): """ Retrieve the accessible facet of an Item previously shared with L{shareItem}. This method is pending deprecation, and L{Role.getShare} should be preferred in new code. @param store: an axiom store (XXX must be the same as role.store) @param role: a L{Role}, the primary role for a user attempting to retrieve the given item. @return: a L{SharedProxy}. This is a wrapper around the shared item which only exposes those interfaces explicitly allowed for the given role. @raise: L{NoSuchShare} if there is no item shared to the given role for the given shareID. """ warnings.warn("Use Role.getShare() instead of sharing.getShare().", PendingDeprecationWarning, stacklevel=2) return role.getShare(shareID) def asAccessibleTo(role, query): """ Return an iterable which yields the shared proxies that are available to the given role, from the given query. This method is pending deprecation, and L{Role.asAccessibleTo} should be preferred in new code. @param role: The role to retrieve L{SharedProxy}s for. @param query: An Axiom query describing the Items to retrieve, which this role can access. @type query: an L{iaxiom.IQuery} provider. """ warnings.warn( "Use Role.asAccessibleTo() instead of sharing.asAccessibleTo().", PendingDeprecationWarning, stacklevel=2) return role.asAccessibleTo(query) def itemFromProxy(obj): """ Retrieve the real, underlying Item based on a L{SharedProxy} object, so that you can access all of its attributes and methods. This function is provided because sometimes it's hard to figure out how to cleanly achieve some behavior, especially running a query which relates to a shared proxy which you have retrieved. However, if you find yourself calling it a lot, that's a very bad sign: calling this method is implicitly a breach of the security that the sharing system tries to provide. Normally, if your code is acting as an agent of role X, it has access to a L{SharedProxy} that only provides interfaces explicitly allowed to X. If you make a mistake and call a method that the user is not supposed to be able to access, the user will receive an exception rather than be allowed to violate the system's security constraints. However, once you have retrieved the underlying item, all bets are off, and you have to perform your own security checks. This is error-prone, and should be avoided. We suggest, instead, adding explicitly allowed methods for performing any queries which your objects need. @param obj: a L{SharedProxy} instance @return: the underlying Item instance of the given L{SharedProxy}, with all of its methods and attributes exposed. """ return object.__getattribute__(obj, '_sharedItem') def unShare(sharedItem): """ Remove all instances of this item from public or shared view. """ sharedItem.store.query(Share, Share.sharedItem == sharedItem).deleteFromStore() def randomEarlyShared(store, role): """ If there are no explicitly-published public index pages to display, find a shared item to present to the user as first. """ for r in role.allRoles(): share = store.findFirst(Share, Share.sharedTo == r, sort=Share.storeID.ascending) if share is not None: return share.sharedItem raise NoSuchShare("Why, that user hasn't shared anything at all!")
twisted/mantissa
xmantissa/sharing.py
Python
mit
30,864
using Microsoft.Extensions.Logging; using Orleans; using Presence.Grains.Models; namespace Presence.Grains; /// <summary> /// Represents a game in progress and holds the game's state in memory. /// Notifies player grains about their players joining and leaving the game. /// Updates subscribed observers about the progress of the game. /// </summary> public class GameGrain : Grain, IGameGrain { private readonly ILogger<GameGrain> _logger; private readonly HashSet<IGameObserver> _observers = new(); private readonly HashSet<Guid> _players = new(); private GameStatus _status = GameStatus.Empty; public GameGrain(ILogger<GameGrain> logger) { _logger = logger; } private Guid GrainKey => this.GetPrimaryKey(); /// <summary> /// Presense grain calls this method to update the game with its latest status. /// </summary> public async Task UpdateGameStatusAsync(GameStatus status) { _status = status; // Check for new players that joined since last update foreach (var player in _status.PlayerKeys) { if (!_players.Contains(player)) { try { // Here we call player grains serially, which is less efficient than a fan-out but simpler to express. await GrainFactory.GetGrain<IPlayerGrain>(player).JoinGameAsync(this.AsReference<IGameGrain>()); _players.Add(player); } catch (Exception error) { // Ignore exceptions while telling player grains to join the game. // Since we didn't add the player to the list, this will be tried again with next update. _logger.LogWarning(error, "Failed to tell player {PlayerKey} to join game {GameKey}", player, GrainKey); } } } // Check for players that left the game since last update var promises = new List<(Guid PlayerKey, Task Task)>(); foreach (var player in _players) { if (!_status.PlayerKeys.Contains(player)) { // Here we do a fan-out with multiple calls going out in parallel. We join the promisses later. // More code to write but we get lower latency when calling multiple player grains. promises.Add((player, GrainFactory.GetGrain<IPlayerGrain>(player).LeaveGameAsync(this.AsReference<IGameGrain>()))); } } // Joining promises foreach (var (playerKey, task) in promises) { try { await task; _players.Remove(playerKey); } catch (Exception error) { _logger.LogWarning(error, "Failed to tell player {PlayerKey} to leave the game {GameKey}", playerKey, GrainKey); } } // Notify observers about the latest game score List<IGameObserver> failed = null!; foreach (var observer in _observers) { try { observer.UpdateGameScore(_status.Score); } catch (Exception error) { _logger.LogWarning(error, "Failed to notify observer {ObserverKey} of score for game {GameKey}. Removing observer.", observer.GetPrimaryKey(), GrainKey); // add observer to a list of failures // however defer failed list creation until necessary to avoid incurring an allocation on every call failed ??= new(); failed.Add(observer); } } // Remove dead observers if (failed is not null) { foreach (var observer in failed) { _observers.Remove(observer); } } return; } public Task ObserveGameUpdatesAsync(IGameObserver observer) { _observers.Add(observer); return Task.CompletedTask; } public Task UnobserveGameUpdatesAsync(IGameObserver observer) { _observers.Remove(observer); return Task.CompletedTask; } }
dotnet/orleans
samples/Presence/src/Grains/GameGrain.cs
C#
mit
4,214
<?php namespace App\Controllers\Sites; use \Psr\Http\Message\ServerRequestInterface as request; use App\Source\Factory\PageFactory; use App\Source\Factory\SectionFactory; use App\Models\Pages; use App\Models\Sections; class UniversalPageController extends BaseController { public function homeAction(request $req, $res){ $store = $this->c->cache->store(); if( !$store->has('controller.universal.homeAction') ){ $this->data['pageData'] = PageFactory::getPageWithRequest($req); $ar = $this->data['pageData']->toArray(); $store->put('controller.universal.homeAction', $ar, 60); } else { $this->data['pageData'] = $store->get('controller.universal.homeAction'); } $this->setRequestResult($req, $res); $this->render('public\main\pages\home.twig'); } public function detailAction(request $req, $res, $args){ if($args['pageCode']){ $this->data['pageData'] = PageFactory::getPageByCode($args['pageCode']); } else { $this->data['pageData'] = PageFactory::getPageWithRequest($req); } $this->setRequestResult($req, $res); $this->render('public\main\pages\detail_page.twig'); } public function sectionAction(request $req, $res){ $this->data['pageData'] = SectionFactory::getSectionWithRequest($req); $this->setRequestResult($req, $res); $this->data['subSections'] = Sections::getSubSections($this->data['pageData']->id); $this->data['pagesLinks'] = Pages::where('category_id', $this->data['pageData']->id)->get(); $this->render('public\main\pages\section_page.twig'); } public function notFound(request $req, $res){ $this->setRequestResult($req, $res); return $this->render('public\main\pages\404.twig'); } }
svncao/Ulan
app/Controllers/Sites/UniversalPageController.php
PHP
mit
1,671
namespace Web.Controllers { using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using Models.Identity; using Web.ViewModels.Account; [Authorize] public class AccountController : BaseController { // Used for XSRF protection when adding external logins private const string XsrfKey = "XsrfId"; private ApplicationSignInManager _signInManager; private ApplicationUserManager _userManager; public AccountController() { } public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager) { this.UserManager = userManager; this.SignInManager = signInManager; } public ApplicationSignInManager SignInManager { get { return this._signInManager ?? this.HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { this._signInManager = value; } } public ApplicationUserManager UserManager { get { return this._userManager ?? this.HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { this._userManager = value; } } private IAuthenticationManager AuthenticationManager { get { return this.HttpContext.GetOwinContext().Authentication; } } // // GET: /Account/ConfirmEmail [AllowAnonymous] public async Task<ActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return this.View("Error"); } var result = await this.UserManager.ConfirmEmailAsync(userId, code); return this.View(result.Succeeded ? "ConfirmEmail" : "Error"); } // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult ExternalLogin(string provider, string returnUrl) { // Request a redirect to the external login provider return new ChallengeResult( provider, this.Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl })); } // // GET: /Account/ExternalLoginCallback [AllowAnonymous] public async Task<ActionResult> ExternalLoginCallback(string returnUrl) { var loginInfo = await this.AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return this.RedirectToAction("Login"); } // Sign in the user with this external login provider if the user already has a login var result = await this.SignInManager.ExternalSignInAsync(loginInfo, false); switch (result) { case SignInStatus.Success: return this.RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return this.View("Lockout"); case SignInStatus.RequiresVerification: return this.RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }); default: // If the user does not have an account, then prompt the user to create an account this.ViewBag.ReturnUrl = returnUrl; this.ViewBag.LoginProvider = loginInfo.Login.LoginProvider; return this.View( "ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email }); } } // // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ExternalLoginConfirmation( ExternalLoginConfirmationViewModel model, string returnUrl) { if (this.User.Identity.IsAuthenticated) { return this.RedirectToAction("Index", "Manage"); } if (this.ModelState.IsValid) { // Get the information about the user from the external login provider var info = await this.AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return this.View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await this.UserManager.CreateAsync(user); if (result.Succeeded) { result = await this.UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await this.SignInManager.SignInAsync(user, false, false); return this.RedirectToLocal(returnUrl); } } this.AddErrors(result); } this.ViewBag.ReturnUrl = returnUrl; return this.View(model); } // // GET: /Account/ExternalLoginFailure [AllowAnonymous] public ActionResult ExternalLoginFailure() { return this.View(); } // // GET: /Account/ForgotPassword [AllowAnonymous] public ActionResult ForgotPassword() { return this.View(); } // // POST: /Account/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (this.ModelState.IsValid) { var user = await this.UserManager.FindByNameAsync(model.Email); if (user == null || !(await this.UserManager.IsEmailConfirmedAsync(user.Id))) { // Don't reveal that the user does not exist or is not confirmed return this.View("ForgotPasswordConfirmation"); } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>"); // return RedirectToAction("ForgotPasswordConfirmation", "Account"); } // If we got this far, something failed, redisplay form return this.View(model); } // // GET: /Account/ForgotPasswordConfirmation [AllowAnonymous] public ActionResult ForgotPasswordConfirmation() { return this.View(); } // // GET: /Account/Login [AllowAnonymous] public ActionResult Login(string returnUrl) { this.ViewBag.ReturnUrl = returnUrl; return this.View(); } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!this.ModelState.IsValid) { return this.View(model); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await this.SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, false); switch (result) { case SignInStatus.Success: return this.RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return this.View("Lockout"); case SignInStatus.RequiresVerification: return this.RedirectToAction("SendCode", new { ReturnUrl = returnUrl, model.RememberMe }); default: this.ModelState.AddModelError("", "Invalid login attempt."); return this.View(model); } } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public ActionResult LogOff() { this.AuthenticationManager.SignOut(); return this.RedirectToAction("Index", "Home"); } // // GET: /Account/Register [AllowAnonymous] public ActionResult Register() { return this.View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Register(RegisterViewModel model) { if (this.ModelState.IsValid) { var user = new ApplicationUser { UserName = model.UserName, Email = model.Email }; var result = await this.UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await this.SignInManager.SignInAsync(user, false, false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return this.RedirectToAction("Index", "Home"); } this.AddErrors(result); } // If we got this far, something failed, redisplay form return this.View(model); } // // GET: /Account/ResetPassword [AllowAnonymous] public ActionResult ResetPassword(string code) { return code == null ? this.View("Error") : this.View(); } // // POST: /Account/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model) { if (!this.ModelState.IsValid) { return this.View(model); } var user = await this.UserManager.FindByNameAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return this.RedirectToAction("ResetPasswordConfirmation", "Account"); } var result = await this.UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password); if (result.Succeeded) { return this.RedirectToAction("ResetPasswordConfirmation", "Account"); } this.AddErrors(result); return this.View(); } // // GET: /Account/ResetPasswordConfirmation [AllowAnonymous] public ActionResult ResetPasswordConfirmation() { return this.View(); } // // GET: /Account/SendCode [AllowAnonymous] public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe) { var userId = await this.SignInManager.GetVerifiedUserIdAsync(); if (userId == null) { return this.View("Error"); } var userFactors = await this.UserManager.GetValidTwoFactorProvidersAsync(userId); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return this.View( new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/SendCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> SendCode(SendCodeViewModel model) { if (!this.ModelState.IsValid) { return this.View(); } // Generate the token and send it if (!await this.SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider)) { return this.View("Error"); } return this.RedirectToAction( "VerifyCode", new { Provider = model.SelectedProvider, model.ReturnUrl, model.RememberMe }); } // // GET: /Account/VerifyCode [AllowAnonymous] public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe) { // Require that the user has already logged in via username/password or external login if (!await this.SignInManager.HasBeenVerifiedAsync()) { return this.View("Error"); } return this.View( new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/VerifyCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model) { if (!this.ModelState.IsValid) { return this.View(model); } // The following code protects for brute force attacks against the two factor codes. // If a user enters incorrect codes for a specified amount of time then the user account // will be locked out for a specified amount of time. // You can configure the account lockout settings in IdentityConfig var result = await this.SignInManager.TwoFactorSignInAsync( model.Provider, model.Code, model.RememberMe, model.RememberBrowser); switch (result) { case SignInStatus.Success: return this.RedirectToLocal(model.ReturnUrl); case SignInStatus.LockedOut: return this.View("Lockout"); case SignInStatus.Failure: default: this.ModelState.AddModelError("", "Invalid code."); return this.View(model); } } protected override void Dispose(bool disposing) { if (disposing) { if (this._userManager != null) { this._userManager.Dispose(); this._userManager = null; } if (this._signInManager != null) { this._signInManager.Dispose(); this._signInManager = null; } } base.Dispose(disposing); } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { this.ModelState.AddModelError("", error); } } private ActionResult RedirectToLocal(string returnUrl) { if (this.Url.IsLocalUrl(returnUrl)) { return this.Redirect(returnUrl); } return this.RedirectToAction("Index", "Home"); } internal class ChallengeResult : HttpUnauthorizedResult { public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) { } public ChallengeResult(string provider, string redirectUri, string userId) { this.LoginProvider = provider; this.RedirectUri = redirectUri; this.UserId = userId; } public string LoginProvider { get; set; } public string RedirectUri { get; set; } public string UserId { get; set; } public override void ExecuteResult(ControllerContext context) { var properties = new AuthenticationProperties { RedirectUri = this.RedirectUri }; if (this.UserId != null) { properties.Dictionary[XsrfKey] = this.UserId; } context.HttpContext.GetOwinContext().Authentication.Challenge(properties, this.LoginProvider); } } } }
webdude21/ContentRocks
Web/Controllers/AccountController.cs
C#
mit
17,936
using System.Net; namespace MailRuCloudApi.Api.Requests { class EnsureSdcCookieRequest : BaseRequest<string> { public EnsureSdcCookieRequest(CloudApi cloudApi) : base(cloudApi) { } public override HttpWebRequest CreateRequest(string baseDomain = null) { var request = base.CreateRequest(ConstSettings.AuthDomain); request.Accept = ConstSettings.DefaultAcceptType; return request; } public override string RelationalUri { get { var uri = $"/sdc?from={ConstSettings.CloudDomain}/home"; return uri; } } } }
yar229/Mail.Ru-.net-cloud-client
MailRuCloudApi/Api/Requests/EnsureSdcCookieRequest.cs
C#
mit
698
class RemoveArtistCompleteFromUsers < ActiveRecord::Migration def change remove_column :users, :artist_complete end end
9577/gart360-web
db/migrate/20140218195338_remove_artist_complete_from_users.rb
Ruby
mit
128
/* LedDisplay -- controller library for Avago HCMS-297x displays -- version 0.2 Copyright (c) 2009 Tom Igoe. Some right reserved. Revisions on version 0.2 and 0.3 by Mark Liebman, 27 Jan 2010 * extended a bit to support up to four (4) 8 character displays. vim: set ts=4: Controls an Avago HCMS29xx display. This display has 8 characters, each 5x7 LEDs This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "LedDisplay.h" // Pascal Stang's 5x7 font library: #include "font5x7.h" // The font library is stored in program memory: #include <avr/pgmspace.h> #include <string.h> /* * Constructor. Initializes the pins and the instance variables. */ LedDisplay::LedDisplay(uint8_t _dataPin, uint8_t _registerSelect, uint8_t _clockPin, uint8_t _chipEnable, uint8_t _resetPin, uint8_t _displayLength) { // Define pins for the LED display: this->dataPin = _dataPin; // connects to the display's data in this->registerSelect = _registerSelect; // the display's register select pin this->clockPin = _clockPin; // the display's clock pin this->chipEnable = _chipEnable; // the display's chip enable pin this->resetPin = _resetPin; // the display's reset pin this->displayLength = _displayLength; // number of bytes needed to pad the string this->cursorPos = 0; // position of the cursor in the display // do not allow a long multiple display to use more than LEDDISPLAY_MAXCHARS if (_displayLength > LEDDISPLAY_MAXCHARS) { _displayLength = LEDDISPLAY_MAXCHARS; } // fill stringBuffer with spaces, and a trailing 0: for (unsigned int i = 0; i < sizeof(stringBuffer); i++) { stringBuffer[i] = ' '; } this->setString(stringBuffer); // give displayString a default buffer } /* * Initialize the display. */ void LedDisplay::begin() { // set pin modes for connections: pinMode(dataPin, OUTPUT); pinMode(registerSelect, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(chipEnable, OUTPUT); pinMode(resetPin, OUTPUT); // reset the display: digitalWrite(resetPin, LOW); delay(10); digitalWrite(resetPin, HIGH); // load dot register with lows loadDotRegister(); // set control register 0 for max brightness, and no sleep: loadAllControlRegisters(B01111111); } /* * Clear the display */ void LedDisplay::clear() { this->setString(stringBuffer); for (int displayPos = 0; displayPos < displayLength; displayPos++) { // put the character in the dot register: writeCharacter(' ', displayPos); } // send the dot register array out to the display: loadDotRegister(); } /* * set the cursor to the home position (0) */ void LedDisplay::home() { // set the cursor to the upper left corner: this->cursorPos = 0; } /* * set the cursor anywhere */ void LedDisplay::setCursor(int whichPosition){ this->cursorPos = whichPosition; } /* * return the cursor position */ int LedDisplay::getCursor() { return this->cursorPos; } /* * write a byte out to the display at the cursor position, * and advance the cursor position. */ #if ARDUINO >= 100 size_t LedDisplay::write(uint8_t b) { #else void LedDisplay::write(uint8_t b) { #endif // make sure cursorPos is on the display: if (cursorPos >= 0 && cursorPos < displayLength) { // put the character into the dot register: writeCharacter(b, cursorPos); // put the character into the displayBuffer // but do not write the string constants pass // to us from the user by setString() if (this->displayString == stringBuffer && cursorPos < LEDDISPLAY_MAXCHARS) { stringBuffer[cursorPos] = b; } cursorPos++; // send the dot register array out to the display: loadDotRegister(); } #if ARDUINO >= 100 return 1; #endif } /* * Scroll the displayString across the display. left = -1, right = +1 */ void LedDisplay::scroll(int direction) { cursorPos += direction; // length of the string to display: int stringEnd = strlen(displayString); // Loop over the string and take displayLength characters to write to the display: for (int displayPos = 0; displayPos < displayLength; displayPos++) { // which character in the strings you want: int whichCharacter = displayPos - cursorPos; // which character you want to show from the string: char charToShow; // display the characters until you have no more: if ((whichCharacter >= 0) && (whichCharacter < stringEnd)) { charToShow = displayString[whichCharacter]; } else { // if none of the above, show a space: charToShow = ' '; } // put the character in the dot register: writeCharacter(charToShow, displayPos); } // send the dot register array out to the display: loadDotRegister(); } /* * set displayString */ void LedDisplay::setString(const char * _displayString) { this->displayString = _displayString; } /* * return displayString */ const char * LedDisplay::getString() { return displayString; } /* * return displayString length */ int LedDisplay::stringLength() { return strlen(displayString); } /* * set brightness (0 - 15) */ void LedDisplay::setBrightness(uint8_t bright) { // Limit the brightness if (bright > 15) { bright = 15; } // set the brightness: loadAllControlRegisters(B01110000 + bright); } /* this method loads bits into the dot register array. It doesn't * actually communicate with the display at all, * it just prepares the data: */ void LedDisplay::writeCharacter(char whatCharacter, byte whatPosition) { // calculate the starting position in the array. // every character has 5 columns made of 8 bits: byte thisPosition = whatPosition * 5; // copy the appropriate bits into the dot register array: for (int i = 0; i < 5; i++) { dotRegister[thisPosition+i] = (pgm_read_byte(&Font5x7[((whatCharacter - 0x20) * 5) + i])); } } // This method sends 8 bits to one of the control registers: void LedDisplay::loadControlRegister(uint8_t dataByte) { // select the control registers: digitalWrite(registerSelect, HIGH); // enable writing to the display: digitalWrite(chipEnable, LOW); // shift the data out: shiftOut(dataPin, clockPin, MSBFIRST, dataByte); // disable writing: digitalWrite(chipEnable, HIGH); } // This method sends 8 bits to the control registers in all chips: void LedDisplay::loadAllControlRegisters(uint8_t dataByte) { // Each display can have more than one control chip, and displays // can be daisy-chained into long strings. For some operations, such // as setting the brightness, we need to ensure that a single // control word reaches all displays simultaneously. We do this by // putting each chip into simultaneous mode - effectively coupling // all their data-in pins together. (See section "Serial/Simultaneous // Data Output D0" in datasheet.) // One chip drives four characters, so we compute the number of // chips by diving by four: int chip_count = displayLength / 4; // For each chip in the chain, write the control word that will put // it into simultaneous mode (seriel mode is the power-up default). for (int i = 0; i < chip_count; i++) { loadControlRegister(B10000001); } // Load the specified value into the control register. loadControlRegister(dataByte); // Put all the chips back into serial mode. Because they're still // all in simultaneous mode, we only have to write this word once. loadControlRegister(B10000000); } // this method originally sent 320 bits to the dot register: 12_30_09 ML void LedDisplay::loadDotRegister() { // define max data to send, patch for 4 length displays by KaR]V[aN int maxData = displayLength * 5; // select the dot register: digitalWrite(registerSelect, LOW); // enable writing to the display: digitalWrite(chipEnable, LOW); // shift the data out: for (int i = 0; i < maxData; i++) { shiftOut(dataPin, clockPin, MSBFIRST, dotRegister[i]); } // disable writing: digitalWrite(chipEnable, HIGH); } /* version() returns the version of the library: */ int LedDisplay::version(void) { return 4; }
Pocketart/typhoonclawvex
Musical_Instruments_2017_2018/Musical_Glove/OLD CODE/gloves/Gloves_R/teensy/avr/libraries/LedDisplay/LedDisplay.cpp
C++
mit
8,815
<?php namespace SamIT\TransIP; class BaseFactory { private $defaultOptions; public function __construct($userName, $privateKey, $mode = 'readonly', $defaultOptions = []) { $this->defaultOptions = array_merge([ 'privateKey' => $privateKey, 'userName' => $userName, 'mode' => $mode ], $defaultOptions); } protected function constructService($class, $options = []) { return new $class(array_merge($this->defaultOptions, $options)); } }
SAM-IT/transip-api
src/BaseFactory.php
PHP
mit
526
namespace _06_SumReversedNumbers { using System; using System.Collections.Generic; using System.Linq; public class StartUp { public static void Main() { List<string> numbers = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .ToList(); List<int> reversedNumbers = new List<int>(); for (int i = 0; i < numbers.Count; i++) { string number = numbers[i]; string reversedStr = ReverseTheString(number); int num = int.Parse(reversedStr); reversedNumbers.Add(num); } Console.WriteLine(reversedNumbers.Sum()); } private static string ReverseTheString(string number) { char[] arr = number.ToCharArray(); char[] reversed = arr.Reverse().ToArray(); string reversedString = string.Join("", reversed); return reversedString; } } }
MrPIvanov/SoftUni
02-Progr Fundamentals/16-Lists - Exercises/16-ListsExercises/06-SumReversedNumbers/StartUp.cs
C#
mit
1,051
package com.example.app_indicator_1; public class Constants { public static final String LOGTAG = "NetworkExplorer"; }
TSPZ/HelloGit
App_Indicator_1/src/com/example/app_indicator_1/Constants.java
Java
mit
125
import React from 'react'; import Header from './Header'; import Copyright from './Copyright'; import PCHeader from './PCHeader'; class App extends React.Component { componentDidMount() { $("#back-to-top").headroom({ tolerance: 2, offset: 50, classes: { initial: "animated", pinned: "fadeIn", unpinned: "fadeOut" } }); } render() { return ( <view> <div className="web-pc-banner"></div> <div className="pc-container"> <PCHeader /> {this.props.children} <Copyright /> <ToolBar /> </div> </view> ); } } class ToolBar extends React.Component { /** <a href="javascript:;" className="toolbar-item toolbar-item-app"> <span className="toolbar-code-layer"> <div id="urlcode"></div> </span> </a> */ render() { return (<div className="toolbar"> <a href="javascript:;" className="toolbar-item toolbar-item-weixin"> <span className="toolbar-layer2"> <img src="images/limao.jpg" width="130" height="130"/> </span> </a> <a href="javascript:;" className="toolbar-item toolbar-item-feedback"> <span className="toolbar-layer3"> <img src="images/weixin/kf.jpg" width="130" height="130"/> </span> </a> <a href="javascript:scroll(0,0)" id="top" className="toolbar-item toolbar-item-top"></a> </div>) } } class BackTop extends React.Component { render() { return (<a href="javascript:scroll(0,0)" id="back-to-top" style= {{display: "inline"}}><i className="glyphicon glyphicon-chevron-up"></i></a>) } } export default App;
kongchun/BigData-Web
app/components/App.js
JavaScript
mit
1,790
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class C_escribano extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('session'); $this->load->model('M_escribano'); } public function index() { if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $data['titulo'] = 'Bienvenido Escribano'; $data['minutasRechazadas'] = $this->M_escribano->getMinutasRechazadas( $this->session->userdata('idEscribano')); $data['cantM_rechazadas'] = $this->M_escribano->getCantMinutasRechazadas( $this->session->userdata('idEscribano')); $idEscri = $this->session->userdata('idEscribano'); $unEscribano=$this->M_escribano->getUnEscribano($idEscri); $data['escribano']=$unEscribano; //var_dump($this->session->userdata('usuario')); $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('home/escri',$data); $this->load->view('templates/pie',$data); } public function crearParcela($exito=FALSE, $hizo_post=FALSE, $otra_Parcela=FALSE,$editandoMinuta=FALSE) { if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } if (!$editandoMinuta) { $this->session->unset_userdata('editandoMinuta'); } if($otra_Parcela == TRUE){ $this->session->set_userdata('otraParcela',TRUE); $this->session->set_userdata('otroPh',FALSE); }else{ $this->session->set_userdata('otraParcela',FALSE); $this->session->set_userdata('otroPh',FALSE); } $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $data['arraydepartamentos'] = $this->M_escribano->getDepartamentos(); $data['exito']= $exito; $data['hizo_post']=$hizo_post; $data['titulo'] = 'Bienvenido Escribano'; if($this->input->post() && !$exito){ //seteo los demas input segun lo que ingreso anteriormente $data['circunscripcion'] = $this->input->post('circunscripcion'); $data['seccion']=$this->input->post('seccion'); $data['chacra'] = $this->input->post('chacra'); $data['quinta'] = $this->input->post('quinta'); $data['fraccion'] = $this->input->post('fraccion'); $data['manzana'] =$this->input->post('manzana'); $data['parcela'] = $this->input->post('parcela'); $data['partida'] = $this->input->post('partida'); $data['planoAprobado'] = $this->input->post('planoAprobado'); $data['fechaPlanoAprobado'] = $this->input->post('fechaPlanoAprobado'); $data['tipoPropiedad'] = $this->input->post('tipoPropiedad'); $data['tomo'] = $this->input->post('tomo'); $data['folio'] = $this->input->post('folio'); $data['finca'] = $this->input->post('finca'); $data['año'] = $this->input->post('año'); $data['localidades'] = $this->input->post('localidades'); $data['departamentos'] = $this->M_escribano->getNombreDepartamento($this->input->post('departamentos')); $data['descripcion'] = $this->input->post('descripcion'); $data['nroMatriculaRPI'] = $this->input->post('nroMatriculaRPI'); $data['fechaMatriculaRPI'] = $this->input->post('fechaMatriculaRPI'); $data['superficie'] = $this->input->post('superficie'); }else{ $data['circunscripcion']=''; $data['seccion']=''; $data['chacra']=''; $data{'quinta'}=''; $data{'fraccion'}=''; $data{'manzana'}=''; $data{'parcela'}=''; $data{'partida'}=''; $data{'planoAprobado'}=''; $data{'fechaPlanoAprobado'}=''; $data{'tipoPropiedad'}=''; $data{'tomo'}=''; $data{'folio'}=''; $data{'finca'}=''; $data{'año'}=''; $data{'localidades'}=''; $data{'departamentos'}=''; $data{'descripcion'}=''; $data{'nroMatriculaRPI'}=''; $data{'fechaMatriculaRPI'}=''; $data['superficie'] =""; } $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/parcela',$data); $this->load->view('templates/pie',$data); } public function registrarParcela() { $hizo_post=TRUE; $this->load->helper(array('form', 'url')); //set_reules(nombre del campo, mensaje a mostrar, reglas de validacion) $this->form_validation->set_rules('circunscripcion', 'circunscripcion', 'required',array('required' => 'Debes ingresar una circunscripcion ') ); $this->form_validation->set_rules('seccion', 'seccion', 'required',array('required' => 'Debes ingresar una sección ') ); $this->form_validation->set_rules('superficie', 'superficie', 'required',array('required' => 'Debes seleccionar una superficie') ); $this->form_validation->set_rules('partida', 'partida', 'required',array('required' => 'Debes ingresar una partida ') ); $this->form_validation->set_rules('planoAprobado', 'planoAprobado', 'required',array('required' => 'Debes ingresar un plano aprobado','is_unique'=>'Ya existe un escribano con el nombre de usuario ingresado') ); $this->form_validation->set_rules('fechaPlanoAprobado', 'fechaPlanoAprobado', 'required',array('required' => 'Debes ingresar una fecha ') ); $this->form_validation->set_rules('tipoPropiedad', 'tipoPropiedad','required|callback_check_propiedad'); $this->form_validation->set_message('check_propiedad', 'Debes seleccionar una Propiedad'); $this->form_validation->set_rules('tomo', 'tomo', 'required',array('required' => 'Debes ingresar un tomo') ); $this->form_validation->set_rules('folio', 'folio', 'required',array('required' => 'Debes ingresar un folio ') ); $this->form_validation->set_rules('finca', 'finca', 'required',array('required' => 'Debes ingresar una finca ') ); $this->form_validation->set_rules('año', 'año', 'required',array('required' => 'Debes ingresar un año ') ); $this->form_validation->set_rules('departamentos','departamentos','required|callback_check_departamento'); $this->form_validation->set_message('check_departamento', 'Debes seleccionar un departamento'); $this->form_validation->set_rules('localidades','localidades','required|callback_check_localidad'); $this->form_validation->set_message('check_localidad', 'Debes seleccionar una localidad'); $this->form_validation->set_rules('descripcion', 'descripcion', 'required',array('required' => 'Debes ingresar una descripcion ') ); $this->form_validation->set_rules('nroMatriculaRPI', 'matricualRpi', 'required',array('required' => 'Debes ingresar una matricula ') ); $this->form_validation->set_rules('fechaMatriculaRPI', 'fechaMatriculaRPI', 'required',array('required' => 'Debes ingresar una fecha ') ); if($this->form_validation->run() == FALSE) { $this->crearParcela(FALSE,TRUE, FALSE); }else{ $datos_parcela= array ( $date1=str_replace('/','-',$this->input->post('fechaPlanoAprobado')), $date2=str_replace('/','-',$this->input->post('fechaMatriculaRPI')), $date1=new DateTime($date1), $date2=new DateTime($date2), 'fechaPlanoAprobado' =>$date1->format('Y-m-d '), 'fechaMatriculaRPI' =>$date2->format('Y-m-d '), 'circunscripcion' => $this->input->post('circunscripcion'), 'seccion' => $this->input->post('seccion'), 'chacra' => $this->input->post('chacra'), 'quinta' => $this->input->post('correo'), 'fraccion' => $this->input->post('fraccion'), 'manzana' => $this->input->post('manzana'), 'parcela' => $this->input->post('parcela'), 'superficie' => $this->input->post('superficie'), 'partida' =>$this->input->post('partida'), 'tipoPropiedad' => $this->input->post('tipoPropiedad'), 'planoAprobado' => $this->input->post('planoAprobado'), 'descripcion' => $this->input->post('descripcion'), 'nroMatriculaRPI' => $this->input->post('nroMatriculaRPI'), 'departamentos' => $this->input->post('departamentos'), 'localidades' => $this->input->post('localidades'), 'tomo' => $this->input->post('tomo'), 'folio' => $this->input->post('folio'), 'finca' => $this->input->post('finca'), 'año' => $this->input->post('año'), ); $this->session->set_userdata($datos_parcela); $this->crearRelacion(FALSE,FALSE); } } public function crearRelacion($exito=FALSE, $hizo_post=FALSE, $otro_ph=FALSE){ if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } /*Variables para evitar que inserte una minuta y parcela cuando quiere agregar otro ph*/ if($otro_ph==TRUE){ $this->session->set_userdata('otroPh',TRUE); $this->session->set_userdata('otraParcela',TRUE); } $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $data['exito']= $exito; $data['hizo_post']=$hizo_post; if($this->input->post() && !$exito){ //seteo los demas input segun lo que ingreso anteriormente $data['ph'] = $this->input->post('ph'); $data['fecha_escritura'] = $this->input->post('fecha_escritura'); $data['nro_ucuf'] = $this->input->post('nro_ucuf'); $data['tipo_ucuf'] = $this->input->post('tipo_ucuf'); $data['plano_aprobado'] = $this->input->post('plano_aprobado'); $data['fecha_plano_aprobado'] =$this->input->post('fecha_plano_aprobado'); $data['porcentaje_ucuf'] = $this->input->post('porcentaje_ucuf'); $data['poligonos'] = $this->input->post('poligonos'); }else{ $data['ph']=''; $data['fecha_escritura']=''; $data['nro_ucuf']=''; $data['tipo_ucuf']=''; $data['plano_aprobado']=''; $data['fecha_plano_aprobado']=''; $data['porcentaje_ucuf']=''; $data['poligonos']=''; } $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/relacion',$data); $this->load->view('templates/pie',$data); } public function registrarRelacion(){ $hizo_post=TRUE; $this->load->helper(array('form', 'url')); //set_reules(nombre del campo, mensaje a mostrar, reglas de validacion) $this->form_validation->set_rules('fecha_escritura', 'fecha_escritura', 'required',array('required' => 'Debes ingresar una fecha de escritura') ); if($this->form_validation->run() == FALSE) { $this->crearRelacion(FALSE,TRUE); } else{ $datos_ph= array ( $date1=str_replace('/','-',$this->input->post('fecha_escritura')), $date2=str_replace('/','-',$this->input->post('fecha_plano_aprobado')), $date1=new DateTime($date1), $date2=new DateTime($date2), 'fecha_escritura' => $date1->format('Y-m-d '), 'fecha_plano_aprobado' =>$date2->format('Y-m-d '), 'ph' => $this->input->post('ph'), 'nro_ucuf' => $this->input->post('nro_ucuf'), 'tipo_ucuf' => $this->input->post('tipo_ucuf'), 'plano_aprobado' => $this->input->post('plano_aprobado'), 'porcentaje_ucuf' => $this->input->post('porcentaje_ucuf'), 'poligonos' => $this->input->post('poligonos'), ); $this->session->set_userdata($datos_ph); /* if($this->session->userdata('datos_ph')) { $ph_anterior = $this->session->userdata('datos_ph'); array_push($ph_anterior, $datos_ph); $this->session->set_userdata('propietario', $ph_anterior); }else { $array = array(); $this->session->set_userdata('datos_ph',$array); $ph_anterior = $this->session->userdata('datos_ph'); array_push($ph_anterior, $datos_ph); $this->session->set_userdata('datos_ph', $ph_anterior); } */ redirect(base_url().'index.php/c_escribano/crearPropietario',FALSE,FALSE); } } public function crearPropietario($exito=FALSE, $hizo_post=FALSE) { if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $data['arraydepartamentos'] = $this->M_escribano->getDepartamentos(); $data["personas"] = $this->M_escribano->getPersonas(); $data['exito']= $exito; $data['hizo_post']=$hizo_post; $data['titulo'] = 'Bienvenido Escribano'; if ($this->input->post('idPersonaSelect')==NULL) { $this->session->set_userdata('idPersonaSelect', $this->input->post('idPersonaSelect')); }else{ $this->session->set_userdata('idPersonaSelect', NULL); } /*Si elije agregar otro propietario asigna TRUE a $exito para que setee los campos de propietario*/ if($this->input->post('minuta') == "agregarpropietario") { $exito=TRUE; } if($this->input->post() && !$exito){ //seteo los demas input segun lo que ingreso anteriormente $data['propietario'] = $this->input->post('propietario'); $data['porcentaje_condominio'] = $this->input->post('porcentaje_condominio'); $data['tipo_propietario'] = $this->input->post('tipo_propietario'); $data['empresa'] = $this->input->post('empresa'); $data['nombreyapellido'] = $this->input->post('nombreyapellido'); $data['sexo_combobox']=$this->input->post('sexo_combobox'); $data['dni']=$this->input->post('dni'); $data['cuit'] = $this->input->post('cuit'); $data['cuil'] = $this->input->post('cuil'); $data['conyuge'] = $this->input->post('conyuge'); $data['fecha_nacimiento'] = $this->input->post('fecha_nacimiento'); $data['direccion'] =$this->input->post('direccion'); $data['departamentos'] = $this->input->post('departamentos'); $data['localidades'] = $this->input->post('localidades'); }else{ $data['propietario']=''; $data['tipo_propietario']=''; $data['porcentaje_condominio']=''; $data['tipo_propietario']=''; $data['empresa']=''; $data['nombreyapellido']=''; $data['sexo_combobox']=''; $data['dni']=''; $data['cuit']=''; $data['cuil']=''; $data['conyuge']=''; $data['fecha_nacimiento']=''; $data['direccion']=''; $data['departamentos']=''; $data['localidades']=''; } $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/propietario',$data); $this->load->view('templates/pie',$data); } public function registrarPropietario(){ $hizo_post=TRUE; $this->load->helper(array('form', 'url')); //set_reules(nombre del campo, mensaje a mostrar, reglas de validacion) if($this->input->post('propietario')=='P'){ $this->form_validation->set_rules('porcentaje_condominio', 'porcentaje_condominio', 'required',array('required' => 'Debes ingresar porcentaje de codominio') ); $this->form_validation->set_rules('nombreyapellido', 'nombreyapellido', 'required',array('required' => 'Debes ingresar una fecha de escritura') ); $this->form_validation->set_rules('tipo_propietario', 'tipo_propietario', 'required',array('required' => 'Debes ingresar un nombre y apellido')) ; $this->form_validation->set_rules('sexo_combobox', 'sexo_combobox', 'required',array('required' => 'Debes seleccionar tipo de sexo ') ); $this->form_validation->set_rules('dni', 'dni','required',array('required' => 'Debes ingresar un dni ') ); $this->form_validation->set_rules('departamentos','departamentos','required|callback_check_departamento'); $this->form_validation->set_message('check_departamento', 'Debes seleccionar un departamento'); $this->form_validation->set_rules('localidades','localidades','required|callback_check_localidad'); $this->form_validation->set_message('check_localidad', 'Debes seleccionar una localidad'); } else{ $this->form_validation->set_rules('porcentaje_condominio', 'porcentaje_condominio', 'required',array('required' => 'Debes ingresar porcentaje de codominio') ); $this->form_validation->set_rules('tipo_propietario', 'tipo_propietario', 'required',array('required' => 'Debes ingresar un nombre y apellido')); $this->form_validation->set_rules('nombreyapellido', 'nombreyapellido', 'required',array('required' => 'Debes ingresar un nombre y apellido') ); $this->form_validation->set_rules('cuit', 'cuit', 'required',array('required' => 'Debes ingresar un cuit ') ); $this->form_validation->set_rules('departamentos','departamentos','required|callback_check_departamento'); $this->form_validation->set_message('check_departamento', 'Debes seleccionar un departamento'); $this->form_validation->set_rules('localidades','localidades','required|callback_check_localidad'); $this->form_validation->set_message('check_localidad', 'Debes seleccionar una localidad'); } if($this->form_validation->run() == FALSE) { $this->crearPropietario(FALSE,TRUE); } else{ if($this->input->post('propietario')=='P') { $datos_propietario= array ( $date1=str_replace('/','-',$this->input->post('fecha_nacimiento')), $date1=new DateTime($date1), 'fecha_nacimiento' => $date1->format('Y-m-d '), 'propietario' => $this->input->post('propietario'), 'tipo_propietario' => $this->input->post('tipo_propietario'), 'porcentaje_condominio' => $this->input->post('porcentaje_condominio'), 'nombreyapellido' => $this->input->post('nombreyapellido'), 'sexo_combobox' => $this->input->post('sexo_combobox'), 'dni' => $this->input->post('dni'), 'cuit_cuil' => $this->input->post('cuil'), 'direccion' => $this->input->post('direccion'), 'conyuge' => $this->input->post('conyuge'), 'localidad' => $this->input->post('localidades'), ); }else{ $datos_propietario= array ( $date1=str_replace('/','-',$this->input->post('fecha_nacimiento')), $date1=new DateTime($date1), 'fecha_nacimiento' => $date1->format('Y-m-d '), 'propietario' => $this->input->post('propietario'), 'tipo_propietario' => $this->input->post('tipo_propietario'), 'porcentaje_condominio' => $this->input->post('porcentaje_condominio'), 'nombreyapellido' => $this->input->post('nombreyapellido'), 'sexo_combobox' => $this->input->post('sexo_combobox'), 'dni' => $this->input->post('dni'), 'cuit_cuil' => $this->input->post('cuit'), 'direccion' => $this->input->post('direccion'), 'conyuge' => $this->input->post('conyuge'), 'localidad' => $this->input->post('localidades'), ); } /*$this->session->set_userdata($datos_propietario);*/ if($this->session->userdata('propietario')&&(!$this->session->userdata('propietario')=='')) { $propietario_anterior = $this->session->userdata('propietario'); array_push($propietario_anterior, $datos_propietario); $this->session->set_userdata('propietario', $propietario_anterior); }else { $array = array(); $this->session->set_userdata('propietario',$array); $propietario_anterior = $this->session->userdata('propietario'); array_push($propietario_anterior, $datos_propietario); $this->session->set_userdata('propietario', $propietario_anterior); } /*verifica si presionó boton agregar propietario o guardar*/ if($this->input->post('minuta') == "agregar") { $this->crearPropietario(TRUE,FALSE); } else { $this->M_escribano->insertarMinuta(); $this->finMinutas(); } } } function finMinutas(){ $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/finMinuta',$data); $this->load->view('templates/pie',$data); } function checkPost(){ if($this->input->post('finminuta') == "agregarph") { $this->session->unset_userdata('datos_ph'); $this->session->unset_userdata('propietario'); $this->crearRelacion(FALSE, TRUE, TRUE); }else{ $this->session->unset_userdata('datos_parcela'); $this->session->unset_userdata('datos_ph'); $this->session->unset_userdata('propietario'); $this->crearParcela(FALSE, TRUE, TRUE); } } //verifica que haya seleccionado alguna localidad function check_localidad($post_string){ if($post_string=="Seleccione localidad"){ return FALSE;} else{ return TRUE; } } //verifica que haya seleccionado algun departamento function check_departamento($post_string){ if($post_string==""){ return FALSE;} else{ return TRUE; } } //verifica que haya seleccionado algun tipo de propiedad function check_propiedad($post_string){ if($post_string==""){ return FALSE;} else{ return TRUE; } } function check_tipoucuf($post_string){ if($post_string=="Seleccionar"){ return FALSE;} else{ return TRUE; } } function cargarLocalidades(){ $id_departamento=$this->input->post('id_departamento'); echo json_encode($this->M_escribano->getLocalidades($id_departamento)); } public function departamento() { $id_prov=$_POST["miprovincia"]; //$departamentos=$this->db->get("departamento")->result(); $departamentos=$this->db->get_where('departamento', array('idProvincia'=>$id_prov))->result(); $id_dep=0; foreach ($departamentos as $d ) { $id_dep+=1; echo"<option value='$id_dep'>$d->nombre</option>"; } } public function localidad() { $id_dep=$_POST["midepartamento"]; //$departamentos=$this->db->get("departamento")->result(); $localidades=$this->db->get_where('localidad', array('idDepartamento'=>$id_dep))->result(); //en este caso quiero que en el value aparezca el id que esta en la tabla , porque este valor me va a servir para insertar en la tabla usuarioescribano foreach ($localidades as $l ) { echo"<option value='$l->idLocalidad'>$l->nombre</option>"; } } public function registrarMinuta() { if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $data['titulo'] = 'Bienvenido Escribano'; $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/minuta',$data); $this->load->view('templates/pie',$data); } public function verMinutas() { if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } $data['titulo'] = 'Bienvenido Escribano'; $data["minutas"] = $this->M_escribano->getMinutasPorFecha($this->session->userdata('idEscribano')); $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/verMinutas',$data); $this->load->view('templates/pie',$data); } public function verUnaMinuta($param="") { if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $data['titulo'] = 'Bienvenido Escribano'; $data["minuta"] = $this->M_escribano->getUnaMinuta($param); $idEscribano = $data["minuta"][0]->idEscribano; $data["unEscribano"] = $this->M_escribano->getUnEscribano($idEscribano); $idMinuta = $data["minuta"][0]->idMinuta; $data["parcelas"] =$this->M_escribano->getParcelas($idMinuta); //var_dump($data["parcelas"]); $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/verUnaMinuta',$data); $this->load->view('templates/pie',$data); } public function verPropietarios($param="") { if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $data['titulo'] = 'Bienvenido Escribano'; $data['propietariosAd'] = $this->M_escribano->getPropietarios_porMinuta_Ad($param); $data['propietariosTr'] = $this->M_escribano->getPropietarios_porMinuta_Tr($param); //var_dump($data['propietarios']); $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/verPropietarios',$data); $this->load->view('templates/pie',$data); } public function imprimirMinuta($param="") { if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $data['titulo'] = 'Bienvenido Escribano'; $data["minuta"] = $this->M_escribano->getUnaMinuta($param); $idEscribano = $data["minuta"][0]->idEscribano; $data["unEscribano"] = $this->M_escribano->getUnEscribano($idEscribano); $idMinuta = $data["minuta"][0]->idMinuta; $data["parcelas"] =$this->M_escribano->getParcelas($idMinuta); //$this->load->view('templates/cabecera_escribano',$data); //$this->load->view('templates/escri_menu',$data); $this->load->view('escribano/imprimirMinuta',$data); //$this->load->view('templates/pie',$data); } public function nuevoPedido($exito=FALSE, $hizo_post=FALSE){ if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } $data['titulo'] = 'Bienvenido escribano'; $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/nuevoPedido',$data); $this->load->view('templates/pie',$data); } public function crearPedido($exito=FALSE, $hizo_post=FALSE){ if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $data['titulo'] = 'Bienvenido escribano'; $descripcion=$_POST['pedido']; $idEscribano=$_POST['idEscribano']; $datetime_variable = new DateTime(); $datetime_formatted = date_format($datetime_variable, 'Y-m-d H:i:s'); $datos_usuarios= array ( 'idEscribano' => $idEscribano, 'descripcion' => $descripcion, 'fechaPedido' =>$datetime_formatted, 'estadoPedido' =>'P' ); $this->db->insert("pedidos", $datos_usuarios); redirect(base_url().'index.php/c_escribano/verPedidos'); } public function verPedidos() { if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_escribano_login'); } $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $idEscribano=$this->session->userdata('idEscribano'); $data['pedidos']=$this->M_escribano->getPedidos($idEscribano); $data['titulo'] = 'Bienvenido Escribano'; $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/verPedidos',$data); $this->load->view('templates/pie',$data); } public function buscar_min_a_x_id(){ if ($_POST["idMinuta"]==null) { $idMinuta=""; }else { $idMinuta=$_POST["idMinuta"]; }; $noti_min=array("idMinuta"=>$idMinuta,"estado"=>"A"); $this->session->set_flashdata('noti_min',$noti_min); redirect(base_url().'index.php/c_escribano/verMinutas'); } public function buscar_min_r_x_id(){ if ($_POST["idMinuta"]==null) { $idMinuta=""; }else { $idMinuta=$_POST["idMinuta"]; }; $noti_min=array("idMinuta"=>$idMinuta,"estado"=>"R"); $this->session->set_flashdata('noti_min',$noti_min); redirect(base_url().'index.php/c_escribano/verMinutas'); } public function buscar_si(){ if ($_POST["idPedido"]==null) { $idPedido=""; }else { $idPedido=$_POST["idPedido"]; }; $noti_si=array("idPedido"=>$idPedido,"estadoPedido"=>"C"); $this->session->set_flashdata('noti_si',$noti_si); redirect(base_url().'index.php/c_escribano/verPedidos'); } public function notificaciones_ma(){ $idEscribano=$this->session->userdata('idEscribano'); return( $this->M_escribano->getMinutasxEstadoxisEscribano('A',$idEscribano)); } public function notificaciones_mr(){ $idEscribano=$this->session->userdata('idEscribano'); return( $this->M_escribano->getMinutasxEstadoxisEscribano('R',$idEscribano)); } public function notificaciones_si(){ $idEscribano=$this->session->userdata('idEscribano'); $this->db->from('pedidos'); $this->db->where('estadoPedido', "C"); $this->db->where('idEscribano', $idEscribano); $this->db->order_by('idPedido', 'DESC'); $this->db->limit(10); return( $this->db->get()->result()); } public function buscarParcelas() { if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $idEscribano=$this->session->userdata('idEscribano'); $this->db->select('minuta.fechaIngresoSys,minuta.idMinuta,relacion.fechaEscritura,relacion.nroUfUc,relacion.tipoUfUc,parcela.circunscripcion,parcela.seccion,parcela.chacra,parcela.quinta,parcela.fraccion,parcela.manzana,parcela.parcela,parcela.planoAprobado,parcela.nroMatriculaRPI,parcela.idLocalidad,parcela.idParcela'); $this->db->from('parcela'); $this->db->join('minuta', 'parcela.idMinuta = minuta.idMinuta','left'); $this->db->join('relacion', 'relacion.idParcela=parcela.idParcela'); $this->db->where('idEscribano', $idEscribano); $parcelas= $this->db->get()->result(); $data['parcelas']=$parcelas; $data['titulo'] = 'Bienvenido Escribano'; $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/buscarParcelas',$data); $this->load->view('templates/pie',$data); } public function buscar_min_id(){ if ($_POST["idMinuta"]==null) { $idMinuta=""; }else { $idMinuta=$_POST["idMinuta"]; }; $noti_min=array("idMinuta"=>$idMinuta); $this->session->set_flashdata('noti_min',$noti_min); redirect(base_url().'index.php/c_escribano/verMinutas'); } public function detalles_parcela(){ $idParcela=$_POST["idParcela"]; $parcela=$this->db->get_where('parcela', array('idParcela'=>$idParcela))->row(); $date=new DateTime($parcela->fechaPlanoAprobado); $date_formated=$date->format('d/m/Y '); $fecha_planoAprobado=$date_formated; $date2=new DateTime($parcela->fechaMatriculaRPI); $date_formated2=$date->format('d/m/Y '); $fecha_matriculaRPI=$date_formated; echo " <tr> <th> Circunscripcion</th><td>$parcela->circunscripcion </td> </tr> <tr> <th> Sección</th><td>$parcela->seccion </td> </tr> <tr> <th> Chacra</th><td>$parcela->chacra </td> </tr> <tr> <th> Quinta</th><td>$parcela->quinta </td> </tr> <tr> <th> Fracción</th><td>$parcela->fraccion </td> </tr> <tr> <th> Manzana</th><td>$parcela->manzana </td> </tr> <tr> <th> Parcela</th><td>$parcela->parcela </td> </tr> <tr> <th> Superficie</th><td>$parcela->superficie </td> </tr> <tr> <th> Partida</th><td>$parcela->partida </td> </tr> <tr> <th> Tipo de Propiedad</th><td>$parcela->tipoPropiedad </td> </tr> <tr> <th> Plano Aprobado</th><td>$parcela->planoAprobado</td> </tr> <tr> <th> Fecha Plano Aprobado</th><td>$fecha_planoAprobado </td> </tr> <tr> <th> Descripción</th><td>$parcela->descripcion</td> </tr> <tr> <th> Nro de Matrícula RPI</th><td>$parcela->nroMatriculaRPI</td> </tr> <tr> <th> Fecha Matrícula RPI</th><td>$fecha_matriculaRPI</td> </tr> <tr> <th> Tomo</th><td>$parcela->tomo</td> </tr> <tr> <th> Folio</th><td>$parcela->folio</td> </tr> <tr> <th>Finca</th><td>$parcela->finca</td> </tr> <tr> <th> Año</th><td>$parcela->año</td> </tr> "; } public function verPerfil() { if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } //muestra las notificaciones $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $idEscribano = $this->session->userdata('idEscribano'); $data['unEscribano'] = $this->M_escribano->getUnEscribano($idEscribano); $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/perfil_escribano',$data); $this->load->view('templates/pie',$data); } public function editarEscribano($idUsuario="",$exito=FALSE, $hizo_post=FALSE) { if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } $data['exito']= $exito; $data['hizo_post']=$hizo_post; //muestra las notificaciones $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $data['titulo'] = 'Bienvenido Escribano'; $idEscribano = $this->session->userdata('idEscribano'); $data["unEscribano"] = $this->M_escribano->getUnEscribano($idEscribano); //var_dump($data["operador"]); $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/perfil_escribano',$data); $this->load->view('templates/pie',$data); } public function actualizarEscribano() { $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $data['titulo'] = 'Bienvenido Escribano'; $idUsuario = $this->session->userdata('idEscribano'); $hizo_post=TRUE; $this->load->helper(array('form', 'url')); $this->form_validation->set_rules('nomyap', 'nomyap', 'required',array('required' => 'Debes ingresar un Nombre y Apellido ') ); $this->form_validation->set_rules('dni', 'dni', 'required',array('required' => 'Debes ingresar DNI ')); $this->form_validation->set_rules('email', 'email', 'required',array('required' => 'Debes ingresar un correo ') ); $this->form_validation->set_rules('telefono', 'telefono', 'required',array('required' => 'Debes ingresar numero de teleéfono ') ); $this->form_validation->set_rules('direccion', 'direccion', 'required',array('required' => 'Debes ingresar una dirección ') ); $this->form_validation->set_rules('matricula', 'matricula', 'required',array('required' => 'Debes ingresar una matricula ') ); $this->form_validation->set_rules('usuario', 'usuario', 'required|min_length[6]',array('required' => 'Debes ingresar un nombre de Usuario ','min_length'=> 'El nombre de usuario debe ser de al menos 6 digitos') ); $checked = $this->input->post('cambiar_pass'); if ($checked == 1) { # code... $this->form_validation->set_rules('contraseña', 'contraseña', 'required|min_length[6]',array('required' => 'Debes ingresar una contraseña ','min_length'=> 'La contraseña debe ser de al menos 6 dígitos ') ); $this->form_validation->set_rules('repeContraseña', 'repeContraseña', 'required|matches[contraseña]',array('required' => 'Debes volver a ingresar la contraseña ','matches'=> 'Las dos contraseñas no coinciden ') ); } if($this->form_validation->run() == FALSE) { $this->editarEscribano($idUsuario,FALSE,TRUE); }else{ //actualizo if ($checked == 1) { $contraseña = $this->input->post('contraseña'); $escriAct= array( //Nombre del campo en la bd -----> valor del campo name en la vista 'nomyap' => $this->input->post("nomyap"), 'usuario' => $this->input->post("usuario"), 'dni' => $this->input->post("dni"), 'telefono' => $this->input->post("telefono"), 'direccion' => $this->input->post("direccion"), //'idLocalidad' => $this->input->post('localidad'), 'email' => $this->input->post('email'), 'matricula' => $this->input->post('matricula'), 'contraseña' => sha1($contraseña) ); } else { $escriAct= array( //Nombre del campo en la bd -----> valor del campo name en la vista 'nomyap' => $this->input->post("nomyap"), 'usuario' => $this->input->post("usuario"), 'dni' => $this->input->post("dni"), 'telefono' => $this->input->post("telefono"), 'direccion' => $this->input->post("direccion"), //'idLocalidad' => $this->input->post('localidad'), 'email' => $this->input->post('email'), 'matricula' => $this->input->post('matricula') ); } $ctrl=$this->M_escribano->actualizarEscribano($escriAct,$idUsuario); $this->editarEscribano($idUsuario,TRUE,TRUE); } } public function obtenerDepartamento_x_idLoc(){ $idLocalidad=$_POST["idLocalidad"]; $this->db->select('*'); $this->db->from('departamento'); $this->db->join('localidad', 'localidad.idDepartamento = departamento.idDepartamento'); $this->db->where('localidad.idLocalidad', $idLocalidad); echo $this->db->get()->row()->idDepartamento; } public function mostrarLocalidad() { $id_dep=$_POST["midepartamento"]; $this->db->select('localidad.idLocalidad, localidad.nombre'); $this->db->from('localidad'); $this->db->where('localidad.idDepartamento', $id_dep); $localidades=$this->db->get()->result(); echo"<option value=''>Seleccione una localidad</option>"; //en este caso quiero que en el value aparezca el id que esta en la tabla , porque este valor me va a servir para insertar en la tabla usuarioescribano foreach ($localidades as $l ) { echo"<option value='$l->idLocalidad' >$l->nombre</option>"; } } function sacarPropietario(){ $posicion=$_POST['posicion']; $nuevosPropietarios=$this->session->userdata('propietario'); unset($nuevosPropietarios[$posicion]); $this->session->set_userdata('propietario', $nuevosPropietarios); redirect(base_url().'index.php/c_escribano/crearPropietario'); } //Para editar la minuta rechazada public function editarMinuta($idMinuta) {if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } //muestra las notificaciones $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $data['titulo'] = 'Bienvenido Escribano'; $data['idMinutaEditar']=$idMinuta; $this->session->set_userdata('idMinutaEditar',$idMinuta); $data['fechaInscMinuta']=$this->M_escribano->getfechaInscMinuta($idMinuta); $data['motivoRechazo']=$this->M_escribano->getMinutaxId($idMinuta)->motivoRechazo; $data['parcelas']=$this->db->get_where('parcela', array('idMinuta'=>$idMinuta))->result(); //var_dump($data["operador"]); $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/editarMinuta',$data); $this->load->view('templates/pie',$data); } public function editarParcela($idParcela,$exito=FALSE, $hizo_post=FALSE) { if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $data['arraydepartamentos'] = $this->M_escribano->getDepartamentos(); $data['exito']= $exito; $data['hizo_post']=$hizo_post; $data['titulo'] = 'Bienvenido Escribano'; if($this->input->post() && !$exito ){ //seteo los demas input segun lo que ingreso anteriormente $data['circunscripcion'] = $this->input->post('circunscripcion'); $data['seccion']=$this->input->post('seccion'); $data['chacra'] = $this->input->post('chacra'); $data['quinta'] = $this->input->post('quinta'); $data['fraccion'] = $this->input->post('fraccion'); $data['manzana'] =$this->input->post('manzana'); $data['parcela'] = $this->input->post('parcela'); $data['partida'] = $this->input->post('partida'); $data['planoAprobado'] = $this->input->post('planoAprobado'); $data['fechaPlanoAprobado'] = $this->input->post('fechaPlanoAprobado'); $data['tipoPropiedad'] = $this->input->post('tipoPropiedad'); $data['tomo'] = $this->input->post('tomo'); $data['folio'] = $this->input->post('folio'); $data['finca'] = $this->input->post('finca'); $data['año'] = $this->input->post('año'); $data['localidades'] = $this->input->post('localidades'); $data['departamentos'] = $this->M_escribano->getNombreDepartamento($this->input->post('departamentos')); $data['descripcion'] = $this->input->post('descripcion'); $data['nroMatriculaRPI'] = $this->input->post('nroMatriculaRPI'); $data['fechaMatriculaRPI'] = $this->input->post('fechaMatriculaRPI'); $data['superficie'] = $this->input->post('superficie'); }else{ $parcela=$this->db->get_where('parcela', array('idParcela'=>$idParcela))->row(); $data['circunscripcion']=$parcela->circunscripcion; $data['seccion']=$parcela->seccion; $data['chacra']=$parcela->chacra; $data{'quinta'}=$parcela->quinta; $data{'fraccion'}=$parcela->fraccion; $data{'manzana'}=$parcela->manzana; $data{'parcela'}=$parcela->parcela; $data{'partida'}=$parcela->partida; $data{'planoAprobado'}=$parcela->planoAprobado; $date=new DateTime($parcela->fechaPlanoAprobado); $fecha_planoAprobado=$date->format('d/m/Y '); $data{'fechaPlanoAprobado'}=$fecha_planoAprobado; $data{'tipoPropiedad'}=$parcela->tipoPropiedad; $data{'tomo'}=$parcela->tomo; $data{'folio'}=$parcela->folio; $data{'finca'}=$parcela->finca; $data{'año'}=$parcela->año; $data{'localidades'}=$parcela->idLocalidad; $localidad=$this->db->get_where('localidad', array('idLocalidad'=>$parcela->idLocalidad))->row(); $data{'departamentos'}=$localidad->idDepartamento;; $data{'descripcion'}=$parcela->descripcion; $data{'nroMatriculaRPI'}=$parcela->nroMatriculaRPI; $date=new DateTime($parcela->fechaMatriculaRPI); $fecha_matriculaRPI=$date->format('d/m/Y '); $data{'fechaMatriculaRPI'}=$fecha_matriculaRPI; $data['superficie'] =$parcela->superficie; $data['localidadPost']=$parcela->idLocalidad; $this->session->set_userdata('idParcelaEditar',$idParcela); } $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/editarParcela',$data); $this->load->view('templates/pie',$data); } public function modificarParcela() { $idParcela=$this->session->userdata('idParcelaEditar'); $hizo_post=TRUE; $this->load->helper(array('form', 'url')); //set_reules(nombre del campo, mensaje a mostrar, reglas de validacion) $this->form_validation->set_rules('circunscripcion', 'circunscripcion', 'required',array('required' => 'Debes ingresar una circunscripcion ') ); $this->form_validation->set_rules('seccion', 'seccion', 'required',array('required' => 'Debes ingresar una sección ') ); $this->form_validation->set_rules('superficie', 'superficie', 'required',array('required' => 'Debes seleccionar una superficie') ); $this->form_validation->set_rules('partida', 'partida', 'required',array('required' => 'Debes ingresar una partida ') ); $this->form_validation->set_rules('planoAprobado', 'planoAprobado', 'required',array('required' => 'Debes ingresar un plano aprobado','is_unique'=>'Ya existe un escribano con el nombre de usuario ingresado') ); $this->form_validation->set_rules('fechaPlanoAprobado', 'fechaPlanoAprobado', 'required',array('required' => 'Debes ingresar una fecha ') ); $this->form_validation->set_rules('tipoPropiedad', 'tipoPropiedad','required|callback_check_propiedad'); $this->form_validation->set_message('check_propiedad', 'Debes seleccionar una Propiedad'); $this->form_validation->set_rules('tomo', 'tomo', 'required',array('required' => 'Debes ingresar un tomo') ); $this->form_validation->set_rules('folio', 'folio', 'required',array('required' => 'Debes ingresar un folio ') ); $this->form_validation->set_rules('finca', 'finca', 'required',array('required' => 'Debes ingresar una finca ') ); $this->form_validation->set_rules('año', 'año', 'required',array('required' => 'Debes ingresar un año ') ); $this->form_validation->set_rules('departamentos','departamentos','required|callback_check_departamento'); $this->form_validation->set_message('check_departamento', 'Debes seleccionar un departamento'); $this->form_validation->set_rules('localidades','localidades','required|callback_check_localidad'); $this->form_validation->set_message('check_localidad', 'Debes seleccionar una localidad'); $this->form_validation->set_rules('descripcion', 'descripcion', 'required',array('required' => 'Debes ingresar una descripcion ') ); $this->form_validation->set_rules('nroMatriculaRPI', 'matricualRpi', 'required',array('required' => 'Debes ingresar una matricula ') ); $this->form_validation->set_rules('fechaMatriculaRPI', 'fechaMatriculaRPI', 'required',array('required' => 'Debes ingresar una fecha ') ); if($this->form_validation->run() == FALSE) { $this->editarParcela($idParcela,FALSE,TRUE, FALSE); }else{ $date1=str_replace('/','-',$this->input->post('fechaMatriculaRPI')); $date1=new DateTime($date1); $fechaMatriculaRPI=$date1->format('Y-m-d '); $date2=str_replace('/','-',$this->input->post('fechaPlanoAprobado')); $date2=new DateTime($date2); $fechaPlanoAprobado=$date2->format('Y-m-d '); $datos_parcela= array ( 'circunscripcion' => $this->input->post('circunscripcion'), 'seccion' => $this->input->post('seccion'), 'chacra' => $this->input->post('chacra'), 'quinta' => $this->input->post('quinta'), 'fraccion' => $this->input->post('fraccion'), 'manzana' => $this->input->post('manzana'), 'parcela' => $this->input->post('parcela'), 'superficie' => $this->input->post('superficie'), 'partida' =>$this->input->post('partida'), 'tipoPropiedad' => $this->input->post('tipoPropiedad'), 'planoAprobado' => $this->input->post('planoAprobado'), 'fechaPlanoAprobado' => $fechaPlanoAprobado, 'descripcion' => $this->input->post('descripcion'), 'idMinuta' => $this->session->userdata('idMinutaEditar'), 'nroMatriculaRPI' => $this->input->post('nroMatriculaRPI'), 'fechaMatriculaRPI' => $fechaMatriculaRPI, 'idLocalidad' => $this->input->post('localidades'), 'tomo' => $this->input->post('tomo'), 'folio' => $this->input->post('folio'), 'finca' => $this->input->post('finca'), 'año' => $this->input->post('año'), ); $this->db->where('idParcela', $idParcela); $this->db->update('parcela', $datos_parcela); $this->editarMinuta($this->session->userdata('idMinutaEditar')); } } public function editarPH($idRelacion,$exito=FALSE, $hizo_post=FALSE){ if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } /*Variables para evitar que inserte una minuta y parcela cuando quiere agregar otro ph*/ $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $data['exito']= $exito; $data['hizo_post']=$hizo_post; if($this->input->post() && !$exito){ //seteo los demas input segun lo que ingreso anteriormente $data['ph'] = $this->input->post('ph'); $data['fecha_escritura'] = $this->input->post('fecha_escritura'); $data['nro_ucuf'] = $this->input->post('nro_ucuf'); $data['tipo_ucuf'] = $this->input->post('tipo_ucuf'); $data['plano_aprobado'] = $this->input->post('plano_aprobado'); $data['fecha_plano_aprobado'] =$this->input->post('fecha_plano_aprobado'); $data['porcentaje_ucuf'] = $this->input->post('porcentaje_ucuf'); $data['poligonos'] = $this->input->post('poligonos'); }else{ $relacion=$this->db->get_where('relacion', array('idRelacion'=>$idRelacion))->row(); if($relacion->poligonos==null){ $data['ph']='noph'; $fechaPlanoAprobado=''; }else { $data['ph']='ph'; $date=new DateTime($relacion->fechaPlanoAprobado); $fechaPlanoAprobado=$date->format('d/m/Y '); }; $date=new DateTime($relacion->fechaEscritura); $fechaEscritura=$date->format('d/m/Y '); $data['fecha_escritura']=$fechaEscritura; $data['nro_ucuf']= $relacion->nroUfUc; $data['tipo_ucuf']=$relacion->tipoUfUc; $data['plano_aprobado']= $relacion->planoAprobado; $data['fecha_plano_aprobado']= $fechaPlanoAprobado; $data['porcentaje_ucuf']= $relacion->porcentajeUfUc; $data['poligonos']=$relacion->poligonos; $this->session->set_userdata('idParcelaEditar',$relacion->idParcela); $this->session->set_userdata('idRelacionEditar',$relacion->idRelacion); } $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/editarRelacion',$data); $this->load->view('templates/pie',$data); } public function modificarPH(){ $idRelacion=$this->session->userdata('idRelacionEditar'); $hizo_post=TRUE; $this->load->helper(array('form', 'url')); //set_reules(nombre del campo, mensaje a mostrar, reglas de validacion) $this->form_validation->set_rules('fecha_escritura', 'fecha_escritura', 'required',array('required' => 'Debes ingresar una fecha de escritura') ); if($this->form_validation->run() == FALSE) { $this->editarPH(FALSE,TRUE); } else{ $date1=str_replace('/','-',$this->input->post('fecha_escritura')); $date1=new DateTime($date1); $fechaEscritura=$date1->format('Y-m-d '); $date2=str_replace('/','-',$this->input->post('fecha_plano_aprobado')); $date2=new DateTime($date2); $fechaPlanoAprobado=$date2->format('Y-m-d '); $datos_ph= array ( 'fechaEscritura' => $fechaEscritura, 'nroUfUc' => $this->input->post('nro_ucuf'), 'tipoUfUc' => $this->input->post('tipo_ucuf'), 'planoAprobado' => $this->input->post('plano_aprobado'), 'fechaPlanoAprobado' => $fechaPlanoAprobado, 'porcentajeUfUc' => $this->input->post('porcentaje_ucuf'), 'poligonos' => $this->input->post('poligonos'), ); $this->db->where('idRelacion', $idRelacion); $this->db->update('relacion', $datos_ph); $this->editarMinuta($this->session->userdata('idMinutaEditar')); } } public function editarPropietario($idPropietario,$exito=FALSE, $hizo_post=FALSE) { if($this->session->userdata('perfil') == FALSE || $this->session->userdata('perfil') != 'escribano') { redirect(base_url().'index.php/c_login_escribano'); } $data["notificaciones_ma"]=$this->notificaciones_ma(); $data["notificaciones_mr"]=$this->notificaciones_mr(); $data["notificaciones_si"]=$this->notificaciones_si(); $data['arraydepartamentos'] = $this->M_escribano->getDepartamentos(); $data["personas"] = $this->M_escribano->getPersonas(); $data['exito']= $exito; $data['hizo_post']=$hizo_post; $data['titulo'] = 'Bienvenido Escribano'; if($this->input->post() && !$exito){ //seteo los demas input segun lo que ingreso anteriormente $data['propietario'] = $this->input->post('propietario'); $data['porcentaje_condominio'] = $this->input->post('porcentaje_condominio'); $data['tipo_propietario'] = $this->input->post('tipo_propietario'); $data['empresa'] = $this->input->post('empresa'); $data['nombreyapellido'] = $this->input->post('nombreyapellido'); $data['sexo_combobox']=$this->input->post('sexo_combobox'); $data['dni']=$this->input->post('dni'); $data['cuit'] = $this->input->post('cuit'); $data['cuil'] = $this->input->post('cuil'); $data['conyuge'] = $this->input->post('conyuge'); $data['fecha_nacimiento'] = $this->input->post('fecha_nacimiento'); $data['direccion'] =$this->input->post('direccion'); $data['departamentos'] = $this->input->post('departamentos'); $data['localidades'] = $this->input->post('localidades'); }else{ $propietario=$this->db->get_where('propietario', array('id'=>$idPropietario))->row(); $persona=$this->db->get_where('persona', array('idPersona'=>$propietario->idPersona))->row(); $data['propietario']=$persona->empresa; $data['tipo_propietario']=$propietario->tipoPropietario; $data['porcentaje_condominio']=$propietario->porcentajeCondominio; $data['nombreyapellido']=$persona->apynom; $data['sexo_combobox']=''; $data['dni']=$persona->dni; if ( $data['propietario']=$persona->empresa=='O') { $data['cuit']=$persona->cuitCuil; $data['cuil']=''; }else{ $data['cuil']=$persona->cuitCuil; $data['cuit']='';} $data['conyuge']=$persona->conyuge; $date=new DateTime($persona->fechaNac); $fechaNac=$date->format('d/m/Y '); $data['fecha_nacimiento']=$fechaNac; $data['direccion']=$persona->direccion; $localidad=$this->db->get_where('localidad', array('idLocalidad'=>$persona->idLocalidad))->row(); $data['departamentos']= $localidad->idDepartamento; $data['localidades']=$persona->idLocalidad; $this->session->set_userdata('idPropietarioEditar',$propietario->id); $this->session->set_userdata('idPersonaEditar',$persona->idPersona); } $this->load->view('templates/cabecera_escribano',$data); $this->load->view('templates/escri_menu',$data); $this->load->view('escribano/editarPropietario',$data); $this->load->view('templates/pie',$data); } public function modificarPropietario(){ $idPropietario=$this->session->userdata('idPropietarioEditar'); $idPersona=$this->session->userdata('idPersonaEditar'); $hizo_post=TRUE; $this->load->helper(array('form', 'url')); //set_reules(nombre del campo, mensaje a mostrar, reglas de validacion) if($this->input->post('propietario')=='P'){ $this->form_validation->set_rules('porcentaje_condominio', 'porcentaje_condominio', 'required',array('required' => 'Debes ingresar porcentaje de codominio') ); $this->form_validation->set_rules('nombreyapellido', 'nombreyapellido', 'required',array('required' => 'Debes ingresar una fecha de escritura') ); $this->form_validation->set_rules('tipo_propietario', 'tipo_propietario', 'required') ; $this->form_validation->set_rules('sexo_combobox', 'sexo_combobox', 'required',array('required' => 'Debes seleccionar tipo de sexo ') ); $this->form_validation->set_rules('dni', 'dni','required',array('required' => 'Debes ingresar un dni ') ); $this->form_validation->set_rules('departamentos','departamentos','required|callback_check_departamento'); $this->form_validation->set_message('check_departamento', 'Debes seleccionar un departamento'); $this->form_validation->set_rules('localidades','localidades','required|callback_check_localidad'); $this->form_validation->set_message('check_localidad', 'Debes seleccionar una localidad'); } else{ $this->form_validation->set_rules('porcentaje_condominio', 'porcentaje_condominio', 'required',array('required' => 'Debes ingresar porcentaje de codominio') ); $this->form_validation->set_rules('tipo_propietario', 'tipo_propietario', 'required'); $this->form_validation->set_rules('nombreyapellido', 'nombreyapellido', 'required',array('required' => 'Debes ingresar un nombre y apellido') ); $this->form_validation->set_rules('cuit', 'cuit', 'required',array('required' => 'Debes ingresar un cuit ') ); $this->form_validation->set_rules('departamentos','departamentos','required|callback_check_departamento'); $this->form_validation->set_message('check_departamento', 'Debes seleccionar un departamento'); $this->form_validation->set_rules('localidades','localidades','required|callback_check_localidad'); $this->form_validation->set_message('check_localidad', 'Debes seleccionar una localidad'); } if($this->form_validation->run() == FALSE) { $this->editarPropietario($idPropietario,FALSE,TRUE); } else{ $date2=str_replace('/','-',$this->input->post('fecha_nacimiento')); $date2=new DateTime($date2); $fecha_nacimiento=$date2->format('Y-m-d '); $datos_propietario= array ( 'tipoPropietario' => $this->input->post('tipo_propietario'), 'porcentajeCondominio' => $this->input->post('porcentaje_condominio'), ); $datos_persona=array( 'empresa' => $this->input->post('propietario'), 'apynom' => $this->input->post('nombreyapellido'), 'dni' => $this->input->post('dni'), 'cuitCuil' => $this->input->post('cuit'), 'direccion' => $this->input->post('direccion'), 'conyuge' => $this->input->post('conyuge'), 'fechaNac' => $fecha_nacimiento, 'idLocalidad' => $this->input->post('localidades'), ); $this->db->where('id', $idPropietario); $this->db->update('propietario', $datos_propietario); $this->db->where('idPersona', $idPersona); $this->db->update('persona', $datos_persona); } $this->editarMinuta($this->session->userdata('idMinutaEditar')); } public function finalizarEdicion(){ $idMinuta=$_POST['idMinuta']; $datetime_variable = new DateTime(); $datetime_formatted = date_format($datetime_variable, 'Y-m-d H:i:s'); $data = array( 'idMinuta' => $idMinuta , 'estadoMinuta' => 'P' , 'fechaEstado'=>$datetime_formatted , ); $this->db->insert('estadominuta', $data); $this->verMinutas(); } public function nuevaParcela(){ $this->session->unset_userdata('datos_parcela'); $this->session->unset_userdata('datos_ph'); $this->session->unset_userdata('propietario'); $this->session->set_userdata('idMinuta',$this->session->userdata('idMinutaEditar')); $this->session->set_userdata('editandoMinuta','s'); $this->crearParcela(FALSE, TRUE, TRUE,TRUE); } public function nuevoPH($idParcela){ $parcela=$this->db->get_where('parcela ', array('idParcela'=>$idParcela))->row(); $datos_parcela= array ( 'fechaPlanoAprobado' =>$parcela->fechaPlanoAprobado, 'fechaMatriculaRPI' =>$parcela->fechaMatriculaRPI, 'circunscripcion' => $parcela->circunscripcion, 'seccion' => $parcela->seccion, 'chacra' => $parcela->chacra, 'quinta' => $parcela->quinta, 'fraccion' => $parcela->fraccion, 'manzana' => $parcela->manzana, 'parcela' => $parcela->parcela, 'superficie' => $parcela->superficie, 'partida' =>$parcela->partida, 'tipoPropiedad' => $parcela->tipoPropiedad, 'planoAprobado' => $parcela->planoAprobado, 'descripcion' => $parcela->descripcion, 'nroMatriculaRPI' => $parcela->nroMatriculaRPI, 'localidades' => $parcela->idLocalidad, 'tomo' =>$parcela->tomo, 'folio' =>$parcela->folio, 'finca' =>$parcela->finca, 'año' => $parcela->año, ); $this->session->set_userdata($datos_parcela); $this->session->unset_userdata('datos_ph'); $this->session->unset_userdata('propietario'); $this->session->set_userdata('idParcela',$idParcela); $this->session->set_userdata('editandoMinuta','s'); $this->crearRelacion(FALSE, TRUE, TRUE); } public function nuevoPropietario($idRelacion){ $this->session->set_userdata('idMinuta',$this->session->userdata('idMinutaEditar')); $relacion=$this->db->get_where('relacion', array('idRelacion'=>$idRelacion))->row(); $idParcela=$relacion->idParcela; $parcela=$this->db->get_where('parcela', array('idParcela'=>$idParcela))->row(); $datos_parcela= array ( 'fechaPlanoAprobado' =>$parcela->fechaPlanoAprobado, 'fechaMatriculaRPI' =>$parcela->fechaMatriculaRPI, 'circunscripcion' => $parcela->circunscripcion, 'seccion' => $parcela->seccion, 'chacra' => $parcela->chacra, 'quinta' => $parcela->quinta, 'fraccion' => $parcela->fraccion, 'manzana' => $parcela->manzana, 'parcela' => $parcela->parcela, 'superficie' => $parcela->superficie, 'partida' =>$parcela->partida, 'tipoPropiedad' => $parcela->tipoPropiedad, 'planoAprobado' => $parcela->planoAprobado, 'descripcion' => $parcela->descripcion, 'nroMatriculaRPI' => $parcela->nroMatriculaRPI, 'localidades' => $parcela->idLocalidad, 'tomo' =>$parcela->tomo, 'folio' =>$parcela->folio, 'finca' =>$parcela->finca, 'año' => $parcela->año, ); $this->session->set_userdata($datos_parcela); $datos_ph= array ( 'fecha_escritura' => $relacion->fechaEscritura, 'nro_ucuf' => $relacion->nroUfUc, 'tipo_ucuf' => $relacion->tipoUfUc, 'plano_aprobado' => $relacion->planoAprobado, 'porcentaje_ucuf' => $relacion->porcentajeUfUc, 'poligonos' => $relacion->poligonos, ); $this->session->set_userdata($datos_ph); $this->session->unset_userdata('propietario'); $this->session->set_userdata('editandoMinuta','s'); $this->crearPropietario(FALSE, TRUE, TRUE); } public function eliminarPH(){ $idRelacion=$_POST['idRelacion']; $this->db->delete('propietario', array('idRelacion' => $idRelacion)); $this->db->delete('relacion', array('idRelacion' => $idRelacion)); $this->editarMinuta($this->session->userdata('idMinutaEditar')); } public function eliminarParcela(){ $idParcela=$_POST['idParcela']; $relaciones=$this->db->get_where('relacion ', array('idParcela'=>$idParcela))->result(); foreach ($relaciones as $r) { $this->db->delete('propietario', array('idRelacion' => $r->idRelacion)); } $this->db->delete('relacion', array('idParcela' => $idParcela)); $this->db->delete('parcela', array('idParcela' => $idParcela)); $this->editarMinuta($this->session->userdata('idMinutaEditar')); } public function eliminarPropietario(){ $idPropietario=$_POST['idPropietario']; $this->db->delete('propietario', array('id' => $idPropietario)); $this->editarMinuta($this->session->userdata('idMinutaEditar')); } }
marcespinoza/proyecto
application/controllers/C_escribano.php
PHP
mit
66,704
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.Its.Recipes; using Newtonsoft.Json.Linq; using Vipr.Core.CodeModel; using Vipr.Core.CodeModel.Vocabularies.Capabilities; using Vipr.Writer.CSharp.Lite; namespace CSharpLiteWriterUnitTests { public static class OdcmTestExtensions { public static IEnumerable<OdcmProperty> GetProperties(this OdcmModel model) { return model.Namespaces.SelectMany(n => n.Classes.SelectMany(c => c.Properties)); } public static IEnumerable<Tuple<string, object>> GetSampleKeyArguments(this OdcmEntityClass entityClass) { return entityClass.Key.Select(p => new Tuple<string, object>(p.Name, Any.CSharpIdentifier(1))); } public static JObject GetSampleJObject(this OdcmEntityClass entityClass, bool dontSalt = false) { return entityClass.GetSampleJObject(entityClass.GetSampleKeyArguments(), dontSalt); } public static JObject GetSampleJObject(this OdcmEntityClass entityClass, IEnumerable<Tuple<string, object>> keyArguments, bool dontSalt = false) { var retVal = new JObject(); foreach (var keyArgument in keyArguments) { retVal.Add(keyArgument.Item1, new JValue(keyArgument.Item2)); } foreach (var collectionProperty in entityClass.Properties.Where(p => p.IsCollection)) { retVal.Add(collectionProperty.Name, new JArray()); } if (!dontSalt) { retVal.Add(Any.Word(), new JValue(Any.Int())); } return retVal; } public static IEnumerable<Tuple<string, object>> GetSampleArguments(this OdcmMethod method) { return method.Parameters.Select(p => new Tuple<string, object>(p.Name, Any.Paragraph(5))); } public static OdcmProperty Rename(this OdcmProperty originalProperty, string newName) { var index = originalProperty.Class.Properties.IndexOf(originalProperty); originalProperty.Class.Properties[index] = new OdcmProperty(newName) { Class = originalProperty.Class, ReadOnly = originalProperty.ReadOnly, Projection = originalProperty.Type.DefaultProjection, ContainsTarget = originalProperty.ContainsTarget, IsCollection = originalProperty.IsCollection, IsLink = originalProperty.IsLink, IsNullable = originalProperty.IsNullable, IsRequired = originalProperty.IsRequired }; if (originalProperty.Class is OdcmEntityClass && ((OdcmEntityClass)originalProperty.Class).Key.Contains(originalProperty)) { var keyIndex = ((OdcmEntityClass)originalProperty.Class).Key.IndexOf(originalProperty); ((OdcmEntityClass)originalProperty.Class).Key[keyIndex] = originalProperty.Class.Properties[index]; } return originalProperty.Class.Properties[index]; } public static string GetDefaultEntitySetName(this OdcmEntityClass odcmClass) { return odcmClass.Name + "s"; } public static string GetDefaultEntitySetPath(this OdcmEntityClass odcmClass) { return "/" + odcmClass.GetDefaultEntitySetName(); } public static string GetDefaultSingletonName(this OdcmEntityClass odcmClass) { return odcmClass.Name; } public static string GetDefaultSingletonPath(this OdcmEntityClass odcmClass) { return "/" + odcmClass.GetDefaultSingletonName(); } public static string GetDefaultEntityPath(this OdcmEntityClass odcmClass, IEnumerable<Tuple<string, object>> keyValues = null) { keyValues = keyValues ?? odcmClass.GetSampleKeyArguments().ToArray(); return string.Format("{0}({1})", odcmClass.GetDefaultEntitySetPath(), ODataKeyPredicate.AsString(keyValues.ToArray())); } public static string GetDefaultEntityPropertyPath(this OdcmEntityClass odcmClass, OdcmProperty property, IEnumerable<Tuple<string, object>> keyValues = null) { return odcmClass.GetDefaultEntityPropertyPath(property.Name, keyValues); } public static string GetDefaultEntityPropertyPath(this OdcmEntityClass odcmClass, string propertyName, IEnumerable<Tuple<string, object>> keyValues = null) { return string.Format("{0}/{1}", odcmClass.GetDefaultEntityPath(keyValues), propertyName); } public static string GetDefaultEntityMethodPath(this OdcmEntityClass odcmClass, IEnumerable<Tuple<string, object>> keyValues, string propertyName) { return string.Format("{0}/{1}", odcmClass.GetDefaultEntityPath(keyValues), propertyName); } public static EntityArtifacts GetArtifactsFrom(this OdcmEntityClass Class, Assembly Proxy) { var retVal = new EntityArtifacts { Class = Class, ConcreteType = Proxy.GetClass(Class.Namespace, Class.Name), ConcreteInterface = Proxy.GetInterface(Class.Namespace, "I" + Class.Name), FetcherType = Proxy.GetClass(Class.Namespace, Class.Name + "Fetcher"), FetcherInterface = Proxy.GetInterface(Class.Namespace, "I" + Class.Name + "Fetcher"), CollectionType = Proxy.GetClass(Class.Namespace, Class.Name + "Collection"), CollectionInterface = Proxy.GetInterface(Class.Namespace, "I" + Class.Name + "Collection") }; return retVal; } public static OdcmProjection AnyOdcmProjection(this OdcmType odcmType) { var projection = new OdcmProjection { Type = odcmType, Capabilities = new List<OdcmCapability>() }; var capabilityTerms = OdcmProjection .WellKnowCapabilityTerms .Distinct(); foreach (var term in capabilityTerms) { projection.Capabilities.Add(new OdcmBooleanCapability(Any.Bool(), term)); } return projection; } public static IEnumerable<OdcmProjection> AnyOdcmProjections(this OdcmType odcmType, int count = 5) { for (int i = 0; i < count; i++) { yield return odcmType.AnyOdcmProjection(); } } } }
v-am/Vipr
test/CSharpLiteWriterUnitTests/OdcmTestExtensions.cs
C#
mit
6,764
$(document).ready(function() { CKEDITOR.replace("sl_content", { fullPage: true, allowedContent: true, filebrowserUploadUrl: '/ckeditor/upload' }); $(".poll_delete").click(function(){ if($("#poll_title li").length<=2) { alert('항목은 최소 두개는 입력되어야 합니다.') return false; } $(this).parent().remove(); }); $("#poll_add").click(function(){ $("#poll_title").append($("#poll_title li:last").clone(true)); }); });
sleeping-lion/slboard_codeigniter
public/js/boards/add.js
JavaScript
mit
481
// Copyright (c) Rotorz Limited. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root. "use strict";
webreed/webreed
test/fakes/plugins/fake-plugin-without-setup.js
JavaScript
mit
142
<?php /** * Phossa Project * * PHP version 5.4 * * @category Library * @package Phossa\Query * @author Hong Zhang <phossa@126.com> * @copyright 2015 phossa.com * @license http://mit-license.org/ MIT License * @link http://www.phossa.com/ */ /*# declare(strict_types=1); */ namespace Phossa\Query\Clause; /** * AliasTrait * * @package Phossa\Query * @author Hong Zhang <phossa@126.com> * @see AliasInterface * @version 1.0.0 * @since 1.0.0 added */ trait AliasTrait { /** * subquery alias * * @var string * @access protected */ protected $alias; /** * {@inheritDoc} */ public function alias(/*# string */ $alias) { $this->alias = $alias; return $this; } /** * {@inheritDoc} */ public function hasAlias()/*#: bool */ { return null !== $this->alias; } /** * {@inheritDoc} */ public function getAlias()/*#: string */ { // auto generate a random one if (!$this->hasAlias()) { $this->alias = substr(md5(microtime(true)),0,3); } return $this->alias; } }
phossa/phossa-query
src/Phossa/Query/Clause/AliasTrait.php
PHP
mit
1,173
'use strict'; var path = require('path'); var test = require('ava'); var assert = require('yeoman-assert'); var helpers = require('yeoman-test'); test.before(() => { return helpers.run(path.join(__dirname, '../../generators/gulp')) .withOptions({ 'skip-install': true, 'uploading': 'None' }) .toPromise(); }); test('creates html.js', () => { assert.file('gulp/tasks/html.js'); }); test('contains correct tasks', () => { assert.fileContent('gulp/tasks/html.js', 'gulp.task(\'html'); });
sondr3/generator-statisk
test/gulp/html.js
JavaScript
mit
519
// // Created by Alexandre Sejournant on 09/06/2016. // #ifndef DUNJONEER_OBJECT_HPP #define DUNJONEER_OBJECT_HPP #include <IEntity.hpp> #include <Settings.hpp> class Object : public IEntity { private: Object(); //Illegal call protected: //SETTINGS Settings *_config; //ID stuff std::string _type; std::string _name; //IRRLICHT UTILITIES t_irrDevice *_device; t_sManager *_sceneManager; //POSITION SYSTEM t_vec3df _positionVector; t_vec3df _accelerationVector; float _movementSpeed; //OBJECT CLASS REQUIREMENTS t_mesh *_standingAnimation; t_node *_standingAnimationNode; t_mesh *_walkingAnimation; t_node *_walkingAnimationNode; t_node *_node; public: Object(t_irrDevice *newDevice, Settings *config); virtual ~Object(); /////////// //SETTERS//////////////////////////////////////////////////////////////////////////// virtual void setPos ( const t_vec3df &newPos );//DEFAULT// virtual void setAcc ( const t_vec3df &newAcc );//DEFAULT// virtual void setSpeed ( const float &newSpeed );//DEFAULT// virtual void setName ( const std::string &newName );//DEFAULT// virtual void setCurrentNode ( const std::string &nodeName );//DEFAULT// ///////////////////////////////////////////////////////////////////////////////////// /////////// //GETTERS//////////////////////////////////////////////////// virtual t_vec3df const &getPos () const;//DEFAULT// virtual t_vec3df const &getAcc () const;//DEFAULT// virtual float const &getSpeed () const;//DEFAULT// virtual std::string const &getType () const;//DEFAULT// virtual std::string const &getName () const;//DEFAULT// ///////////////////////////////////////////////////////////// ////////// //SYSTEM//////////////////////////////////////////////////////////////////////// virtual void updatePosition ( );//SYSTEM// virtual void loadStandingMesh (const std::string &fileName );//SYSTEM// //////////////////////////////////////////////////////////////////////////////// }; #endif //DUNJONEER_OBJECT_HPP
sejour-a/dunjoneer
headers/Object.hpp
C++
mit
2,449
namespace BingRestServices.Traffic { public class Severity : KeyType { public static readonly Severity LowImpact = Create<Severity>("1"); public static readonly Severity Minor = Create<Severity>("2"); public static readonly Severity Moderate = Create<Severity>("3"); public static readonly Severity Serious = Create<Severity>("4"); } }
ivanovvitaly/BingRestServices.Net
BingRestServices/Traffic/Severity.cs
C#
mit
379
<?php class ConfBase extends Conf { function getHost () { return $this->databaseHost; } function getPort () { return $this->databasePort; } function getName () { return $this->databaseName; } function getUser () { return $this->databaseUser; } function getPassword () { return $this->databasePassword; } function getSecretKey () { return $this->databaseSecretKey; } function getDebug () { return $this->debug; } }
w-jerome/focus
app/config/config.php
PHP
mit
452
function scrollDistanceFromBottom() { return pageHeight() - (window.pageYOffset + self.innerHeight); } function pageHeight() { return $("body").height(); }
bloopletech/pictures
public/javascripts/application.js
JavaScript
mit
160
package db_test import ( "reflect" "sync" "testing" "time" "github.com/OpenBazaar/openbazaar-go/repo" "github.com/OpenBazaar/openbazaar-go/repo/db" "github.com/OpenBazaar/openbazaar-go/schema" ) func newNotificationStore() (repo.NotificationStore, func(), error) { appSchema := schema.MustNewCustomSchemaManager(schema.SchemaContext{ DataPath: schema.GenerateTempPath(), TestModeEnabled: true, }) if err := appSchema.BuildSchemaDirectories(); err != nil { return nil, nil, err } if err := appSchema.InitializeDatabase(); err != nil { return nil, nil, err } database, err := appSchema.OpenDatabase() if err != nil { return nil, nil, err } return db.NewNotificationStore(database, new(sync.Mutex)), appSchema.DestroySchemaDirectories, nil } func TestNotficationsDB_PutRecord(t *testing.T) { var ( db, teardown, err = newNotificationStore() // now as Unix() quantizes time to DB's resolution which makes reflect.DeepEqual pass below now = time.Unix(time.Now().UTC().Unix(), 0) putRecordExamples = []*repo.Notification{ repo.NewNotification(repo.OrderCancelNotification{ ID: "orderCancelNotif", Type: repo.NotifierTypeOrderCancelNotification, OrderId: "orderCancelReferenceOrderID", }, now, true), repo.NewNotification(repo.ModeratorDisputeExpiry{ ID: "disputeAgingNotif", Type: repo.NotifierTypeModeratorDisputeExpiry, CaseID: "disputAgingReferenceCaseID", }, now, false), repo.NewNotification(repo.BuyerDisputeTimeout{ ID: "purchaseAgingNotif", Type: repo.NotifierTypeBuyerDisputeTimeout, OrderID: "purchaseAgingReferenceOrderID", }, now, true), } ) if err != nil { t.Fatal(err) } defer teardown() for _, subject := range putRecordExamples { if err := db.PutRecord(subject); err != nil { t.Fatal(err) } allNotifications, _, err := db.GetAll("", -1, []string{}) if err != nil { t.Fatal(err) } foundNotification := false for _, actual := range allNotifications { if actual.ID != subject.ID { t.Logf("Actual notification ID (%s) did not match subject, continuing...", actual.ID) continue } foundNotification = true if actual.GetType() != subject.GetType() { t.Error("Expected found notification to match types") t.Errorf("Expected: %s", subject.GetType()) t.Errorf("Actual: %s", actual.GetType()) } if !reflect.DeepEqual(subject, actual) { t.Error("Expected found notification to equal each other") t.Errorf("Expected: %+v\n", subject) t.Errorf("Actual: %+v\n", actual) } } if !foundNotification { t.Errorf("Expected to find notification, but was not found\nExpected type: (%s) Expected ID: (%s)", subject.GetType(), subject.GetID()) t.Errorf("Found records: %+v", allNotifications) } } } func TestNotficationsDB_Delete(t *testing.T) { db, teardown, err := newNotificationStore() if err != nil { t.Fatal(err) } defer teardown() n := repo.FollowNotification{"1", repo.NotifierTypeFollowNotification, "abc"} err = db.PutRecord(repo.NewNotification(n, time.Now(), false)) if err != nil { t.Error(err) } err = db.Delete("1") if err != nil { t.Error(err) } stmt, err := db.PrepareQuery("select notifID from notifications where notifID='1'") if err != nil { t.Error(err) } defer stmt.Close() var notifId int err = stmt.QueryRow().Scan(&notifId) if err == nil { t.Error("Delete failed") } } func TestNotficationsDB_GetAll(t *testing.T) { db, teardown, err := newNotificationStore() if err != nil { t.Fatal(err) } defer teardown() f := repo.FollowNotification{"1", repo.NotifierTypeFollowNotification, "abc"} err = db.PutRecord(repo.NewNotification(f, time.Now(), false)) if err != nil { t.Error(err) } u := repo.UnfollowNotification{"2", repo.NotifierTypeUnfollowNotification, "123"} err = db.PutRecord(repo.NewNotification(u, time.Now().Add(time.Second), false)) if err != nil { t.Error(err) } u = repo.UnfollowNotification{"3", repo.NotifierTypeUnfollowNotification, "56778"} err = db.PutRecord(repo.NewNotification(u, time.Now().Add(time.Second*2), false)) if err != nil { t.Error(err) } notifs, _, err := db.GetAll("", -1, []string{}) if err != nil { t.Error(err) } if len(notifs) != 3 { t.Error("Returned incorrect number of messages") return } limtedMessages, _, err := db.GetAll("", 2, []string{}) if err != nil { t.Error(err) } if len(limtedMessages) != 2 { t.Error("Returned incorrect number of messages") return } offsetMessages, _, err := db.GetAll("3", -1, []string{}) if err != nil { t.Error(err) } if len(offsetMessages) != 2 { t.Errorf("Returned incorrect number of messages %d", len(offsetMessages)) return } filteredMessages, _, err := db.GetAll("", -1, []string{"unfollow"}) if err != nil { t.Error(err) } if len(filteredMessages) != 2 { t.Errorf("Returned incorrect number of messages %d", len(filteredMessages)) return } } func TestNotficationsDB_MarkAsRead(t *testing.T) { db, teardown, err := newNotificationStore() if err != nil { t.Fatal(err) } defer teardown() n := repo.FollowNotification{"5", repo.NotifierTypeFollowNotification, "abc"} err = db.PutRecord(repo.NewNotification(n, time.Now(), false)) if err != nil { t.Error(err) } err = db.MarkAsRead("5") if err != nil { t.Error(err) } stmt, err := db.PrepareQuery("select read from notifications where notifID='5'") if err != nil { t.Error(err) } defer stmt.Close() var read int err = stmt.QueryRow().Scan(&read) if err != nil { t.Error(err) } if read != 1 { t.Error("Failed to mark message as read") } } func TestNotficationsDB_MarkAllAsRead(t *testing.T) { db, teardown, err := newNotificationStore() if err != nil { t.Fatal(err) } defer teardown() n := repo.FollowNotification{"6", repo.NotifierTypeFollowNotification, "abc"} err = db.PutRecord(repo.NewNotification(n, time.Now(), false)) if err != nil { t.Error(err) } n = repo.FollowNotification{"7", repo.NotifierTypeFollowNotification, "123"} err = db.PutRecord(repo.NewNotification(n, time.Now(), false)) if err != nil { t.Error(err) } err = db.MarkAllAsRead() if err != nil { t.Error(err) } rows, err := db.PrepareAndExecuteQuery("select * from notifications where read=0") if err != nil { t.Error(err) } if rows.Next() { t.Error("Failed to mark all as read") } } func TestNotificationDB_GetUnreadCount(t *testing.T) { db, teardown, err := newNotificationStore() if err != nil { t.Fatal(err) } defer teardown() n := repo.FollowNotification{"8", repo.NotifierTypeFollowNotification, "abc"} err = db.PutRecord(repo.NewNotification(n, time.Now(), false)) if err != nil { t.Error(err) } err = db.MarkAsRead("8") if err != nil { t.Error(err) } n = repo.FollowNotification{"9", repo.NotifierTypeFollowNotification, "xyz"} err = db.PutRecord(repo.NewNotification(n, time.Now(), false)) if err != nil { t.Error(err) } all, _, err := db.GetAll("", -1, []string{}) if err != nil { t.Error(err) } var c int for _, a := range all { if !a.IsRead { c++ } } count, err := db.GetUnreadCount() if err != nil { t.Error(err) } if count != c { t.Error("GetUnreadCount returned incorrect count") } }
gubatron/openbazaar-go
repo/db/notifications_test.go
GO
mit
7,264
/* global chrome */ (function contentScript() { function onPageMessage(event) { const message = event.data; if (event.source !== window) { return; } // Only accept messages that we know are ours if (typeof message !== 'object' || message === null || message.source !== 'react-rpm') { return; } // Ignore messages send from contentScript, avoid infinite dispatching if (message.sender === 'contentScript') { return; } chrome.runtime.sendMessage(message); } function onMessage(message, /* sender, sendResponse */) { // relay all messages to pageScript window.postMessage({ ...message, sender: 'contentScript' }, '*'); } window.addEventListener('message', onPageMessage); chrome.runtime.onMessage.addListener(onMessage); }());
mkawauchi/react-rpm
chrome/extension/content/contentScript.js
JavaScript
mit
814
'use strict'; const path = require('path'); const should = require('should'); const Nconfetti = require('./../../index.js'); describe('Nconfetti#loadSync', () => { it('should loadSync all config files of given directory', (done) => { const nconfetti = new Nconfetti({path: path.join(__dirname, '..', 'configs', 'env'), env: 'development'}); const config = nconfetti.loadSync(); const expectedConfig = { development_config: { development_config: 'A Entry', }, sub_folder: { sub_folder_config: { sub: 'A sub entry', }, }, }; should(config) .deepEqual(expectedConfig); done(); }); });
5minds/nconfetti
tests/nconfetti/test_load_sync.js
JavaScript
mit
684
<?php namespace Formapro\Yadm; use MongoDB\BSON\Binary; class Uuid { private $binary; public function __construct($data) { if (is_string($data) && false !== strpos($data, '-')) { $bytes = \Ramsey\Uuid\Uuid::fromString($data)->getBytes(); } elseif ($data instanceof Binary) { $bytes = $data->getData(); } else { $bytes = $data; } $this->binary = new Binary($bytes, Binary::TYPE_UUID); } public function getBinary(): Binary { return $this->binary; } public function getData() { return $this->binary->getData(); } public function getType() { return $this->binary->getType(); } public function toString(): string { return \Ramsey\Uuid\Uuid::fromBytes($this->getData())->toString(); } public function __toString(): string { return $this->toString(); } public static function generate(): self { return new static (\Ramsey\Uuid\Uuid::uuid4()->getBytes()); } }
makasim/yadm
src/Uuid.php
PHP
mit
1,083
# -*- coding: utf-8 -*- from jinja2 import Environment, FileSystemLoader, Template, TemplateNotFound import jinja2.ext import os class TemplateProvider(object): _template_dirs = [] def __init__(self, *args, **kwargs): self._env = self._create_env(*args, **kwargs) def _create_env(self, *args, **kwargs): raise NotImplementedError() def _get_template(self, *args, **kwargs): raise NotImplementedError() def render_to_string(self, *args, **kwargs): raise NotImplementedError() class JinjaTemplateProvider(TemplateProvider): def __init__(self, template_dirs, **extra_options): super(JinjaTemplateProvider, self).__init__(template_dirs, **extra_options) def _create_env(self, template_dirs, **extra_options): env = Environment(loader=FileSystemLoader(template_dirs), extensions=[jinja2.ext.i18n, jinja2.ext.with_], autoescape=True, **extra_options) env.install_gettext_callables(gettext=lambda s: s, ngettext=lambda s: s) return env def get_template(self, template, globals=None, env=None): env = env or self._env if isinstance(template, Template): return template elif isinstance(template, basestring): try: return env.get_template(template, globals=globals) except TemplateNotFound, e: raise TemplateNotFound(str(e)) for t in template: try: return env.get_template(t, globals=globals) except TemplateNotFound: continue raise TemplateNotFound(template) def render_to_string(self, template, context=None): template = self.get_template(template) context = dict(context or {}) return template.render(context) def _register_function(self, tag_type, function, name): assert tag_type in ['global', 'filter'] if name is None: name = function.__name__ getattr(self._env, {'filter': 'filters', 'global': 'globals'}[tag_type])[name] = function def register_filter(self, function, name=None): self._register_function('filter', function, name) def register_global(self, function, name=None): self._register_function('global', function, name) def register_template_dir(self, template_dir): new_dirs = set(os.listdir(template_dir)) for existing in self._template_dirs: if new_dirs.intersection(set(os.listdir(existing))): raise ValueError( 'There are overlapping directories ' 'with existing templates: %s' % new_dirs.intersection(set(os.listdir(template_dir)))) self._template_dirs.append(template_dir) self._env.loader = FileSystemLoader(self._template_dirs)
ra2er/templateit
templateit/providers.py
Python
mit
3,011
#!/usr/bin/env node /* * rapò * https://github.com/leny/rapo * * JS/COFFEE Document - /cli.js - cli entry point, commander setup and runner * * Copyright (c) 2014 Leny * Licensed under the MIT license. */ "use strict"; var chalk, error, pkg, program, rapo, sURL, spinner; pkg = require("../package.json"); rapo = require("./rapo.js"); chalk = require("chalk"); error = function(oError) { console.log(chalk.bold.red("✘ " + oError + ".")); return process.exit(1); }; (spinner = require("simple-spinner")).change_sequence(["◓", "◑", "◒", "◐"]); (program = require("commander")).version(pkg.version).usage("[options] <url>").description("Performance reviews for websites, using PhantomJS.").parse(process.argv); if (!(sURL = program.args[0])) { error("No URL given!"); } spinner.start(50); rapo(sURL, {}, function(oError, oResults) { spinner.stop(); console.log(oResults); return process.exit(0); });
leny/rapo
lib/cli.js
JavaScript
mit
937
<?php namespace Clocanth; use Clocanth\RouteManager; class App { protected function __construct() { } public static function run() { return RouteManager::instance()->routeRequest(); } }
fallenby/clocanth
clocanth/framework/App.php
PHP
mit
293
<div class="row"> <div class="col-sm-12"> <section class="panel"> <header class="panel-heading wht-bg"> <h4 class="gen-case"><img src="<?php echo theme_url('icon_vlb/customer-black.png') ?>" class="img-icon">&nbsp;&nbsp; <b>Add Customer Group</b> <div class="pull-right buttons"> <a class="btn btn-success" href="#" id="save" onClick="$('#sample_edit_form').submit() "><span>Save</span></a> <a class="btn btn-default" href="<?php echo site_url(ADMIN_PATH . "/customer/group/"); ?>"><span>Back</span></a> </div> </h4> </header> <?php $attributes = array('class' => 'form-horizontal bucket-form', 'id' => 'user_edit_form'); ?> <?php echo form_open(null, $attributes); ?> <div class="panel-body"> <div class="tab-content tasi-tab"> <div id="overview" class="tab-pane active"> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label class="col-lg-2 control-label"><span class="red"> *</span> Group Name : </label> <div class="col-lg-6"> <?php echo form_input(array('id' => 'first_name', 'name' => 'first_name', 'class' => 'form-control', 'value' => set_value('first_name', (isset($Customer->first_name)) ? $Customer->first_name : ''))); ?> </div> </div> <div class="form-group"> <label class="col-lg-2 control-label"> Customer : </label> <div class="col-lg-6"> <?php echo form_dropdown('state', array("" => " - Select Customer - ", "Customer 1" => "Customer 1", "Customer 2" => "Customer 2", 'Customer 3' => 'Customer 3'), set_value('state', (isset($User->state)) ? $User->state : ''), 'id="state" class="form-control" multiple=""'); ?> </div> </div> <div class="form-group"> <label class="col-lg-2 control-label"><span class="red"> *</span> Status : </label> <div class="col-lg-6"> <?php echo form_dropdown('eStatus', array("" => " - Select Status - ", "active" => "Active", "inactive" => "Inactive"), (isset($Sampl->eStatus)) ? $Sampl->eStatus : '', 'id="groups" class="form-control"'); ?> </div> </div> </div> </div> </div> </div> </div> <?php echo form_close(); ?> </section> </div> </div>
chintan21191/vlb
application/modules/customer/views/admin/group/edit.php
PHP
mit
3,654
#!/usr/bin/python # load all opp file, store in a matrix, and print to files for significant interactions import os, sys import psyco psyco.full() class PW: def __init__(self): self.pw={} self.pw={} self.pw={} self.pw={} self.opps=[] return def get_opp_names(self): fnames=os.listdir("./") opp_names=[] for fname in fnames: if fname[len(fname)-4:len(fname)] == ".opp": opp_names.append(fname) self.opps = opp_names return def print_opp_names(self): for fname in self.opps: print fname def load(self): if not self.opps: self.get_opp_names() for fname in self.opps: #ARG03A0020_010.opp conf1=fname[:14] lines = open(fname).readlines() for line in lines: if len(line) < 20: continue fields = line.split() conf2=fields[1] ele = float(fields[2]) vdw = float(fields[3]) raw = float(fields[4]) crt = float(fields[5]) if self.pw.has_key(conf1): self.pw[conf1][conf2]=(ele, vdw, raw, crt) else: self.pw[conf1] = {} self.pw[conf1][conf2]= (ele, vdw, raw, crt) def filter(self, t): count = 0 confs=self.pw.keys() for conf1 in confs: for conf2 in confs: if abs(self.pw[conf1][conf2][0]) > t and abs(self.pw[conf1][conf2][1]) > t: count += 1 return count if __name__== "__main__": pwtable = PW() # pwtable.get_opp_names() # pwtable.print_opp_names() pwtable.load() t=float(sys.argv[1]) print "Number of entries with ele or/and vdw greater than %f is %d" % (t, pwtable.filter(t))
MarilyGunnersLab/MCCE
mcce_stable/bin/thinopp.py
Python
mit
1,775
#if (TARGETS_NETCOREAPP && LESSTHAN_NET50) || NETSTANDARD20_OR_GREATER using System; // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma warning disable CA2217 // Do not mark enums with FlagsAttribute #pragma warning disable RCS1157 // Composite enum value contains undefined flag. // ReSharper disable CommentTypo // ReSharper disable IdentifierTypo // ReSharper disable UnusedMember.Global namespace System.Diagnostics.CodeAnalysis { /// <summary> /// <para>Specifies the types of members that are dynamically accessed.</para> /// <para> /// This enumeration has a <see cref="FlagsAttribute"/> attribute that allows a /// bitwise combination of its member values. /// </para> /// </summary> [Flags] internal enum DynamicallyAccessedMemberTypes { /// <summary> /// Specifies no members. /// </summary> None = 0, /// <summary> /// Specifies the default, parameterless public constructor. /// </summary> PublicParameterlessConstructor = 0x0001, /// <summary> /// Specifies all public constructors. /// </summary> PublicConstructors = 0x0002 | PublicParameterlessConstructor, /// <summary> /// Specifies all non-public constructors. /// </summary> NonPublicConstructors = 0x0004, /// <summary> /// Specifies all public methods. /// </summary> PublicMethods = 0x0008, /// <summary> /// Specifies all non-public methods. /// </summary> NonPublicMethods = 0x0010, /// <summary> /// Specifies all public fields. /// </summary> PublicFields = 0x0020, /// <summary> /// Specifies all non-public fields. /// </summary> NonPublicFields = 0x0040, /// <summary> /// Specifies all public nested types. /// </summary> PublicNestedTypes = 0x0080, /// <summary> /// Specifies all non-public nested types. /// </summary> NonPublicNestedTypes = 0x0100, /// <summary> /// Specifies all public properties. /// </summary> PublicProperties = 0x0200, /// <summary> /// Specifies all non-public properties. /// </summary> NonPublicProperties = 0x0400, /// <summary> /// Specifies all public events. /// </summary> PublicEvents = 0x0800, /// <summary> /// Specifies all non-public events. /// </summary> NonPublicEvents = 0x1000, /// <summary> /// Specifies all interfaces implemented by the type. /// </summary> Interfaces = 0x2000, /// <summary> /// Specifies all members. /// </summary> All = ~None } } #endif
rsdn/CodeJam
CodeJam.Main/Targeting/CodeAnalysis/DynamicallyAccessedMemberTypes.cs
C#
mit
2,543
/** * IP blocker extension for frontend HTTPD * * (C) 2021 TekMonks. All rights reserved. * License: See enclosed file. */ const utils = require(conf.libdir+"/utils.js"); let ipblacklist = []; exports.name = "ipblocker"; exports.initSync = _ => utils.watchFile(`${conf.confdir}/ipblacklist.json`, data=>ipblacklist=JSON.parse(data), conf.ipblacklistRefresh||10000); exports.processRequest = async (req, res, _dataSender, _errorSender, _access, error) => { if (_isBlacklistedIP(req)) { error.error(`Blocking blacklisted IP ${utils.getClientIP(req)}`); // blacklisted, won't honor res.socket.destroy(); res.end(); return true; } else return false; } function _isBlacklistedIP(req) { let clientIP = utils.getClientIP(req); if (req.socket.remoteFamily == "IPv6") clientIP = utils.getEmbeddedIPV4(clientIP)||utils.expandIPv6Address(clientIP);; return ipblacklist.includes(clientIP.toLowerCase()); }
TekMonks/monkshu
frontend/server/ext/ipblocker.js
JavaScript
mit
925
using System; using System.Reflection; namespace ForSerial.Objects { [AttributeUsage(AttributeTargets.Method)] public abstract class PreBuildAttribute : Attribute { private readonly Type requiredReaderType; private readonly Type preBuildContextType; protected PreBuildAttribute(Type requiredReaderType, Type preBuildContextType) { this.requiredReaderType = requiredReaderType; this.preBuildContextType = preBuildContextType; } public bool ReaderMatches(Type readerType) { return readerType == requiredReaderType; } public void AssertValidMethod(MethodInfo method) { if (method.ReturnType != preBuildContextType || method.GetParameterTypes().SingleOrDefaultIfMore() != preBuildContextType) { throw new InvalidMethodSignature(GetType(), method, preBuildContextType); } } public abstract Writer GetWriter(); public abstract object GetContextValue(Writer writer); public abstract void ReadPreBuildResult(object preBuildResult, Writer writer); private class InvalidMethodSignature : Exception { public InvalidMethodSignature(Type attributeType, MethodInfo method, Type expectedType) : base("{0} applied to invalid method {1}.{2}. Single parameter and return value must both be of type {3}" .FormatWith(attributeType.FullName, method.DeclaringType, method.Name, expectedType.FullName)) { } } } }
soxtoby/ForSerial
Serializer/Objects/PreBuildAttribute.cs
C#
mit
1,660
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class LoadBalancerLoadBalancingRulesOperations(object): """LoadBalancerLoadBalancingRulesOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2019_12_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, resource_group_name, # type: str load_balancer_name, # type: str **kwargs # type: Any ): # type: (...) -> Iterable["_models.LoadBalancerLoadBalancingRuleListResult"] """Gets all the load balancing rules in a load balancer. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param load_balancer_name: The name of the load balancer. :type load_balancer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LoadBalancerLoadBalancingRuleListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2019_12_01.models.LoadBalancerLoadBalancingRuleListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.LoadBalancerLoadBalancingRuleListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-12-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('LoadBalancerLoadBalancingRuleListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/loadBalancingRules'} # type: ignore def get( self, resource_group_name, # type: str load_balancer_name, # type: str load_balancing_rule_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.LoadBalancingRule" """Gets the specified load balancer load balancing rule. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param load_balancer_name: The name of the load balancer. :type load_balancer_name: str :param load_balancing_rule_name: The name of the load balancing rule. :type load_balancing_rule_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: LoadBalancingRule, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_12_01.models.LoadBalancingRule :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.LoadBalancingRule"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-12-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'), 'loadBalancingRuleName': self._serialize.url("load_balancing_rule_name", load_balancing_rule_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('LoadBalancingRule', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/loadBalancingRules/{loadBalancingRuleName}'} # type: ignore
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_12_01/operations/_load_balancer_load_balancing_rules_operations.py
Python
mit
8,924
guru_view
abhu66/sekolah
application/views/admin/guru/guru_view.php
PHP
mit
9
require "application_system_test_case" class RequestsTest < ApplicationSystemTestCase # test "visiting the index" do # visit requests_url # # assert_selector "h1", text: "Request" # end end
adp90/cwrubeta-services
test/system/requests_test.rb
Ruby
mit
205
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Security::Mgmt::V2018_06_01 module Models # # Azure Security Center is provided in two pricing tiers: free and # standard, with the standard tier available with a trial period. The # standard tier offers advanced security capabilities, while the free tier # offers basic security features. # class Pricing < Resource include MsRestAzure # @return [PricingTier] The pricing tier value. Azure Security Center is # provided in two pricing tiers: free and standard, with the standard # tier available with a trial period. The standard tier offers advanced # security capabilities, while the free tier offers basic security # features. Possible values include: 'Free', 'Standard' attr_accessor :pricing_tier # @return [Duration] The duration left for the subscriptions free trial # period - in ISO 8601 format (e.g. P3Y6M4DT12H30M5S). attr_accessor :free_trial_remaining_time # # Mapper for Pricing class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'Pricing', type: { name: 'Composite', class_name: 'Pricing', model_properties: { id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } }, pricing_tier: { client_side_validation: true, required: true, serialized_name: 'properties.pricingTier', type: { name: 'String' } }, free_trial_remaining_time: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.freeTrialRemainingTime', type: { name: 'TimeSpan' } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_security/lib/2018-06-01/generated/azure_mgmt_security/models/pricing.rb
Ruby
mit
2,961
namespace StringBuilder.Substring { using System; using System.Text; public static class Extension { public static StringBuilder Substring(this StringBuilder sb, int startIndex, int length) { if (startIndex < 0 || startIndex >= sb.Length || length < 0 || startIndex + length > sb.Length) { throw new IndexOutOfRangeException(); } StringBuilder result = new StringBuilder(); for (int i = 0; i < length; i++) { result.Append(sb[startIndex + i]); } return result; } } }
danisio/CSharpOOP-Homeworks
Extension-Methods-Delegates-Lambda-LINQ/01.StringBuilder.Substring/Extension.cs
C#
mit
646
( function ( root, factory ) { if ( typeof define === 'function' && define.amd ) { define( [ 'ko' ], factory ); } else { root.router = factory( root.ko ); }; }( this, function ( ko ) { "use strict"; var router = { on404: function ( rt, e ) { throw new Error( [ 'Path' + router.resolvePath.apply( router, rt ) + ' not found.', 'You can handle the error by overriding this function.' ].join( '\n' ) ); }, route: ko.observableArray(), root: Page( { title: window.document.title } ), resolvePath: function resolvePath() { var args = Array.from( arguments ); var url = args.map( function ( r, i, s ) { if ( r.slice( -1 ) !== '/' && i !== s.length - 1 ) r += '/'; return r; } ).reduce( function ( url, path ) { return new window.URL( path, url.href ); }, new window.URL( window.location.origin ) ); return url.pathname + url.search + url.hash; }, navigate: function navigate( href ) { href = router.resolvePath( href ); return guards( path( href ) ).then( function () { window.history.pushState( {}, '', href ); router.route( path() ); } ); }, start: function start( opts ) { return ( window.onpopstate = handlePop )(); }, loader: { start: function () {}, done: function () {} } }; router.Page = Page; ko.bindingHandlers[ 'page' ] = { init: function ( element, valueAccessor, allBindingsAccessor, viewModel, bindingContext ) { var value = valueAccessor(); if ( !value.route ) throw new Error( 'route required' ); var parent = bindingContext._page || router.root; var page = parent.to[ value.route ] = parent.to[ value.route ] || Page( { route: value.route } ); Object.assign( page, { element: element, src: value.src, title: value.title || parent.title, template: value.template, guard: value.guard, onclose: value.onclose, context: bindingContext } ); page.close(); return { controlsDescendantBindings: true }; } }; ko.bindingHandlers[ 'nav' ] = { update: function ( element, valueAccessor, allBindingsAccessor, viewModel, bindingContext ) { var value = valueAccessor(); var page = bindingContext._page || {}; var route = page.path ? page.path() : '/'; if ( element.tagName === 'A' ) element.href = router.resolvePath( route, value ); element.onclick = function ( ev ) { var href = this.href || router.resolvePath( route, value ); if ( ev.button !== 0 || ( ev.ctrlKey && ev.button === 0 ) ) { if ( this.tagName !== 'A' ) window.open( href, '_blank' ).focus(); return true; }; router.navigate( href ); return false; }; } }; function Page( data ) { if ( !( this instanceof Page ) ) return new Page( data ); data = data || {}; this.element = data.element; this.route = data.route; this.title = data.title; this.template = data.template; this.guard = data.guard; this.onclose = data.onclose; this.current = ''; this.src = data.src; this.context = data.context; this.to = {}; }; Page.prototype.check = function check( route ) { return wrap( this.guard, this, [ route ] ).then( function () { return this; }.bind( this ) ); }; Page.prototype.ensureTemplate = function ensureTemplate() { var tmplname = this.template.name || this.template; var tmpl = window.document.querySelector( 'script#' + tmplname ); if ( !tmpl && !this.src ) return Promise.reject( new Error( 'No template or source supplied' ) ); if ( !tmpl && this.src ) return window.fetch( encodeURI( this.src ) ).then( function ( response ) { if ( response.status !== 200 ) { var e = new Error( response.statusText ); e.response = response; throw e; }; return response.text(); } ).then( function ( text ) { var tmpl = document.createElement( 'div' ); tmpl.innerHTML = text; tmpl = tmpl.firstChild; if ( !tmpl || tmpl.tagName !== 'SCRIPT' || tmpl.id !== tmplname ) throw new Error( 'Wrong source' ); window.document.body.appendChild( tmpl ); } ); }; Page.prototype.open = function open( current ) { this.current = current; if ( !this.template || !this.element ) return this; ko.applyBindingsToNode( this.element, { template: this.template }, this.context.extend( { _page: this } ) ); this.element.style.display = ''; return this; }; Page.prototype.close = function close() { this.current = ''; var children = Array.from( this.element.children ); var ready = Promise.resolve(); if ( children.length ) ready = wrap( this.onclose, this ); return ready.then( function () { children.map( function ( c ) { c.remove(); } ); this.element.style.display = 'none'; return this; }.bind( this ) ); }; Page.prototype.closeChildren = function closeChildren() { return Promise.all( Object.keys( this.to ).map( function ( t ) { return this.to[ t ].close(); }.bind( this ) ) ); }; Page.prototype.closeSiblings = function closeSiblings() { var parent = this.parent(); if ( !parent ) return; return Promise.all( Object.keys( parent.to ).map( function ( t ) { if ( parent.to[ t ] !== this ) return parent.to[ t ].close(); }.bind( this ) ) ); }; Page.prototype.next = function next( route ) { if ( !route && this.to[ '/' ] ) return this.to[ '/' ]; if ( route && this.to[ route ] ) return this.to[ route ]; if ( route && this.to[ '*' ] ) return this.to[ '*' ]; }; Page.prototype.path = function path() { var path = []; var parent = this; do { path.unshift( parent.current ); parent = parent.parent(); } while ( parent ) return path.join( '/' ); }; Page.prototype.parent = function parent() { if ( this === router.root ) return; try { return this.context._page || router.root; } catch ( e ) { return router.root; }; }; function guards( rt ) { router.loader.start(); console.log( 'GUARD', rt ); return router.root.check( rt ).then( workGuard.bind( this, { rt: Array.from( rt ), page: router.root } ) ).then( function ( page ) { window.document.title = page.title || router.root.title; router.loader.done(); return page; } ).catch( function ( e ) { if ( e instanceof Promise ) return e; if ( e instanceof Error && e.message === 'Page not found' ) return router.on404( rt, e ); throw e; router.loader.done(); } ); }; function workGuard( cur ) { var r = cur.rt.shift(); var next = cur.page.next( r ); if ( !next ) return cur.page.closeChildren().then( function () { if ( r ) return Promise.reject( new Error( 'Page not found' ) ); return Promise.resolve( cur.page ); }.bind( this ) ); return Promise.all( [ next.check( r ), next.ensureTemplate() ] ).then( function ( res ) { cur.page = res[ 0 ]; if ( cur.page.current === r ) return; return cur.page.closeSiblings().then( function () { cur.page.open( r ); } ); } ).then( workGuard.bind( this, cur ) ); }; function handlePop() { return guards( path() ).then( function () { router.route( path() ); } ); }; function path( pathname ) { return ( pathname || window.location.pathname ).slice( 1 ).split( '/' ).filter( function ( r ) { return !!r; } ); }; function wrap( target, reciever, args ) { if ( target instanceof Error ) return Promise.reject( target ); if ( !( target instanceof Function ) ) return Promise.resolve( target ); if ( !Array.isArray( args ) ) args = [ args ]; try { var r = ( reciever || args ) ? target.apply( reciever, args ) : target.call(); if ( !( r instanceof Promise ) ) return Promise.resolve( r ); return r; } catch ( e ) { return Promise.reject( e ); }; }; return router; } ) );
qwemaze/ko-router
ko-router.js
JavaScript
mit
9,328
namespace WhatThe.Mods.CitiesSkylines.ServiceDispatcher.SerializableSettings { /// <summary> /// The different service types. /// </summary> public enum ServiceType { /// <summary> /// Not a service. /// </summary> None = 0, /// <summary> /// The death care standard service. /// </summary> DeathCare = 1, /// <summary> /// The garbage standard service. /// </summary> Garbage = 2, /// <summary> /// The health care standard service. /// </summary> HealthCare = 3, /// <summary> /// The wrecking crew hidden service. /// </summary> WreckingCrews = 4, /// <summary> /// The recovery crew hidden service. /// </summary> RecoveryCrews = 5 } /// <summary> /// The different settings types. /// </summary> public enum SettingsType { /// <summary> /// Not a settngs block. /// </summary> None = 0, /// <summary> /// A standard service block. /// </summary> StandardService = 1, /// <summary> /// A hidden service block. /// </summary> HiddenService = 2, /// <summary> /// The service range settings block. /// </summary> ServiceRanges = 3, /// <summary> /// The compatibility settings block. /// </summary> Compatibility = 4 } /// <summary> /// Result of deserialization. /// </summary> internal enum DeserializationResult { /// <summary> /// The end of data was reached. /// </summary> EndOfData = 0, /// <summary> /// Deserialization was successfull. /// </summary> Success = 1, /// <summary> /// An error occured. /// </summary> Error = 2 } }
DinkyToyz/wtmcsServiceDispatcher
wtmcsServiceDispatcher/SerializableSettings/SimpleTypes.cs
C#
mit
1,975
package com.ssh.action; import org.hibernate.sql.Update; import org.springframework.beans.factory.annotation.Autowired; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.ssh.bean.Department; import com.ssh.service.DepartmentService; import com.ssh.util.PageBean; public class DepartmentAction extends ActionSupport implements ModelDriven<Department>{ /** * */ private static final long serialVersionUID = 1L; private Department department = new Department(); @Autowired private DepartmentService departmentService; private int curPage=1; public int getCurPage() { return curPage; } public void setCurPage(int curPage) { this.curPage = curPage; } @Override public Department getModel() { // TODO Auto-generated method stub return department; } //提供一个查询方法 public String findAll(){ PageBean<Department> pageBean = departmentService.findByPage(curPage); ActionContext.getContext().getValueStack().push(pageBean); return "find"; } //跳转到增加部门页面 public String saveUI(){ return "saveUI"; } //添加部门的执行方法 public String save(){ departmentService.save(department); return "saveSuccess"; } //编辑部门执行方法 public String edit(){ department = departmentService.findById(department.getDid()); return "editSuccess"; } //编写修改部门的方法 public String update(){ departmentService.update(department); return "updateSuccess"; } //删除部门的方法 public String delete(){ department = departmentService.findById(department.getDid()); departmentService.delete(department); return "deleteSuccess"; } }
mahongliang/ssh_employee
src/main/java/com/ssh/action/DepartmentAction.java
Java
mit
1,766
const RATING_CHANGED = 'RATING_CHANGED'; const Rating = function(model, context) { var stars = []; for (var i = 1; i <= model.top; i++) { let star = model.rating < i ? '☆' : '★'; let prevRating = (model.rating == model.prevRating) ? '' : ` (was ${model.prevRating}/${model.top})`; let title = `${model.rating}/${model.top}${prevRating}`; let key = parseInt(i); stars.push( h('span', {onClick: ()=>context.bus$.push({type: RATING_CHANGED, rating: key}), key: i, title: title}, star) ); } return( h('div', null, [ h('p', {className: "event-form-rating"}, stars), h('input', {type: "hidden", name: "event[rating]", value: model.rating}, null) ]) ); } const RatingApplet = { view: Rating, update: function(message) { switch (message.type) { case RATING_CHANGED: this.updateModel({rating: message.rating}); break; } } } export default RatingApplet;
dncrht/mical
app/javascript/packs/rating.js
JavaScript
mit
948
'use strict'; var grunt = require('grunt'), config = require('./config'); exports.log = grunt.log; exports.verbose = grunt.verbose; exports.init = function() { if (!config.get('cool_colors')) { grunt.option('color', false); grunt.log.initColors(); } if (config.get('verbose')) { grunt.option('verbose', true); } };
jacobk/werk
lib/logger.js
JavaScript
mit
341
//= require ./templates/uploading //= require ./templates/complete //= require ./s3_fileupload
allen13/s3_fileupload_rails
app/assets/javascripts/s3_fileupload/index.js
JavaScript
mit
94
package treap import ( "fmt" "testing" ) func StringLess(p, q interface{}) bool { return p.(string) < q.(string) } func IntLess(p, q interface{}) bool { return p.(int) < q.(int) } func TestEmpty(t *testing.T) { tree := NewTree(StringLess) if tree.Len() != 0 { t.Errorf("expected tree len 0") } x := tree.Get("asdf") if x != nil { t.Errorf("expected nil for nonexistent key") } } func TestInsert(t *testing.T) { tree := NewTree(StringLess) tree.Insert("xyz", "adsf") x := tree.Get("xyz") if x != "adsf" { t.Errorf("expected adsf, got %v", x) } } func TestFromDoc(t *testing.T) { tree := NewTree(IntLess) tree.Insert(5, "a") tree.Insert(7, "b") x := tree.Get(5) if x != "a" { t.Errorf("expected a, got %v", x) } x = tree.Get(7) if x != "b" { t.Errorf("expected b, got %v", x) } tree.Insert(2, "c") x = tree.Get(2) if x != "c" { t.Errorf("exepcted c, got %v", x) } tree.Insert(2, "d") x = tree.Get(2) if x != "d" { t.Errorf("exepcted d, got %v", x) } tree.Delete(5) if tree.Exists(5) { t.Errorf("expected 5 to be removed from tree") } } func TestBalance(t *testing.T) { tree := NewTree(IntLess) for i := 0; i < 1000; i++ { tree.Insert(i, false) } for i := 0; i < 1000; i += 50 { fmt.Printf("%d: height = %d\n", i, tree.Height(i)) } } // tests copied from petar's llrb func TestCases(t *testing.T) { tree := NewTree(IntLess) tree.Insert(1, true) tree.Insert(1, false) if tree.Len() != 1 { t.Errorf("expecting len 1") } if !tree.Exists(1) { t.Errorf("expecting to find key=1") } tree.Delete(1) if tree.Len() != 0 { t.Errorf("expecting len 0") } if tree.Exists(1) { t.Errorf("not expecting to find key=1") } tree.Delete(1) if tree.Len() != 0 { t.Errorf("expecting len 0") } if tree.Exists(1) { t.Errorf("not expecting to find key=1") } } func TestReverseInsertOrder(t *testing.T) { tree := NewTree(IntLess) n := 100 for i := 0; i < n; i++ { tree.Insert(n-i, true) } c := tree.IterKeysAscend() for j, item := 1, <-c; item != nil; j, item = j+1, <-c { if item.(int) != j { t.Fatalf("bad order") } } } func TestIterateOverlapNoFunc(t *testing.T) { tree := NewTree(IntLess) n := 100 for i := 0; i < n; i++ { tree.Insert(n-i, true) } for v := range tree.IterateOverlap(50) { t.Errorf("didn't expect to have any overlap since fn not defined: %v", v) } } type BucketKey struct { Start int64 Duration int64 } type BucketVal struct { Start int64 Duration int64 Value float64 } func BucketLess(a, b interface{}) bool { aa := a.(*BucketKey) bb := b.(*BucketKey) if aa.Start < bb.Start { return true } if aa.Start == bb.Start { return aa.Duration < bb.Duration } return false } func BucketOverlap(a, b interface{}) bool { aa := a.(*BucketKey) bb := b.(*BucketKey) return aa.Start+aa.Duration < bb.Start } func TestIterateOverlap(t *testing.T) { tree := NewOverlapTree(BucketLess, BucketOverlap) tree.Insert(&BucketKey{100, 10}, &BucketVal{100, 10, 5.0}) tree.Insert(&BucketKey{110, 10}, &BucketVal{110, 10, 6.0}) tree.Insert(&BucketKey{120, 10}, &BucketVal{120, 10, 7.0}) tree.Insert(&BucketKey{130, 10}, &BucketVal{130, 10, 8.0}) for v := range tree.IterateOverlap(&BucketKey{105, 7}) { fmt.Printf("val: %v\n", v) } } /* before: after: A B / \ / \ B C D A / \ / \ / \ D E F G E C / \ F G */ func TestLeftRotate(t *testing.T) { // create a tree by hand... a := newNode("a", "a", 1) b := newNode("b", "b", 2) c := newNode("c", "c", 3) d := newNode("d", "d", 4) e := newNode("e", "e", 5) f := newNode("f", "g", 5) g := newNode("g", "g", 5) a.left = b a.right = c b.left = d b.right = e c.left = f c.right = g x := new(Tree) root := x.leftRotate(a) if root != b { t.Errorf("expected root to be b") } if root.left != d { t.Errorf("expected root.left to be d") } if root.right != a { t.Errorf("expected root.right to be a") } if a.left != e { t.Errorf("expected a.left to be e") } if a.right != c { t.Errorf("expected a.right to be c") } if c.left != f { t.Errorf("expected c.left to be f") } if c.right != g { t.Errorf("expected c.right to be g") } } /* before: after: A C / \ / \ B C A G / \ / \ / \ D E F G B F / \ D E */ func TestRightRotate(t *testing.T) { // create a tree by hand... a := newNode("a", "a", 1) b := newNode("b", "b", 2) c := newNode("c", "c", 3) d := newNode("d", "d", 4) e := newNode("e", "e", 5) f := newNode("f", "g", 5) g := newNode("g", "g", 5) a.left = b a.right = c b.left = d b.right = e c.left = f c.right = g x := new(Tree) root := x.rightRotate(a) if root != c { t.Errorf("expected root to be c") } if root.left != a { t.Errorf("expected root.left to be a") } if root.right != g { t.Errorf("expected root.right to be g") } if a.left != b { t.Errorf("expected a.left to be b") } if a.right != f { t.Errorf("expected a.right to be f") } if b.left != d { t.Errorf("expected b.left to be d") } if b.right != e { t.Errorf("expected b.right to be e") } }
stathat/treapold
treap_test.go
GO
mit
7,171
# -*- encoding : utf-8 -*- module CommentHelper end
grigio/opentalk
app/helpers/comment_helper.rb
Ruby
mit
52
// @ts-ignore mocked (original defined in webdriver package) import got from 'got' import { remote } from '../../../src' import { ELEMENT_KEY } from '../../../src/constants' describe('element', () => { it('should fetch an element', async () => { const browser = await remote({ baseUrl: 'http://foobar.com', capabilities: { browserName: 'foobar' } }) const elem = await browser.$('#foo') expect(got.mock.calls[1][1].method) .toBe('POST') expect(got.mock.calls[1][0].pathname) .toBe('/session/foobar-123/element') expect(got.mock.calls[1][1].json) .toEqual({ using: 'css selector', value: '#foo' }) expect(elem.elementId).toBe('some-elem-123') expect(elem[ELEMENT_KEY]).toBe('some-elem-123') expect(elem.ELEMENT).toBe(undefined) }) it('should fetch an element (no w3c)', async () => { const browser = await remote({ baseUrl: 'http://foobar.com', capabilities: { browserName: 'foobar-noW3C' } }) const elem = await browser.$('#foo') expect(elem[ELEMENT_KEY]).toBe(undefined) expect(elem.ELEMENT).toBe('some-elem-123') }) it('should allow to transform protocol reference into a WebdriverIO element', async () => { const browser = await remote({ baseUrl: 'http://foobar.com', capabilities: { browserName: 'foobar-noW3C' } }) const elem = await browser.$({ [ELEMENT_KEY]: 'foobar' }) expect(elem.elementId).toBe('foobar') }) it('keeps prototype from browser object', async () => { const browser = await remote({ baseUrl: 'http://foobar.com', capabilities: { browserName: 'foobar', // @ts-ignore mock feature mobileMode: true, 'appium-version': '1.9.2' } }) expect(browser.isMobile).toBe(true) const elem = await browser.$('#foo') expect(elem.isMobile).toBe(true) }) afterEach(() => { got.mockClear() }) })
webdriverio/webdriverio
packages/webdriverio/tests/commands/browser/$.test.ts
TypeScript
mit
2,233
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure end module Azure::Network end module Azure::Network::Mgmt end module Azure::Network::Mgmt::V2016_06_01 end
Azure/azure-sdk-for-ruby
management/azure_mgmt_network/lib/2016-06-01/generated/azure_mgmt_network/module_definition.rb
Ruby
mit
284
var five = require("johnny-five");<% if (projectType === "useParticle") { %> var Spark = require("spark-io"); var board = new five.Board({ // Create Johnny-Five board connected via Spark. // Assumes access tokens are stored as environment variables // but you can enter them directly below instead. io: new Spark({ token: <%- sparkToken ? '"' + sparkToken + '"': 'process.env.SPARK_TOKEN'; %>, deviceId: <%- sparkDeviceID ? '"' + sparkDeviceID + '"': 'process.env.SPARK_DEVICE_ID'; %> }) });<% } else if (projectType === "useRasPi") { %> var board = new five.Board({ io: new Raspi() }); <% } else { %> var board = new five.Board(); <% } if (includeBarcli) { %> var Barcli = require("barcli"); <% } if (includej5Songs) { %> var songs = require("j5-songs"); <% } if (includeNodePixel) { %> var pixel = require("node-pixel"); var strip = null; <% } if (includeOledJS) { %> var Oled = require("oled-js"); <% } %> // The board's pins will not be accessible until // the board has reported that it is ready board.on("ready", function () { console.log("Ready!"); <% if (includeBarcli) { %> // See https://github.com/dtex/barcli for usage var graph = new Barcli(); // Sets bar to 25% graph.update(0.25); // Sets bar to 100% graph.update(1.0); <% } if (includeOledJS) { %> //OLED Options var opts = { width: 128, height: 64, address: 0x3D }; // Instance of Oled var oled = new Oled(board, five, opts); // See https://github.com/noopkat/oled-js for usage. oled.clearDisplay(); <% } if (includeNodePixel) { %> // Node-Pixel options strip = new pixel.Strip({ data: 6, length: 4, firmata: board, controller: "FIRMATA", }); strip.on("ready", function () { // do stuff with the strip here. // See https://github.com/ajfisher/node-pixel for usage }); <% } if (includej5Songs) { %> // j5-songs var piezo = new five.Piezo(3); // Load a song object var song = songs.load("never-gonna-give-you-up"); // See https://github.com/julianduque/j5-songs for more songs and usage // Play it ! piezo.play(song); <% } if (!(includej5Songs || includeOledJS || includeNodePixel)) { if (projectType === "useParticle") { %> var led = new five.Led("D7"); <% } else {%> var led = new five.Led(13); <% } %> led.blink(500);<% } %> });
pierceray/generator-johnny-five
generators/app/templates/_index.js
JavaScript
mit
2,333
/** * Particle */ (function() { var nspace = this.Particle; /** * * @type Particle */ var Particle = nspace.Particle = function(spin, energy) { this.spin = spin; this.energy = energy; }; Particle.SPIN_HALF = 0.5; Particle.SPIN_ONE = 1; Particle.prototype = { spin: null, mass: null, restEnergy: null, charge: null, energy: null, /** * * @param {Number} energy * @return {Particle} */ setEnergy: function(energy) { this.energy = energy; return this; }, /** * * @return {Number} */ getEnergy: function() { return this.energy; }, /** * @returns {Number} */ getMass: function() { return this.mass; }, /** * @returns {Number} eV */ getRestEnergy: function() { return this.restEnergy; }, /** * @returns {Number} eV */ getCharge: function() { return this.charge; }, /** * @returns {Number} */ getSpin: function() { return this.spin; } }; })();
bjester/quantum-probability
lib/particle/Particle.js
JavaScript
mit
1,080
<div class="row"> <div class ="col-md-12"> <form method ="Post" action = "<?php echo base_url(); ?>Lektori/post_delete_lektor" enctype="multipart/form-data"> <div class ="row"> <div class ="col-md-12"> <div class ="form-group"> <input type="hidden" name ="ID" value="<?php echo $id ?>"class ="form-control"> </div> </div> <div class ="col-md-12"> <div class ="form-group"> <label>Meno lektora :</label> <?php echo $Lektor ?> </div> </div> <div class ="col-md-12"> <button class="btn btn-danger btn-large">Odstrániť</button> <button class="btn btn-info btn-large"><a href="<?php echo base_url();?>Admin/Lektori">Späť</a></button> </div> </div> </form> </div> </div>
JohnnySima/Agentura
application/modules/Lektori/views/delete_lektor_v.php
PHP
mit
1,007
/** * A script that will read all users from one Auth0 tenant and create new users * in another Auth0 tenant. The existing users' metadata will be ready and only * those users with a matching datatools client_id will be copied over. The new * users will have new passwords set, so the users will have to reset their * passwords to regain access. * * Two config files are required for this to work. The `from-client.json` will * contain information for machine-to-machine connections and the existing * client application ID that users should have in their metadata. The * `to-client.json` file should have information for machine-to-machine * connections and the client application ID that will replace to old * applicaiton client ID in their metadata. * * If deleting (and then recreating) existing users in the to tenant is desired, * the connection ID is also required. A way to find the connection ID involves * going to the Auth0 API explorer, setting the API token with a token generated * from a machine-to-machine API for the to tenant and then executing the "Get * all connections" endpoint. * See here: https://auth0.com/docs/api/management/v2#!/Connections/get_connections. * That endpoint will give a listing of all connections. Find the connection * with the name "Username-Password-Authentication" and use that ID. * * Both of the `from-client.json` and `to-cleint.json` files should have the * following base format: * * { * "apiClient": "SECRET", * "apiSecret": "SECRET", * "domain": "SECRET.auth0.com", * "clientId": "SECRET" * "connectionId": "secrect" // optional in to-client.json for deleting users * } * * * To run the script, open a cli and type `node migrate-auth0-users.js` */ const fetch = require('isomorphic-fetch') const omit = require('lodash/omit') const qs = require('qs') const uuid = require('uuid/v4') // load required config files const from = require('./from-client.json') const to = require('./to-client.json') const DEFAULT_CONNECTION_NAME = 'Username-Password-Authentication' const deleteExistingUsersInToClient = true /** * Get a Management API token using machine-to-machine credentials. */ async function getManagementToken (connectionSettings) { const { apiClient, apiSecret, domain } = connectionSettings // make request to auth0 to get a token const token = await fetch( `https://${domain}/oauth/token`, { body: JSON.stringify({ grant_type: 'client_credentials', client_id: apiClient, client_secret: apiSecret, audience: `https://${domain}/api/v2/` }), headers: { 'content-type': 'application/json' }, method: 'POST' } ) .then((res) => res.json()) .then((json) => { if (!json.access_token) { // Encountered a problem authenticating with API, raise error console.error(json) throw new Error('error authenticating with Auth0 Management API') } else { // Authentication successful console.log(`received access to management api for domain ${domain}`) return json.access_token } }) return token } /** * Create header information to perform authenticated requests to management API */ function makeHeaderWithToken (token) { return { Authorization: `Bearer ${token}`, 'content-type': 'application/json' } } /** * Helper to wait for a bit * @param waitTime time in milliseconds */ function promiseTimeout (waitTime) { return new Promise((resolve, reject) => { setTimeout(resolve, waitTime) }) } /** * Delete a user from a tenant */ async function deleteUser (domain, token, connectionId, email) { // deleting a lot of users individually can sometimes result in 429 errors // from Auth0, so wait 4 seconds just in case. await promiseTimeout(4000) const response = await fetch( `https://${domain}/api/v2/connections/${connectionId}/users?${qs.stringify({email})}`, { headers: makeHeaderWithToken(token), method: 'DELETE' } ) if (response.status >= 400) { console.error(`Failed to delete user! Received status: ${response.status}`) console.error(await response.text()) } } /** * make request to create user */ async function createUser (domain, token, user) { const response = await fetch( `https://${domain}/api/v2/users`, { body: JSON.stringify(user), headers: makeHeaderWithToken(token), method: 'POST' } ) // check if request succeeded const createFailed = response.status >= 400 const responseJson = await response.json() if (createFailed) { // although the creation failed, don't raise an error as most // of the time this was caused by the user already existing console.error(`created user failed for ${user.email}`) return { responseJson, success: false } } else { // user creation successful! console.log(`created user ${user.email}`) return { success: true } } } async function main () { // get management tokens for both from and to tenants const fromToken = await getManagementToken(from) const toToken = await getManagementToken(to) // iterate through all users in from manager let numUsersFetched = 0 let totalUsers = Number.POSITIVE_INFINITY let page = 0 while (numUsersFetched < totalUsers) { // get a batch of 100 users (a limit imposed by auth0) const response = await fetch( `https://${from.domain}/api/v2/users?per_page=100&include_totals=true&page=${page}`, { headers: makeHeaderWithToken(fromToken) } ) const json = await response.json() // update the progress of fetching users numUsersFetched += json.users.length console.log(`fetched ${numUsersFetched} users so far`) totalUsers = json.total page++ // iterate through fetched users for (let user of json.users) { // only users that have a matching clientId should be created in the // new tenant, so assume they shouldn't be created until finding a // match let shouldCreateInNewApp = false // replace all user and app metadata with only the matching from // client data and then replace the client ID with the to client ID const metadatas = ['user_metadata', 'app_metadata'] metadatas.forEach(metadataKey => { if (!user[metadataKey]) return const metadata = user[metadataKey] if (!metadata.datatools) return metadata.datatools = metadata.datatools.filter( dt => dt.client_id === from.clientId ) if (metadata.datatools.length > 0) { shouldCreateInNewApp = true metadata.datatools[0].client_id = to.clientId } }) // no match found, continue to the next user in the current batch if (!shouldCreateInNewApp) continue // can't copy over passwords, so set the password of the copied user // as a UUID so that it's extremely unlikely for some random person // to guess the password. The user will have to reset their password // to gain access. user.password = uuid() // add required connection name (this is the default value created // by Auth0, so it could theoretically be different.) user.connection = DEFAULT_CONNECTION_NAME // omit items that will cause the creation to fail or cause weirdness // in new data values user = omit( user, [ 'logins_count', 'last_ip', 'last_login', 'last_password_reset', 'created_at', 'updated_at', 'identities' ] ) // Modify the user_id so an extra prefix isn't created. User IDs are in // the format `auth0|123456`. If that exact user ID is sent over as is // when creating the new user, the new user_id will look something like: // `auth0|auth0|123456`. If now user_id is included in the create user // request, then a completely new user_id is created. However, if a the // user_id is just the data beyond the "auth0|" (ie everything from // position 6 and beyond), then Auth0 will create a user_id with the // exact same data. user.user_id = user.user_id.substr(6) // attempt to create the user const createUserResult = await createUser(to.domain, toToken, user) if (!createUserResult.success) { // creation of user not successful, check if script should try again by // deleting an existing user if ( createUserResult.responseJson.message === 'The user already exists.' && deleteExistingUsersInToClient ) { // user creation failed due to existing user. Delete that existing // user and then try creating the user again console.log('Deleting existing user in to tenant') await deleteUser(to.domain, toToken, to.connectionId, user.email) const createUserResult2ndTry = await createUser(to.domain, toToken, user) if (!createUserResult2ndTry.success) { console.log('Creating user a 2nd time failed!') console.error(createUserResult.responseJson) } } else { console.error(createUserResult.responseJson) } } } } } main()
conveyal/datatools-manager
scripts/migrate-auth0-users.js
JavaScript
mit
9,303
<?php return array ( 'id' => 'lg_kf350_ver1', 'fallback' => 'lg_generic_obigo_q7', 'capabilities' => array ( 'mobile_browser' => 'Teleca-Obigo', 'mobile_browser_version' => '7.0', 'can_skip_aligned_link_row' => 'true', 'uaprof' => 'http://gsm.lge.com/html/gsm/LG-KF350.xml', 'model_name' => 'KF350', 'brand_name' => 'LG', 'release_date' => '2009_april', 'softkey_support' => 'true', 'table_support' => 'true', 'wml_1_1' => 'true', 'wml_1_3' => 'true', 'physical_screen_height' => '45', 'columns' => '15', 'physical_screen_width' => '34', 'rows' => '20', 'max_image_width' => '228', 'resolution_width' => '240', 'resolution_height' => '320', 'max_image_height' => '280', 'jpg' => 'true', 'gif' => 'true', 'bmp' => 'true', 'wbmp' => 'true', 'png' => 'true', 'colors' => '65536', 'nokia_voice_call' => 'true', 'wta_phonebook' => 'true', 'max_deck_size' => '40000', 'wap_push_support' => 'true', 'mms_png' => 'true', 'mms_max_size' => '307200', 'mms_max_width' => '1280', 'mms_spmidi' => 'true', 'mms_max_height' => '1024', 'mms_gif_static' => 'true', 'mms_wav' => 'true', 'mms_vcard' => 'true', 'mms_midi_monophonic' => 'true', 'mms_bmp' => 'true', 'mms_wbmp' => 'true', 'mms_amr' => 'true', 'mms_jpeg_baseline' => 'true', 'wav' => 'true', 'sp_midi' => 'true', 'mp3' => 'true', 'amr' => 'true', 'midi_monophonic' => 'true', 'imelody' => 'true', 'max_data_rate' => '40', 'xhtml_can_embed_video' => 'plain', 'directdownload_support' => 'true', 'oma_v_1_0_separate_delivery' => 'true', ), );
cuckata23/wurfl-data
data/lg_kf350_ver1.php
PHP
mit
1,705
'use strict'; const path = require('path'); const { config, paths, constants } = require('..'); test('config store is defined', () => { expect(config).toBeDefined(); }); test('config file default name', () => { expect(path.basename(config.path)).toEqual('config.json'); if (process.platform === "win32") { // https://github.com/sindresorhus/env-paths/blob/5944db4b2f8c635e8b39a363f6bdff40825be16e/index.js#L28 expect(path.basename(path.dirname(path.dirname(config.path)))).toEqual('DAISY Ace'); expect(path.basename(path.dirname(config.path))).toEqual('Config'); } else { expect(path.basename(path.dirname(config.path))).toEqual('DAISY Ace'); } }); test('paths are defined', () => { expect(paths).toBeDefined(); expect(paths.config).toBeDefined(); expect(paths.data).toBeDefined(); expect(paths.log).toBeDefined(); expect(paths.temp).toBeDefined(); }); test('constants are defined', () => { expect(constants).toBeDefined(); }); test('constants are as in constants.json', () => { expect(constants.dirname).toBe('DAISY Ace'); });
daisy/ace
packages/ace-config/src/__tests__/index.test.js
JavaScript
mit
1,074
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Orinoco Framework, a lightweight PHP framework."> <meta name="author" content="Ryan Yonzon"> <link rel="shortcut icon" href="/favicon.ico"> <title>Orinoco Framework - A lightweight PHP framework</title> </head> <body> <div><h1>Oops! An Error Occured</h1></div> <div><?= $this->renderContent() ?></div> </body> </html>
rawswift/Orinoco
src/Default/view/layout/error.php
PHP
mit
568
var LocalStrategy = require('passport-local').Strategy; var User = require('../models/user.js'); var Rider = require('../models/rider.js'); module.exports = function(passport) { passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { done(err, user); }); }); passport.use('local', new LocalStrategy( function(username, password, done) { return User.validatePassword(username, password, done); })); passport.use('signup', new LocalStrategy({ passReqToCallback: true }, function(req, username, password, done) { User.findOne(username, done, function(err, user) { if (err) return done(err); if (user) return done(null, false, { message: req.flash('error', "That username is already taken") }); else { return User.create(req.body.realname, username, password, req.body.tel, req.body.type, done); } }); })); };
arodrig1/disgo
config/passport.js
JavaScript
mit
1,048
module Clusta module Geometry class Edge < Element abbreviate 'E' key :source_label key :target_label field :weight, :optional => true def weighted? self.weight end def directed? false end def joins? label source_label == label || target_label == label end def labels_string [source_label, target_label].map(&:to_s).join(' -> ') end def source_degree Degree.new(source_label, 1) end def target_degree Degree.new(target_label, 1) end def degrees [source_degree, target_degree] end def degree_of label case label when source_label then source_degree when target_label then target_degree else raise Error.new("This edge (#{labels_string}) does not contain vertex #{label}") end end def reversed self.class.new(target_label, source_label, weight) end def neighbor Neighbor.new(target_label, weight) end end end end
strategist922/clusta
lib/clusta/geometry/edge.rb
Ruby
mit
1,123
import * as React from 'react'; import * as ReactDOM from 'react-dom'; let Dial = React.createClass({ displayName: "Dial", _normalizeDegrees(degrees) { // Normalize to a positive value between 0 and 360 return (360 + degrees) % 360; }, _getDegrees() { return this._normalizeDegrees(this.props.degrees || this.state.degrees); }, _getRotation(factor=1) { // 45 gets the arrow to the top. return 'rotate(' + (factor * (this._getDegrees() + 45)) + 'deg)' }, _onMouseDown(evt) { // We are now moving this.setState({mouseDragging: true}); evt.preventDefault(); evt.stopImmediatePropagation(); }, _onMouseMove(evt) { if (!this.state.mouseDragging) { return; } let dialRect = this.refs.dialFace.getBoundingClientRect(); let mousePos = [evt.clientX, evt.clientY]; let dialPos = [dialRect.left + dialRect.width / 2, dialRect.top + dialRect.height / 2]; let radians = Math.atan2(dialPos[1] - mousePos[1], dialPos[0] - mousePos[0]); let degrees = radians * (180 / Math.PI) - 90; // Save it internally this.setState({degrees: degrees}); // Notify parent if (this.props.onChange) { this.props.onChange(this._normalizeDegrees(degrees)); } evt.preventDefault(); evt.stopImmediatePropagation(); }, _onMouseUp(evt) { if (!this.state.mouseDragging) { return; } // We are no longer moving this.setState({mouseDragging: false}); }, getInitialState() { return {mouseDragging: false, degrees: 0}; }, componentDidMount() { window.addEventListener("mouseup", this._onMouseUp); window.addEventListener("touchend", this._onMouseUp); window.addEventListener("mousemove", this._onMouseMove); window.addEventListener("touchmove", this._onMouseMove); }, componentWillUnmount() { window.removeEventListener("mouseup", this._onMouseUp); window.removeEventListener("mousemove", this._onMouseMove); window.removeEventListener("mousemove", this._onMouseMove); window.removeEventListener("touchmove", this._onMouseMove); }, render() { return <div className="dial" onMouseDown={this._onMouseDown} onTouchStart={this._onMouseDown}> <div className="dial__chamfer"> <div className="dial__face" style={{transform: this._getRotation()}} ref="dialFace"> <div className="dial__arrow"></div> <div className="dial__inner"></div> </div> </div> <div className="dial__text"> {this.props.children} &nbsp; {(Math.abs(this._getDegrees()) / 3.6).toFixed(0)}% </div> </div> } }); export {Dial};
staab/staab.github.io
src/js/components/features.js
JavaScript
mit
3,002
module Lixian115 VERSION = "0.0.1" end
qingyan1990/115-lixian
lib/lixian115/version.rb
Ruby
mit
41
import React, { Component, PropTypes } from 'react'; import { Link } from 'react-router'; export default class App extends Component { static propTypes = { children: PropTypes.node, }; render() { return ( <div className="app"> <div className="main-container"> <div className="side-bar"> <h2><a href="https://github.com/supnate/rekit-example">Rekit Example</a></h2> <ul> <li><Link to="/rekit-example">Topic List</Link></li> <li><Link to="/rekit-example/topic/add">New Topic</Link></li> </ul> </div> <div className="page-container"> {this.props.children} </div> </div> </div> ); } }
supnate/rekit-example
src/containers/App.js
JavaScript
mit
747
package ext_animorphs; import battlecode.common.Direction; import battlecode.common.GameActionException; import battlecode.common.MapLocation; import battlecode.common.Robot; import battlecode.common.RobotController; public class Runner { public RobotController rc; public Controller c; public MapLocation cur; public Mover m; public Sensor sensor; public Runner(Controller c, Sensor sensor) { this.rc = c.rc; this.c = c; m = new Mover(c); this.sensor = sensor; } public Direction flee() throws GameActionException { cur = rc.getLocation(); // (r+2)^2 ~= r^2 + 20 if r ~ 4 if (m.inDangerRadius(cur)) { // too close to splash range return m.moveInDir(c.enemyhq.directionTo(cur)); } Robot[] en = sensor.getBots(Sensor.ATTACK_RANGE_ENEMIES); if (en.length > 0) { return fleeWeighted(en); } // en= sensor.getBots(Sensor.SENSE_RANGE_ENEMIES); // if (en.length > 0) { // return fleeWeighted(en); // } // no enemies return Direction.OMNI; } public Direction fleeWeighted(Robot[] en) throws GameActionException { Robot[] allies = sensor.getBots(Sensor.SENSE_RANGE_ALLIES); int yDir = 0; int xDir = 0; int numEnemies = en.length; int numAllies = allies.length; for (Robot e : en) { MapLocation eLoc = rc.senseRobotInfo(e).location; xDir -= eLoc.x; yDir -= eLoc.y; } for (Robot a : allies) { MapLocation aLoc = rc.senseRobotInfo(a).location; xDir += aLoc.x; yDir += aLoc.y; } xDir += numEnemies * cur.x - numAllies * cur.x; yDir += numEnemies * cur.y - numAllies * cur.y; Direction desired = cur.directionTo(cur.add(xDir, yDir)); return m.smartMove(desired); } public Direction fleeClosest(Robot[] en) throws GameActionException { MapLocation min = rc.senseLocationOf(en[0]); int minDist = min.distanceSquaredTo(cur); for (int i = 1; i < en.length; i++) { MapLocation next = rc.senseLocationOf(en[i]); int dist = next.distanceSquaredTo(cur); if (minDist < dist) { min = next; minDist = dist; } } Direction desired = cur.directionTo(min); return m.moveInDir(desired); } }
fabian-braun/reignOfDke
ext_animorphs/Runner.java
Java
mit
2,104
package pl.designpatterns.behavioral.interpreter; public class IntToHexConverter implements Interpretable { @Override public String interpret(int decimal) { return Interpreter.getInstance().getHexadecimal(decimal); } }
vego1mar/JDP
src/main/java/pl/designpatterns/behavioral/interpreter/IntToHexConverter.java
Java
mit
242