repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
Caspar12/Csharp
src/Zh.DAL.Base.NH/NHHibernateTemplate.cs
494
using System; using System.Collections.Generic; using System.Text; using Spring.Data.NHibernate.Generic; using Spring.Objects.Factory; namespace Zh.DAL.Base.NH { public class NHHibernateTemplate : HibernateTemplate, IInitializingObject { public Guid id = Guid.Empty; public void AfterPropertiesSet() { if (id == Guid.Empty) { id = Guid.NewGuid(); } base.AfterPropertiesSet(); } } }
mit
LisLo/ArTEMiS
src/main/webapp/app/account/password/password.controller.js
1077
(function() { 'use strict'; angular .module('artemisApp') .controller('PasswordController', PasswordController); PasswordController.$inject = ['Auth', 'Principal']; function PasswordController (Auth, Principal) { var vm = this; vm.changePassword = changePassword; vm.doNotMatch = null; vm.error = null; vm.success = null; Principal.identity().then(function(account) { vm.account = account; }); function changePassword () { if (vm.password !== vm.confirmPassword) { vm.error = null; vm.success = null; vm.doNotMatch = 'ERROR'; } else { vm.doNotMatch = null; Auth.changePassword(vm.password).then(function () { vm.error = null; vm.success = 'OK'; }).catch(function () { vm.success = null; vm.error = 'ERROR'; }); } } } })();
mit
ansharfirman/absensi
application/views/page/absensibulanan2.php
2927
<!-- Main content --> <section class="content"> <!-- Main row --> <div class="row"> <!-- Left col --> <div class="col-md-12"> <!-- MAP & BOX PANE --> <div class="box box-success"> <div class="box-header with-border"> <h3 class="box-title"><?php echo $title ?></h3> <div class="box-tools pull-right"> <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i> </button> <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button> </div> </div> <!-- /.box-header --> <div class="box-body"> <p> <?php $kelasId = $this->uri->segment(4); ?> <form action="<?php echo base_url('main/absensi/2/'.$kelasId) ?>" method="get" style="display: flex; position: absolute;"> <div class="input-group" style="margin-right: 10px; width: 250px;"> <input class="form-control" type="text" id="datepicker2" required placeholder="Tanggal" name="date"> <div class="input-group-btn"> <button type="submit" class="btn btn-danger">Ok</button> </div> </div> <a target="_blank" class="btn btn-warning" href="<?php echo base_url('main/printToXLS/'.$date.'/S/'.$kelasId); ?>">Print</a> </form> </p> <div class="table-responsive"> <table id="example" class="table table-bordered table-hover"> <thead> <th>No</th> <th>Nama</th> <?php foreach ($absensi['listtanggal'] as $key) { echo "<th>".$key['tanggal']."</th>"; } ?> </thead> <tbody> <?php if ($absensi['0']['NAMA']) { $x = 1; foreach ($absensi as $key) { if ($key['NAMA']) { echo " <tr> <td>".$x++."</td> <td>".$key['NAMA']."</td>"; foreach ($key['DATA'] as $key2) { if (!$key2['IN']) { echo "<td class='bg-red color-palette'></td>"; } else { echo "<td>".$key2['IN']." | ".$key2['OUT']."</td>"; } } echo "</tr>"; } } } ?> </tbody> </table> </div> </div> <!-- /.box-body --> </div> </div> <!-- /.col --> </div> <!-- /.row --> </section> <!-- /.content -->
mit
Wassasin/cloaca
src/Cloaca/EvaluationBundle/Twig/TriboolExtension.php
1025
<?php namespace Cloaca\EvaluationBundle\Twig; use Cloaca\EvaluationBundle\Types\Tribool; class TriboolExtension extends \Twig_Extension { public function getFilters() { return array( new \Twig_SimpleFilter('tribool', array($this, 'triboolFilter'), array('is_safe' => array('html'))), ); } public function triboolFilter($x, $mode='html', $bad='no') { static $strong_map = array( 'na' => Tribool::TRIBOOL_UNDETERMINED, 'no' => Tribool::TRIBOOL_NO, 'yes' => Tribool::TRIBOOL_YES ); $result = null; switch($x) { case Tribool::TRIBOOL_UNDETERMINED: $result = 'n.v.t.'; break; case Tribool::TRIBOOL_NO: $result = 'nee'; break; case Tribool::TRIBOOL_YES: $result = 'ja'; break; } if($strong_map[$bad] == $x) { switch($mode) { case 'html': return '<strong>'.$result.'</strong>'; case 'latex': return '\\textbf{'.$result.'}'; } } else { return $result; } } public function getName() { return 'tribool_extension'; } } ?>
mit
fijal/quill
nolang/objects/userobject.py
787
""" User supplied objects """ from nolang.objects.root import W_Root class W_UserObject(W_Root): def __init__(self, w_type): self.w_type = w_type self._dict_w = {} def gettype(self, space): return self.w_type def setattr(self, space, attrname, w_val): if self.w_type.force_names is not None: if attrname not in self.w_type.force_names: msg = '%s is not an allowed attribute of object of class %s' % ( attrname, self.w_type.name) raise space.apperr(space.w_attrerror, msg) self._dict_w[attrname] = w_val def getattr(self, space, attrname): try: return self._dict_w[attrname] except KeyError: return space.w_NotImplemented
mit
skidding/flatris
web/components/shared/GamePreview/GamePreview.fixture.js
525
// @flow import React from 'react'; import { getBlankGame } from 'shared/reducers/game'; import { getSampleUser } from '../../../utils/test-helpers'; import { GameContainerMock } from '../../../mocks/GameContainerMock'; import GamePreview from './GamePreview'; const user = getSampleUser(); const game = getBlankGame({ id: 'dce6b11e', user }); export default ( <GameContainerMock> <GamePreview curUser={user} game={game} onSelectP2={() => console.log('Select P2')} /> </GameContainerMock> );
mit
babestvl/FoodClash
frameworks/cocos2d-html5/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js
10707
/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ /** * cc.ProgressTimer's rendering objects of Canvas */ (function(){ cc.ProgressTimer.CanvasRenderCmd = function(renderableObject){ cc.Node.CanvasRenderCmd.call(this, renderableObject); this._needDraw = true; this._PI180 = Math.PI / 180; this._barRect = cc.rect(0, 0, 0, 0); this._origin = cc.p(0, 0); this._radius = 0; this._startAngle = 270; this._endAngle = 270; this._counterClockWise = false; }; var proto = cc.ProgressTimer.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = cc.ProgressTimer.CanvasRenderCmd; proto.rendering = function (ctx, scaleX, scaleY) { var wrapper = ctx || cc._renderContext,context = wrapper.getContext(), node = this._node, locSprite = node._sprite; var locTextureCoord = locSprite._renderCmd._textureCoord, alpha = locSprite._renderCmd._displayedOpacity / 255; if (locTextureCoord.width === 0 || locTextureCoord.height === 0) return; if (!locSprite._texture || !locTextureCoord.validRect || alpha === 0) return; wrapper.setTransform(this._worldTransform, scaleX, scaleY); wrapper.setCompositeOperation(locSprite._blendFuncStr); wrapper.setGlobalAlpha(alpha); var locRect = locSprite._rect, locOffsetPosition = locSprite._offsetPosition; var locX = locOffsetPosition.x, locY = -locOffsetPosition.y - locRect.height, locWidth = locRect.width, locHeight = locRect.height; wrapper.save(); if (locSprite._flippedX) { locX = -locX - locWidth; context.scale(-1, 1); } if (locSprite._flippedY) { locY = locOffsetPosition.y; context.scale(1, -1); } //clip if (node._type === cc.ProgressTimer.TYPE_BAR) { var locBarRect = this._barRect; context.beginPath(); context.rect(locBarRect.x * scaleX, locBarRect.y * scaleY, locBarRect.width * scaleX, locBarRect.height * scaleY); context.clip(); context.closePath(); } else if (node._type === cc.ProgressTimer.TYPE_RADIAL) { var locOriginX = this._origin.x * scaleX; var locOriginY = this._origin.y * scaleY; context.beginPath(); context.arc(locOriginX, locOriginY, this._radius * scaleY, this._PI180 * this._startAngle, this._PI180 * this._endAngle, this._counterClockWise); context.lineTo(locOriginX, locOriginY); context.clip(); context.closePath(); } //draw sprite var image = locSprite._texture.getHtmlElementObj(); if (locSprite._renderCmd._colorized) { context.drawImage(image, 0, 0, locTextureCoord.width, locTextureCoord.height, locX * scaleX, locY * scaleY, locWidth * scaleX, locHeight * scaleY); } else { context.drawImage(image, locTextureCoord.renderX, locTextureCoord.renderY, locTextureCoord.width, locTextureCoord.height, locX * scaleX, locY * scaleY, locWidth * scaleX, locHeight * scaleY); } wrapper.restore(); cc.g_NumberOfDraws++; }; proto.releaseData = function(){}; proto.initCmd = function(){}; proto._updateProgress = function(){ var node = this._node; var locSprite = node._sprite; var sw = locSprite.width, sh = locSprite.height; var locMidPoint = node._midPoint; if (node._type === cc.ProgressTimer.TYPE_RADIAL) { this._radius = Math.round(Math.sqrt(sw * sw + sh * sh)); var locStartAngle, locEndAngle, locCounterClockWise = false, locOrigin = this._origin; locOrigin.x = sw * locMidPoint.x; locOrigin.y = -sh * locMidPoint.y; if (node._reverseDirection) { locEndAngle = 270; locStartAngle = 270 - 3.6 * node._percentage; } else { locStartAngle = -90; locEndAngle = -90 + 3.6 * node._percentage; } if (locSprite._flippedX) { locOrigin.x -= sw * (node._midPoint.x * 2); locStartAngle = -locStartAngle; locEndAngle = -locEndAngle; locStartAngle -= 180; locEndAngle -= 180; locCounterClockWise = !locCounterClockWise; } if (locSprite._flippedY) { locOrigin.y += sh * (node._midPoint.y * 2); locCounterClockWise = !locCounterClockWise; locStartAngle = -locStartAngle; locEndAngle = -locEndAngle; } this._startAngle = locStartAngle; this._endAngle = locEndAngle; this._counterClockWise = locCounterClockWise; } else { var locBarChangeRate = node._barChangeRate; var percentageF = node._percentage / 100; var locBarRect = this._barRect; var drewSize = cc.size((sw * (1 - locBarChangeRate.x)), (sh * (1 - locBarChangeRate.y))); var drawingSize = cc.size((sw - drewSize.width) * percentageF, (sh - drewSize.height) * percentageF); var currentDrawSize = cc.size(drewSize.width + drawingSize.width, drewSize.height + drawingSize.height); var startPoint = cc.p(sw * locMidPoint.x, sh * locMidPoint.y); var needToLeft = startPoint.x - currentDrawSize.width / 2; if ((locMidPoint.x > 0.5) && (currentDrawSize.width / 2 >= sw - startPoint.x)) needToLeft = sw - currentDrawSize.width; var needToTop = startPoint.y - currentDrawSize.height / 2; if ((locMidPoint.y > 0.5) && (currentDrawSize.height / 2 >= sh - startPoint.y)) needToTop = sh - currentDrawSize.height; //left pos locBarRect.x = 0; var flipXNeed = 1; if (locSprite._flippedX) { locBarRect.x -= currentDrawSize.width; flipXNeed = -1; } if (needToLeft > 0) locBarRect.x += needToLeft * flipXNeed; //right pos locBarRect.y = 0; var flipYNeed = 1; if (locSprite._flippedY) { locBarRect.y += currentDrawSize.height; flipYNeed = -1; } if (needToTop > 0) locBarRect.y -= needToTop * flipYNeed; //clip width and clip height locBarRect.width = currentDrawSize.width; locBarRect.height = -currentDrawSize.height; } }; proto._updateColor = function(){}; proto._syncStatus = function (parentCmd) { var node = this._node; if(!node._sprite) return; var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; var parentNode = parentCmd ? parentCmd._node : null; if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty)) locFlag |= flags.colorDirty; if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty)) locFlag |= flags.opacityDirty; if(parentCmd && (parentCmd._dirtyFlag & flags.transformDirty)) locFlag |= flags.transformDirty; this._dirtyFlag = locFlag; var spriteCmd = node._sprite._renderCmd; var spriteFlag = spriteCmd._dirtyFlag; var colorDirty = spriteFlag & flags.colorDirty, opacityDirty = spriteFlag & flags.opacityDirty; if (colorDirty){ spriteCmd._syncDisplayColor(); } if (opacityDirty){ spriteCmd._syncDisplayOpacity(); } if(colorDirty || opacityDirty){ spriteCmd._updateColor(); //this._updateColor(); } if (locFlag & flags.transformDirty) { //update the transform this.transform(parentCmd); } if (locFlag & flags.orderDirty) { this._dirtyFlag = this._dirtyFlag & flags.orderDirty ^ this._dirtyFlag; } }; proto.updateStatus = function () { var node = this._node; if(!node._sprite) return; var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; var spriteCmd = node._sprite._renderCmd; var spriteFlag = spriteCmd._dirtyFlag; var colorDirty = spriteFlag & flags.colorDirty, opacityDirty = spriteFlag & flags.opacityDirty; if(colorDirty){ spriteCmd._updateDisplayColor(); } if(opacityDirty){ spriteCmd._updateDisplayOpacity(); } if(colorDirty || opacityDirty){ spriteCmd._updateColor(); //this._updateColor(); } if(locFlag & flags.transformDirty){ //update the transform this.transform(this.getParentRenderCmd(), true); } this._dirtyFlag = 0; }; })();
mit
jrwiegand/tdd-project
functional_tests/test_simple_list_creation.py
3198
from .base import FunctionalTest from selenium import webdriver from selenium.webdriver.common.keys import Keys class NewVisitorTest(FunctionalTest): def test_can_start_a_list_and_retrieve_it_later(self): # Edith has heard about a cool new online to-do app. She goes # to check out its homepage self.browser.get(self.server_url) # She notices the page title and header mention to-do lists self.assertIn('To-Do', self.browser.title) header_text = self.browser.find_element_by_tag_name('h1').text self.assertIn('To-Do', header_text) # She is invited to enter a to-do item straight away inputbox = self.get_item_input_box() self.assertEqual( inputbox.get_attribute('placeholder'), 'Enter a to-do item' ) # She types "Buy peacock feathers" into a text box (Edith's hobby # is tying fly-fishing lures) inputbox.send_keys('Buy peacock feathers') # When she hits enter, she is taken to a new URL, # and now the page lists "1: Buy peacock feathers" as an item in a # to-do list table inputbox.send_keys(Keys.ENTER) edith_list_url = self.browser.current_url self.assertRegex(edith_list_url, '/lists/.+') self.check_for_row_in_list_table('1: Buy peacock feathers') # There is still a text box inviting her to add another item. She # enters "Use peacock feathers to make a fly" (Edith is very # methodical) inputbox = self.get_item_input_box() inputbox.send_keys('Use peacock feathers to make a fly') inputbox.send_keys(Keys.ENTER) # The page updates again, and now shows both items on her list self.check_for_row_in_list_table( '2: Use peacock feathers to make a fly') self.check_for_row_in_list_table('1: Buy peacock feathers') # Now a new user, Francis, comes along to the site. # We use a new browser session to make sure that no information # of Edith's is coming through from cookies etc self.browser.quit() self.browser = webdriver.Firefox() # Francis visits the home page. There is no sign of Edith's # list self.browser.get(self.server_url) page_text = self.browser.find_element_by_tag_name('body').text self.assertNotIn('Buy peacock feathers', page_text) self.assertNotIn('make a fly', page_text) # Francis starts a new list by entering a new item. He # is less interesting than Edith... inputbox = self.get_item_input_box() inputbox.send_keys('Buy milk') inputbox.send_keys(Keys.ENTER) # Francis gets his own unique URL francis_list_url = self.browser.current_url self.assertRegex(francis_list_url, '/lists/.+') self.assertNotEqual(francis_list_url, edith_list_url) # Again, there is no trace of Edith's list page_text = self.browser.find_element_by_tag_name('body').text self.assertNotIn('Buy peacock feathers', page_text) self.assertIn('Buy milk', page_text) # Satisfied, they both go back to sleep
mit
metaprime/ripme
src/main/java/com/rarchives/ripme/ripper/rippers/RajceRipper.java
2051
package com.rarchives.ripme.ripper.rippers; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import com.rarchives.ripme.ripper.AbstractHTMLRipper; import com.rarchives.ripme.utils.Http; public class RajceRipper extends AbstractHTMLRipper { private static final String DOMAIN = "rajce.idnes.cz"; private static final String HOST = "rajce.idnes"; public RajceRipper(URL url) throws IOException { super(url); } @Override public String getHost() { return HOST; } @Override public String getDomain() { return DOMAIN; } @Override public String getGID(URL url) throws MalformedURLException { Pattern p = Pattern.compile("^https?://([^.]+)\\.rajce\\.idnes\\.cz/(([^/]+)/.*)?$"); Matcher m = p.matcher(url.toExternalForm()); if (!m.matches()) { throw new MalformedURLException("Unsupported URL format: " + url.toExternalForm()); } String user = m.group(1); String album = m.group(3); if (album == null) { throw new MalformedURLException("Unsupported URL format (not an album): " + url.toExternalForm()); } return user + "/" + album; } @Override public Document getFirstPage() throws IOException { return Http.url(url).get(); } @Override public Document getNextPage(Document doc) throws IOException { return super.getNextPage(doc); } @Override public List<String> getURLsFromPage(Document page) { List<String> result = new ArrayList<>(); for (Element el : page.select("a.photoThumb")) { result.add(el.attr("href")); } return result; } @Override public void downloadURL(URL url, int index) { addURLToDownload(url, getPrefix(index)); } }
mit
haohangxu/haohangxu.github.io
js/main.js
1636
--- layout: null sitemap: exclude: 'yes' --- function showBlog() { $('.about').hide() $('.words').show() } function showAbout() { $('.about').show() $('.words').hide() } var buttonActions = { 'blog-button': showBlog, 'about-button': showAbout, } $(document).ready(function () { $('#blog-link').click(function (e) { showBlog() }) for (var buttonClass in buttonActions) { $('a.' + buttonClass).click(function (e) { buttonActions[e.target.className]() if ($('.panel-cover').hasClass('panel-cover--collapsed')) return currentWidth = $('.panel-cover').width() if (currentWidth < 960) { $('.panel-cover').addClass('panel-cover--collapsed') } else { $('.panel-cover').css('max-width', currentWidth) $('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {}) } }) } if (window.location.pathname !== '{{ site.baseurl }}/' && window.location.pathname !== '{{ site.baseurl }}/index.html') { $('.panel-cover').addClass('panel-cover--collapsed') } $('.btn-mobile-menu').click(function () { $('.navigation-wrapper').toggleClass('visible animated slideIn') $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle fadeIn') }) for (var buttonClass in buttonActions) { $('.navigation-wrapper .' + buttonClass).click(function () { $('.navigation-wrapper').toggleClass('visible') $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn') }) } })
mit
antw/iniparse
spec/parser/line_parsing_spec.rb
11808
require 'spec_helper' # Tests parsing of individual, out of context, line types using #parse_line. describe 'Parsing a line' do it 'should strip leading whitespace and set the :indent option' do expect(IniParse::Parser.parse_line(' [section]')).to \ be_section_tuple(:any, {:indent => ' '}) end it 'should raise an error if the line could not be matched' do expect { IniParse::Parser.parse_line('invalid line') }.to \ raise_error(IniParse::ParseError) end it 'should parse using the types set in IniParse::Parser.parse_types' do begin # Remove last type. type = IniParse::Parser.parse_types.pop expect(type).not_to receive(:parse) IniParse::Parser.parse_line('[section]') ensure IniParse::Parser.parse_types << type end end # -- # ========================================================================== # Option lines. # ========================================================================== # ++ describe 'with "k = v"' do before(:all) do @tuple = IniParse::Parser.parse_line('k = v') end it 'should return an option tuple' do expect(@tuple).to be_option_tuple('k', 'v') end it 'should set no indent, comment, offset or separator' do expect(@tuple.last[:indent]).to be_nil expect(@tuple.last[:comment]).to be_nil expect(@tuple.last[:comment_offset]).to be_nil expect(@tuple.last[:comment_sep]).to be_nil end end describe 'with "k = a value with spaces"' do it 'should return an option tuple' do expect(IniParse::Parser.parse_line('k = a value with spaces')).to \ be_option_tuple('k', 'a value with spaces') end end describe 'with "k = v ; a comment "' do before(:all) do @tuple = IniParse::Parser.parse_line('k = v ; a comment') end it 'should return an option tuple' do expect(@tuple).to be_option_tuple('k', 'v') end it 'should set the comment to "a comment"' do expect(@tuple).to be_option_tuple(:any, :any, :comment => 'a comment') end it 'should set the comment separator to ";"' do expect(@tuple).to be_option_tuple(:any, :any, :comment_sep => ';') end it 'should set the comment offset to 6' do expect(@tuple).to be_option_tuple(:any, :any, :comment_offset => 6) end end describe 'with "k = v;w;x y;z"' do before(:all) do @tuple = IniParse::Parser.parse_line('k = v;w;x y;z') end it 'should return an option tuple with the correct value' do expect(@tuple).to be_option_tuple(:any, 'v;w;x y;z') end it 'should not set a comment' do expect(@tuple.last[:comment]).to be_nil expect(@tuple.last[:comment_offset]).to be_nil expect(@tuple.last[:comment_sep]).to be_nil end end describe 'with "k = v;w ; a comment"' do before(:all) do @tuple = IniParse::Parser.parse_line('k = v;w ; a comment') end it 'should return an option tuple with the correct value' do expect(@tuple).to be_option_tuple(:any, 'v;w') end it 'should set the comment to "a comment"' do expect(@tuple).to be_option_tuple(:any, :any, :comment => 'a comment') end it 'should set the comment separator to ";"' do expect(@tuple).to be_option_tuple(:any, :any, :comment_sep => ';') end it 'should set the comment offset to 8' do expect(@tuple).to be_option_tuple(:any, :any, :comment_offset => 8) end end describe 'with "key=value"' do it 'should return an option tuple with the correct key and value' do expect(IniParse::Parser.parse_line('key=value')).to \ be_option_tuple('key', 'value') end end describe 'with "key= value"' do it 'should return an option tuple with the correct key and value' do expect(IniParse::Parser.parse_line('key= value')).to \ be_option_tuple('key', 'value') end end describe 'with "key =value"' do it 'should return an option tuple with the correct key and value' do expect(IniParse::Parser.parse_line('key =value')).to \ be_option_tuple('key', 'value') end end describe 'with "key = value"' do it 'should return an option tuple with the correct key and value' do expect(IniParse::Parser.parse_line('key = value')).to \ be_option_tuple('key', 'value') end end describe 'with "key ="' do it 'should return an option tuple with the correct key' do expect(IniParse::Parser.parse_line('key =')).to \ be_option_tuple('key') end it 'should set the option value to nil' do expect(IniParse::Parser.parse_line('key =')).to \ be_option_tuple(:any, nil) end end describe 'with "key = EEjDDJJjDJDJD233232=="' do it 'should include the "equals" in the option value' do expect(IniParse::Parser.parse_line('key = EEjDDJJjDJDJD233232==')).to \ be_option_tuple('key', 'EEjDDJJjDJDJD233232==') end end describe 'with "key = ==EEjDDJJjDJDJD233232"' do it 'should include the "equals" in the option value' do expect(IniParse::Parser.parse_line('key = ==EEjDDJJjDJDJD233232')).to \ be_option_tuple('key', '==EEjDDJJjDJDJD233232') end end describe 'with "key.two = value"' do it 'should return an option tuple with the correct key' do expect(IniParse::Parser.parse_line('key.two = value')).to \ be_option_tuple('key.two') end end describe 'with "key/with/slashes = value"' do it 'should return an option tuple with the correct key' do expect(IniParse::Parser.parse_line('key/with/slashes = value')).to \ be_option_tuple('key/with/slashes', 'value') end end describe 'with "key_with_underscores = value"' do it 'should return an option tuple with the correct key' do expect(IniParse::Parser.parse_line('key_with_underscores = value')).to \ be_option_tuple('key_with_underscores', 'value') end end describe 'with "key-with-dashes = value"' do it 'should return an option tuple with the correct key' do expect(IniParse::Parser.parse_line('key-with-dashes = value')).to \ be_option_tuple('key-with-dashes', 'value') end end describe 'with "key with spaces = value"' do it 'should return an option tuple with the correct key' do expect(IniParse::Parser.parse_line('key with spaces = value')).to \ be_option_tuple('key with spaces', 'value') end end # -- # ========================================================================== # Section lines. # ========================================================================== # ++ describe 'with "[section]"' do before(:all) do @tuple = IniParse::Parser.parse_line('[section]') end it 'should return a section tuple' do expect(@tuple).to be_section_tuple('section') end it 'should set no indent, comment, offset or separator' do expect(@tuple.last[:indent]).to be_nil expect(@tuple.last[:comment]).to be_nil expect(@tuple.last[:comment_offset]).to be_nil expect(@tuple.last[:comment_sep]).to be_nil end end describe 'with "[section with whitespace]"' do it 'should return a section tuple with the correct key' do expect(IniParse::Parser.parse_line('[section with whitespace]')).to \ be_section_tuple('section with whitespace') end end describe 'with "[ section with surounding whitespace ]"' do it 'should return a section tuple with the correct key' do expect(IniParse::Parser.parse_line('[ section with surounding whitespace ]')).to \ be_section_tuple(' section with surounding whitespace ') end end describe 'with "[section] ; a comment"' do before(:all) do @tuple = IniParse::Parser.parse_line('[section] ; a comment') end it 'should return a section tuple' do expect(@tuple).to be_section_tuple('section') end it 'should set the comment to "a comment"' do expect(@tuple).to be_section_tuple(:any, :comment => 'a comment') end it 'should set the comment separator to ";"' do expect(@tuple).to be_section_tuple(:any, :comment_sep => ';') end it 'should set the comment offset to 10' do expect(@tuple).to be_section_tuple(:any, :comment_offset => 10) end end describe 'with "[section;with#comment;chars]"' do before(:all) do @tuple = IniParse::Parser.parse_line('[section;with#comment;chars]') end it 'should return a section tuple with the correct key' do expect(@tuple).to be_section_tuple('section;with#comment;chars') end it 'should not set a comment' do expect(@tuple.last[:indent]).to be_nil expect(@tuple.last[:comment]).to be_nil expect(@tuple.last[:comment_offset]).to be_nil expect(@tuple.last[:comment_sep]).to be_nil end end describe 'with "[section;with#comment;chars] ; a comment"' do before(:all) do @tuple = IniParse::Parser.parse_line('[section;with#comment;chars] ; a comment') end it 'should return a section tuple with the correct key' do expect(@tuple).to be_section_tuple('section;with#comment;chars') end it 'should set the comment to "a comment"' do expect(@tuple).to be_section_tuple(:any, :comment => 'a comment') end it 'should set the comment separator to ";"' do expect(@tuple).to be_section_tuple(:any, :comment_sep => ';') end it 'should set the comment offset to 29' do expect(@tuple).to be_section_tuple(:any, :comment_offset => 29) end end # -- # ========================================================================== # Comment lines. # ========================================================================== # ++ describe 'with "; a comment"' do before(:all) do @tuple = IniParse::Parser.parse_line('; a comment') end it 'should return a comment tuple with the correct comment' do expect(@tuple).to be_comment_tuple('a comment') end it 'should set the comment separator to ";"' do expect(@tuple).to be_comment_tuple(:any, :comment_sep => ';') end it 'should set the comment offset to 0' do expect(@tuple).to be_comment_tuple(:any, :comment_offset => 0) end end describe 'with " ; a comment"' do before(:all) do @tuple = IniParse::Parser.parse_line(' ; a comment') end it 'should return a comment tuple with the correct comment' do expect(@tuple).to be_comment_tuple('a comment') end it 'should set the comment separator to ";"' do expect(@tuple).to be_comment_tuple(:any, :comment_sep => ';') end it 'should set the comment offset to 1' do expect(@tuple).to be_comment_tuple(:any, :comment_offset => 1) end end describe 'with ";"' do before(:all) do @tuple = IniParse::Parser.parse_line(';') end it 'should return a comment tuple with an empty value' do expect(@tuple).to be_comment_tuple('') end it 'should set the comment separator to ";"' do expect(@tuple).to be_comment_tuple(:any, :comment_sep => ';') end it 'should set the comment offset to 0' do expect(@tuple).to be_comment_tuple(:any, :comment_offset => 0) end end # -- # ========================================================================== # Blank lines. # ========================================================================== # ++ describe 'with ""' do it 'should return a blank tuple' do expect(IniParse::Parser.parse_line('')).to be_blank_tuple end end describe 'with " "' do it 'should return a blank tuple' do expect(IniParse::Parser.parse_line(' ')).to be_blank_tuple end end end
mit
hgminerva/innosoftph-ui
wijmo/NpmImages/wijmo-commonjs-min/wijmo.angular2.chart.js
21238
/* * * Wijmo Library 5.20163.254 * http://wijmo.com/ * * Copyright(c) GrapeCity, Inc. All rights reserved. * * Licensed under the Wijmo Commercial License. * [email protected] * http://wijmo.com/products/wijmo-5/license/ * */ "use strict"; var __extends=this && this.__extends || function(d, b) { function __() { this.constructor = d } for (var p in b) b.hasOwnProperty(p) && (d[p] = b[p]); d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __) }, wjcChart=require('wijmo/wijmo.chart'), core_1=require('@angular/core'), core_2=require('@angular/core'), core_3=require('@angular/core'), common_1=require('@angular/common'), forms_1=require('@angular/forms'), wijmo_angular2_directiveBase_1=require('wijmo/wijmo.angular2.directiveBase'), wjFlexChart_outputs=['initialized', 'gotFocusNg: gotFocus', 'lostFocusNg: lostFocus', 'renderingNg: rendering', 'renderedNg: rendered', 'seriesVisibilityChangedNg: seriesVisibilityChanged', 'selectionChangedNg: selectionChanged', 'selectionChangePC: selectionChange', ], WjFlexChart=function(_super) { function WjFlexChart(elRef, injector, parentCmp) { _super.call(this, wijmo_angular2_directiveBase_1.WjDirectiveBehavior.getHostElement(elRef)); this.isInitialized = !1; this.initialized = new core_1.EventEmitter(!0); this.gotFocusNg = new core_1.EventEmitter(!1); this.lostFocusNg = new core_1.EventEmitter(!1); this.renderingNg = new core_1.EventEmitter(!1); this.renderedNg = new core_1.EventEmitter(!1); this.seriesVisibilityChangedNg = new core_1.EventEmitter(!1); this.selectionChangedNg = new core_1.EventEmitter(!1); this.selectionChangePC = new core_1.EventEmitter(!1); var behavior=this._wjBehaviour = wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector, parentCmp) } return __extends(WjFlexChart, _super), WjFlexChart.prototype.ngOnInit = function() { this._wjBehaviour.ngOnInit() }, WjFlexChart.prototype.ngAfterViewInit = function() { this._wjBehaviour.ngAfterViewInit() }, WjFlexChart.prototype.ngOnDestroy = function() { this._wjBehaviour.ngOnDestroy() }, Object.defineProperty(WjFlexChart.prototype, "tooltipContent", { get: function() { return this.tooltip.content }, set: function(value) { this.tooltip.content = value }, enumerable: !0, configurable: !0 }), Object.defineProperty(WjFlexChart.prototype, "labelContent", { get: function() { return this.dataLabel.content }, set: function(value) { this.dataLabel.content = value }, enumerable: !0, configurable: !0 }), WjFlexChart.meta = { outputs: wjFlexChart_outputs, changeEvents: {selectionChanged: ['selection']} }, WjFlexChart.decorators = [{ type: core_1.Component, args: [{ selector: 'wj-flex-chart', template: "<div><ng-content></ng-content></div>", inputs: ['wjModelProperty', 'isDisabled', 'binding', 'footer', 'header', 'selectionMode', 'palette', 'plotMargin', 'footerStyle', 'headerStyle', 'tooltipContent', 'itemsSource', 'bindingX', 'interpolateNulls', 'legendToggle', 'symbolSize', 'options', 'selection', 'itemFormatter', 'labelContent', 'chartType', 'rotated', 'stacking', ], outputs: wjFlexChart_outputs, providers: [{ provide: 'WjComponent', useExisting: core_2.forwardRef(function() { return WjFlexChart }) }, { provide: forms_1.NG_VALUE_ACCESSOR, useFactory: wijmo_angular2_directiveBase_1.WjValueAccessorFactory, multi: !0, deps: ['WjComponent'] }] }, ] }, ], WjFlexChart.ctorParameters = [{ type: core_2.ElementRef, decorators: [{ type: core_3.Inject, args: [core_2.ElementRef, ] }, ] }, { type: core_2.Injector, decorators: [{ type: core_3.Inject, args: [core_2.Injector, ] }, ] }, { type: undefined, decorators: [{ type: core_3.Inject, args: ['WjComponent', ] }, {type: core_3.SkipSelf}, {type: core_2.Optional}, ] }, ], WjFlexChart }(wjcChart.FlexChart), wjFlexPie_outputs, WjFlexPie, wjFlexChartAxis_outputs, WjFlexChartAxis, wjFlexChartLegend_outputs, WjFlexChartLegend, wjFlexChartDataLabel_outputs, WjFlexChartDataLabel, wjFlexPieDataLabel_outputs, WjFlexPieDataLabel, wjFlexChartSeries_outputs, WjFlexChartSeries, wjFlexChartLineMarker_outputs, WjFlexChartLineMarker, wjFlexChartDataPoint_outputs, WjFlexChartDataPoint, wjFlexChartPlotArea_outputs, WjFlexChartPlotArea, moduleExports, WjChartModule; exports.WjFlexChart = WjFlexChart; wjFlexPie_outputs = ['initialized', 'gotFocusNg: gotFocus', 'lostFocusNg: lostFocus', 'renderingNg: rendering', 'renderedNg: rendered', ]; WjFlexPie = function(_super) { function WjFlexPie(elRef, injector, parentCmp) { _super.call(this, wijmo_angular2_directiveBase_1.WjDirectiveBehavior.getHostElement(elRef)); this.isInitialized = !1; this.initialized = new core_1.EventEmitter(!0); this.gotFocusNg = new core_1.EventEmitter(!1); this.lostFocusNg = new core_1.EventEmitter(!1); this.renderingNg = new core_1.EventEmitter(!1); this.renderedNg = new core_1.EventEmitter(!1); var behavior=this._wjBehaviour = wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector, parentCmp) } return __extends(WjFlexPie, _super), WjFlexPie.prototype.ngOnInit = function() { this._wjBehaviour.ngOnInit() }, WjFlexPie.prototype.ngAfterViewInit = function() { this._wjBehaviour.ngAfterViewInit() }, WjFlexPie.prototype.ngOnDestroy = function() { this._wjBehaviour.ngOnDestroy() }, Object.defineProperty(WjFlexPie.prototype, "tooltipContent", { get: function() { return this.tooltip.content }, set: function(value) { this.tooltip.content = value }, enumerable: !0, configurable: !0 }), Object.defineProperty(WjFlexPie.prototype, "labelContent", { get: function() { return this.dataLabel.content }, set: function(value) { this.dataLabel.content = value }, enumerable: !0, configurable: !0 }), WjFlexPie.meta = {outputs: wjFlexPie_outputs}, WjFlexPie.decorators = [{ type: core_1.Component, args: [{ selector: 'wj-flex-pie', template: "<div><ng-content></ng-content></div>", inputs: ['wjModelProperty', 'isDisabled', 'binding', 'footer', 'header', 'selectionMode', 'palette', 'plotMargin', 'footerStyle', 'headerStyle', 'tooltipContent', 'itemsSource', 'bindingName', 'innerRadius', 'isAnimated', 'offset', 'reversed', 'startAngle', 'selectedItemPosition', 'selectedItemOffset', 'itemFormatter', 'labelContent', ], outputs: wjFlexPie_outputs, providers: [{ provide: 'WjComponent', useExisting: core_2.forwardRef(function() { return WjFlexPie }) }, { provide: forms_1.NG_VALUE_ACCESSOR, useFactory: wijmo_angular2_directiveBase_1.WjValueAccessorFactory, multi: !0, deps: ['WjComponent'] }] }, ] }, ], WjFlexPie.ctorParameters = [{ type: core_2.ElementRef, decorators: [{ type: core_3.Inject, args: [core_2.ElementRef, ] }, ] }, { type: core_2.Injector, decorators: [{ type: core_3.Inject, args: [core_2.Injector, ] }, ] }, { type: undefined, decorators: [{ type: core_3.Inject, args: ['WjComponent', ] }, {type: core_3.SkipSelf}, {type: core_2.Optional}, ] }, ], WjFlexPie }(wjcChart.FlexPie); exports.WjFlexPie = WjFlexPie; wjFlexChartAxis_outputs = ['initialized', 'rangeChangedNg: rangeChanged', ]; WjFlexChartAxis = function(_super) { function WjFlexChartAxis(elRef, injector, parentCmp) { _super.call(this); this.isInitialized = !1; this.initialized = new core_1.EventEmitter(!0); this.wjProperty = 'axes'; this.rangeChangedNg = new core_1.EventEmitter(!1); var behavior=this._wjBehaviour = wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector, parentCmp) } return __extends(WjFlexChartAxis, _super), WjFlexChartAxis.prototype.ngOnInit = function() { this._wjBehaviour.ngOnInit() }, WjFlexChartAxis.prototype.ngAfterViewInit = function() { this._wjBehaviour.ngAfterViewInit() }, WjFlexChartAxis.prototype.ngOnDestroy = function() { this._wjBehaviour.ngOnDestroy() }, WjFlexChartAxis.meta = {outputs: wjFlexChartAxis_outputs}, WjFlexChartAxis.decorators = [{ type: core_1.Component, args: [{ selector: 'wj-flex-chart-axis', template: "", inputs: ['wjProperty', 'axisLine', 'format', 'labels', 'majorGrid', 'majorTickMarks', 'majorUnit', 'max', 'min', 'position', 'reversed', 'title', 'labelAngle', 'minorGrid', 'minorTickMarks', 'minorUnit', 'origin', 'logBase', 'plotArea', 'labelAlign', 'name', 'overlappingLabels', 'labelPadding', 'itemFormatter', 'itemsSource', 'binding', ], outputs: wjFlexChartAxis_outputs, providers: [{ provide: 'WjComponent', useExisting: core_2.forwardRef(function() { return WjFlexChartAxis }) }, ] }, ] }, ], WjFlexChartAxis.ctorParameters = [{ type: core_2.ElementRef, decorators: [{ type: core_3.Inject, args: [core_2.ElementRef, ] }, ] }, { type: core_2.Injector, decorators: [{ type: core_3.Inject, args: [core_2.Injector, ] }, ] }, { type: undefined, decorators: [{ type: core_3.Inject, args: ['WjComponent', ] }, {type: core_3.SkipSelf}, {type: core_2.Optional}, ] }, ], WjFlexChartAxis }(wjcChart.Axis); exports.WjFlexChartAxis = WjFlexChartAxis; wjFlexChartLegend_outputs = ['initialized', ]; WjFlexChartLegend = function(_super) { function WjFlexChartLegend(elRef, injector, parentCmp) { _super.call(this, parentCmp); this.isInitialized = !1; this.initialized = new core_1.EventEmitter(!0); this.wjProperty = 'legend'; var behavior=this._wjBehaviour = wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector, parentCmp) } return __extends(WjFlexChartLegend, _super), WjFlexChartLegend.prototype.ngOnInit = function() { this._wjBehaviour.ngOnInit() }, WjFlexChartLegend.prototype.ngAfterViewInit = function() { this._wjBehaviour.ngAfterViewInit() }, WjFlexChartLegend.prototype.ngOnDestroy = function() { this._wjBehaviour.ngOnDestroy() }, WjFlexChartLegend.meta = {outputs: wjFlexChartLegend_outputs}, WjFlexChartLegend.decorators = [{ type: core_1.Component, args: [{ selector: 'wj-flex-chart-legend', template: "", inputs: ['wjProperty', 'position', ], outputs: wjFlexChartLegend_outputs, providers: [{ provide: 'WjComponent', useExisting: core_2.forwardRef(function() { return WjFlexChartLegend }) }, ] }, ] }, ], WjFlexChartLegend.ctorParameters = [{ type: core_2.ElementRef, decorators: [{ type: core_3.Inject, args: [core_2.ElementRef, ] }, ] }, { type: core_2.Injector, decorators: [{ type: core_3.Inject, args: [core_2.Injector, ] }, ] }, { type: undefined, decorators: [{ type: core_3.Inject, args: ['WjComponent', ] }, {type: core_3.SkipSelf}, {type: core_2.Optional}, ] }, ], WjFlexChartLegend }(wjcChart.Legend); exports.WjFlexChartLegend = WjFlexChartLegend; wjFlexChartDataLabel_outputs = ['initialized', ]; WjFlexChartDataLabel = function(_super) { function WjFlexChartDataLabel(elRef, injector, parentCmp) { _super.call(this); this.isInitialized = !1; this.initialized = new core_1.EventEmitter(!0); this.wjProperty = 'dataLabel'; var behavior=this._wjBehaviour = wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector, parentCmp) } return __extends(WjFlexChartDataLabel, _super), WjFlexChartDataLabel.prototype.ngOnInit = function() { this._wjBehaviour.ngOnInit() }, WjFlexChartDataLabel.prototype.ngAfterViewInit = function() { this._wjBehaviour.ngAfterViewInit() }, WjFlexChartDataLabel.prototype.ngOnDestroy = function() { this._wjBehaviour.ngOnDestroy() }, WjFlexChartDataLabel.meta = {outputs: wjFlexChartDataLabel_outputs}, WjFlexChartDataLabel.decorators = [{ type: core_1.Component, args: [{ selector: 'wj-flex-chart-data-label', template: "", inputs: ['wjProperty', 'content', 'border', 'position', ], outputs: wjFlexChartDataLabel_outputs, providers: [{ provide: 'WjComponent', useExisting: core_2.forwardRef(function() { return WjFlexChartDataLabel }) }, ] }, ] }, ], WjFlexChartDataLabel.ctorParameters = [{ type: core_2.ElementRef, decorators: [{ type: core_3.Inject, args: [core_2.ElementRef, ] }, ] }, { type: core_2.Injector, decorators: [{ type: core_3.Inject, args: [core_2.Injector, ] }, ] }, { type: undefined, decorators: [{ type: core_3.Inject, args: ['WjComponent', ] }, {type: core_3.SkipSelf}, {type: core_2.Optional}, ] }, ], WjFlexChartDataLabel }(wjcChart.DataLabel); exports.WjFlexChartDataLabel = WjFlexChartDataLabel; wjFlexPieDataLabel_outputs = ['initialized', ]; WjFlexPieDataLabel = function(_super) { function WjFlexPieDataLabel(elRef, injector, parentCmp) { _super.call(this); this.isInitialized = !1; this.initialized = new core_1.EventEmitter(!0); this.wjProperty = 'dataLabel'; var behavior=this._wjBehaviour = wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector, parentCmp) } return __extends(WjFlexPieDataLabel, _super), WjFlexPieDataLabel.prototype.ngOnInit = function() { this._wjBehaviour.ngOnInit() }, WjFlexPieDataLabel.prototype.ngAfterViewInit = function() { this._wjBehaviour.ngAfterViewInit() }, WjFlexPieDataLabel.prototype.ngOnDestroy = function() { this._wjBehaviour.ngOnDestroy() }, WjFlexPieDataLabel.meta = {outputs: wjFlexPieDataLabel_outputs}, WjFlexPieDataLabel.decorators = [{ type: core_1.Component, args: [{ selector: 'wj-flex-pie-data-label', template: "", inputs: ['wjProperty', 'content', 'border', 'position', ], outputs: wjFlexPieDataLabel_outputs, providers: [{ provide: 'WjComponent', useExisting: core_2.forwardRef(function() { return WjFlexPieDataLabel }) }, ] }, ] }, ], WjFlexPieDataLabel.ctorParameters = [{ type: core_2.ElementRef, decorators: [{ type: core_3.Inject, args: [core_2.ElementRef, ] }, ] }, { type: core_2.Injector, decorators: [{ type: core_3.Inject, args: [core_2.Injector, ] }, ] }, { type: undefined, decorators: [{ type: core_3.Inject, args: ['WjComponent', ] }, {type: core_3.SkipSelf}, {type: core_2.Optional}, ] }, ], WjFlexPieDataLabel }(wjcChart.PieDataLabel); exports.WjFlexPieDataLabel = WjFlexPieDataLabel; wjFlexChartSeries_outputs = ['initialized', 'renderingNg: rendering', 'renderedNg: rendered', 'visibilityChangePC: visibilityChange', ]; WjFlexChartSeries = function(_super) { function WjFlexChartSeries(elRef, injector, parentCmp) { _super.call(this); this.isInitialized = !1; this.initialized = new core_1.EventEmitter(!0); this.wjProperty = 'series'; this.renderingNg = new core_1.EventEmitter(!1); this.renderedNg = new core_1.EventEmitter(!1); this.visibilityChangePC = new core_1.EventEmitter(!1); var behavior=this._wjBehaviour = wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector, parentCmp) } return __extends(WjFlexChartSeries, _super), WjFlexChartSeries.prototype.ngOnInit = function() { this._wjBehaviour.ngOnInit() }, WjFlexChartSeries.prototype.ngAfterViewInit = function() { this._wjBehaviour.ngAfterViewInit() }, WjFlexChartSeries.prototype.ngOnDestroy = function() { this._wjBehaviour.ngOnDestroy() }, WjFlexChartSeries.meta = { outputs: wjFlexChartSeries_outputs, changeEvents: {'chart.seriesVisibilityChanged': ['visibility']}, siblingId: 'series' }, WjFlexChartSeries.decorators = [{ type: core_1.Component, args: [{ selector: 'wj-flex-chart-series', template: "<div><ng-content></ng-content></div>", inputs: ['wjProperty', 'axisX', 'axisY', 'binding', 'bindingX', 'cssClass', 'name', 'style', 'altStyle', 'symbolMarker', 'symbolSize', 'symbolStyle', 'visibility', 'itemsSource', 'chartType', ], outputs: wjFlexChartSeries_outputs, providers: [{ provide: 'WjComponent', useExisting: core_2.forwardRef(function() { return WjFlexChartSeries }) }, ] }, ] }, ], WjFlexChartSeries.ctorParameters = [{ type: core_2.ElementRef, decorators: [{ type: core_3.Inject, args: [core_2.ElementRef, ] }, ] }, { type: core_2.Injector, decorators: [{ type: core_3.Inject, args: [core_2.Injector, ] }, ] }, { type: undefined, decorators: [{ type: core_3.Inject, args: ['WjComponent', ] }, {type: core_3.SkipSelf}, {type: core_2.Optional}, ] }, ], WjFlexChartSeries }(wjcChart.Series); exports.WjFlexChartSeries = WjFlexChartSeries; wjFlexChartLineMarker_outputs = ['initialized', 'positionChangedNg: positionChanged', ]; WjFlexChartLineMarker = function(_super) { function WjFlexChartLineMarker(elRef, injector, parentCmp) { _super.call(this, parentCmp); this.isInitialized = !1; this.initialized = new core_1.EventEmitter(!0); this.positionChangedNg = new core_1.EventEmitter(!1); var behavior=this._wjBehaviour = wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector, parentCmp) } return __extends(WjFlexChartLineMarker, _super), WjFlexChartLineMarker.prototype.ngOnInit = function() { this._wjBehaviour.ngOnInit() }, WjFlexChartLineMarker.prototype.ngAfterViewInit = function() { this._wjBehaviour.ngAfterViewInit() }, WjFlexChartLineMarker.prototype.ngOnDestroy = function() { this._wjBehaviour.ngOnDestroy() }, WjFlexChartLineMarker.meta = {outputs: wjFlexChartLineMarker_outputs}, WjFlexChartLineMarker.decorators = [{ type: core_1.Component, args: [{ selector: 'wj-flex-line-marker', template: "", inputs: ['wjProperty', 'isVisible', 'seriesIndex', 'horizontalPosition', 'content', 'verticalPosition', 'alignment', 'lines', 'interaction', 'dragLines', 'dragThreshold', 'dragContent', ], outputs: wjFlexChartLineMarker_outputs, providers: [{ provide: 'WjComponent', useExisting: core_2.forwardRef(function() { return WjFlexChartLineMarker }) }, ] }, ] }, ], WjFlexChartLineMarker.ctorParameters = [{ type: core_2.ElementRef, decorators: [{ type: core_3.Inject, args: [core_2.ElementRef, ] }, ] }, { type: core_2.Injector, decorators: [{ type: core_3.Inject, args: [core_2.Injector, ] }, ] }, { type: undefined, decorators: [{ type: core_3.Inject, args: ['WjComponent', ] }, {type: core_3.SkipSelf}, {type: core_2.Optional}, ] }, ], WjFlexChartLineMarker }(wjcChart.LineMarker); exports.WjFlexChartLineMarker = WjFlexChartLineMarker; wjFlexChartDataPoint_outputs = ['initialized', ]; WjFlexChartDataPoint = function(_super) { function WjFlexChartDataPoint(elRef, injector, parentCmp) { _super.call(this); this.isInitialized = !1; this.initialized = new core_1.EventEmitter(!0); this.wjProperty = ''; var behavior=this._wjBehaviour = wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector, parentCmp) } return __extends(WjFlexChartDataPoint, _super), WjFlexChartDataPoint.prototype.ngOnInit = function() { this._wjBehaviour.ngOnInit() }, WjFlexChartDataPoint.prototype.ngAfterViewInit = function() { this._wjBehaviour.ngAfterViewInit() }, WjFlexChartDataPoint.prototype.ngOnDestroy = function() { this._wjBehaviour.ngOnDestroy() }, WjFlexChartDataPoint.meta = {outputs: wjFlexChartDataPoint_outputs}, WjFlexChartDataPoint.decorators = [{ type: core_1.Component, args: [{ selector: 'wj-flex-chart-data-point', template: "", inputs: ['wjProperty', 'x', 'y', ], outputs: wjFlexChartDataPoint_outputs, providers: [{ provide: 'WjComponent', useExisting: core_2.forwardRef(function() { return WjFlexChartDataPoint }) }, ] }, ] }, ], WjFlexChartDataPoint.ctorParameters = [{ type: core_2.ElementRef, decorators: [{ type: core_3.Inject, args: [core_2.ElementRef, ] }, ] }, { type: core_2.Injector, decorators: [{ type: core_3.Inject, args: [core_2.Injector, ] }, ] }, { type: undefined, decorators: [{ type: core_3.Inject, args: ['WjComponent', ] }, {type: core_3.SkipSelf}, {type: core_2.Optional}, ] }, ], WjFlexChartDataPoint }(wjcChart.DataPoint); exports.WjFlexChartDataPoint = WjFlexChartDataPoint; wjFlexChartPlotArea_outputs = ['initialized', ]; WjFlexChartPlotArea = function(_super) { function WjFlexChartPlotArea(elRef, injector, parentCmp) { _super.call(this); this.isInitialized = !1; this.initialized = new core_1.EventEmitter(!0); this.wjProperty = 'plotAreas'; var behavior=this._wjBehaviour = wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector, parentCmp) } return __extends(WjFlexChartPlotArea, _super), WjFlexChartPlotArea.prototype.ngOnInit = function() { this._wjBehaviour.ngOnInit() }, WjFlexChartPlotArea.prototype.ngAfterViewInit = function() { this._wjBehaviour.ngAfterViewInit() }, WjFlexChartPlotArea.prototype.ngOnDestroy = function() { this._wjBehaviour.ngOnDestroy() }, WjFlexChartPlotArea.meta = {outputs: wjFlexChartPlotArea_outputs}, WjFlexChartPlotArea.decorators = [{ type: core_1.Component, args: [{ selector: 'wj-flex-chart-plot-area', template: "", inputs: ['wjProperty', 'column', 'height', 'name', 'row', 'style', 'width', ], outputs: wjFlexChartPlotArea_outputs, providers: [{ provide: 'WjComponent', useExisting: core_2.forwardRef(function() { return WjFlexChartPlotArea }) }, ] }, ] }, ], WjFlexChartPlotArea.ctorParameters = [{ type: core_2.ElementRef, decorators: [{ type: core_3.Inject, args: [core_2.ElementRef, ] }, ] }, { type: core_2.Injector, decorators: [{ type: core_3.Inject, args: [core_2.Injector, ] }, ] }, { type: undefined, decorators: [{ type: core_3.Inject, args: ['WjComponent', ] }, {type: core_3.SkipSelf}, {type: core_2.Optional}, ] }, ], WjFlexChartPlotArea }(wjcChart.PlotArea); exports.WjFlexChartPlotArea = WjFlexChartPlotArea; moduleExports = [WjFlexChart, WjFlexPie, WjFlexChartAxis, WjFlexChartLegend, WjFlexChartDataLabel, WjFlexPieDataLabel, WjFlexChartSeries, WjFlexChartLineMarker, WjFlexChartDataPoint, WjFlexChartPlotArea]; WjChartModule = function() { function WjChartModule(){} return WjChartModule.decorators = [{ type: core_1.NgModule, args: [{ imports: [wijmo_angular2_directiveBase_1.WjDirectiveBaseModule, common_1.CommonModule], declarations: moduleExports.slice(), exports: moduleExports.slice() }, ] }, ], WjChartModule.ctorParameters = [], WjChartModule }(); exports.WjChartModule = WjChartModule
mit
eldering/autoanalyst
katalyze/src/rules/NewLeader.java
2707
package rules; import model.EventImportance; import model.LoggableEvent; import model.Score; import model.Submission; import model.Team; public class NewLeader extends StateComparingRuleBase implements StandingsUpdatedEvent { private int breakingPrioRanks; private int normalPrioRanks; public NewLeader(int breakingPrioRanks, int normalPrioRanks) { this.breakingPrioRanks = breakingPrioRanks; this.normalPrioRanks = normalPrioRanks; } private EventImportance fromRank(int rank) { if (rank <= breakingPrioRanks) { return EventImportance.Breaking; } if (rank <= normalPrioRanks) { return EventImportance.Normal; } return EventImportance.Whatever; } private String problemsAsText(int nProblems) { if (nProblems == 1) { return "1 problem"; } else { return String.format("%d problems", nProblems); } } @Override public void onStandingsUpdated(StandingsTransition transition) { Submission submission = transition.submission; if (!submission.isAccepted()) { return; } Team team = submission.getTeam(); Score scoreBefore = transition.before.scoreOf(team); if (scoreBefore.isSolved(submission.getProblem())) { // Problem was already solved. No need to send new notifications return; } int rankBefore = transition.before.rankOf(team); int rankAfter = transition.after.rankOf(team); Score score = transition.after.scoreOf(team); int solvedProblemCount = score.solvedProblemCount(); EventImportance importance = fromRank(rankAfter); String solvedProblemsText = problemsAsText(solvedProblemCount); LoggableEvent event = null; if (solvedProblemCount == 1) { event = transition.createEvent(String.format("{team} solves its first problem: {problem}"), importance); } else if (rankAfter == 1 && rankBefore == 1) { event = transition.createEvent(String.format("{team} extends its lead by solving {problem}. It has now solved %s", solvedProblemsText), importance); } else if (rankAfter < rankBefore) { if (rankAfter == 1) { event = transition.createEvent(String.format("{team} now leads the competition after solving {problem}. It has now solved %s", solvedProblemsText), importance); } else { event = transition.createEvent(String.format("{team} solves {problem}. It has now solved %s and is at rank %d (%d)", solvedProblemsText, rankAfter, rankBefore), importance); } } else if (rankAfter == rankBefore) { event = transition.createEvent(String.format("{team} solves {problem}. It has now solved %s, but is still at rank %d", solvedProblemsText, rankAfter), importance); } else { assert rankAfter <= rankBefore; } notify(event); } }
mit
grollins/flexe-web-angular
scripts/controllers/home.js
2309
'use strict'; angular.module('flexeWebApp') .controller('HomeCtrl', function($scope, $log, FlexeWebBackend, User) { $scope.submissionFailed = false; $scope.submissionSucceeded = false; $scope.submissionStatus = ''; $scope.jobs = []; $scope.username = User.username(); $scope.job = { title: '', refFile: null, comparisonFile: null, }; $scope.closeAlert = function() { $scope.submissionFailed = false; $scope.submissionSucceeded = false; $scope.submissionStatus = ''; }; $scope.saveJob = function() { var fd = new FormData(); fd.append('title', $scope.job.title); fd.append('reference', $scope.job.refFile); fd.append('comparison', $scope.job.comparisonFile); FlexeWebBackend.saveJob(fd) .success(function(data, status, headers, config) { $scope.status = status; $log.debug('Job post success'); $scope.refreshJobs(); $scope.submissionSucceeded = true; }) .error(function(data, status, headers, config) { $scope.status = status; $log.debug('Job post failed'); $log.debug(data); $scope.refreshJobs(); $scope.submissionFailed = true; $scope.submissionStatus = status; }); $scope.jobForm.$setPristine(); $scope.job.title = ''; angular.forEach( angular.element("input[type='file']"), function(inputElem) { angular.element(inputElem).val(null); }); }; $scope.refreshJobs = function() { FlexeWebBackend.refreshJobs() .success(function(data, status) { $scope.status = status; $scope.jobs = data.results; $log.debug('Job refresh success'); }) .error(function(data, status) { $scope.jobs = data || 'Job refresh failed'; $scope.status = status; $log.debug('Job refresh failed'); }); }; $scope.refreshJobs(); });
mit
stas-vilchik/bdd-ml
data/629.js
56
{ return { url: "/bar", method: "post" }; }
mit
gitadept/instagram-private-api
tests/cases/device.js
3391
var should = require('should'); var Client = require('../../client/v1'); var path = require('path'); var mkdirp = require('mkdirp'); var support = require('../support'); var _ = require('lodash'); var fs = require('fs'); describe("`Device` class", function() { var device1; var device1Same; var device2; before(function() { device1 = new Client.Device('someuser1'); device1Same = new Client.Device('someuser1'); device2 = new Client.Device('someuser2'); }) it("should not be problem to access username", function() { device1.username.should.be.equal('someuser1') device2.username.should.be.equal('someuser2') }) it("should not be problem to access id", function() { device1.id.should.match(/^android-[a-zA-Z0-9]{16}$/) }) it("should match same ids 2 times", function() { device1.id.should.be.equal(device1Same.id) }) it("should have md5", function() { device1.md5.should.not.be.empty() device1.md5.should.be.String() device1.md5.length.should.be.equal(32) }) it("should have property api", function() { device1.api.should.be.Number(); device1.api.should.be.oneOf([18, 19, 20, 21, 22, 23]); }) it("should have property release", function() { device1.release.should.be.String(); device1.release.should.be.oneOf(['4.0.4', '4.3.1', '4.4.4', '5.1.1', '6.0.1']); }) it("should have property dpi", function() { device1.dpi.should.be.String(); device1.dpi.should.be.oneOf(['801', '577', '576', '538', '515', '424', '401', '373']); }) it("should have property resolution", function() { device1.resolution.should.be.String(); device1.resolution.should.be.oneOf(['3840x2160', '1440x2560', '2560x1440', '1440x2560', '2560x1440', '1080x1920', '1080x1920', '1080x1920']); }) it("should have property language", function() { device1.language.should.be.String(); device1.language.should.be.oneOf(['en_US']); }) it("should not be problem to get device info", function() { device1.info.should.have.property('model') device1.info.should.have.property('manufacturer') device1.info.should.have.property('device') }) it("should not be problem to get device payload", function() { device1.payload.should.have.property('manufacturer') device1.payload.should.have.property('model') device1.payload.should.have.property('android_version') device1.payload.should.have.property('android_release') device1.payload.manufacturer.should.be.String() device1.payload.manufacturer.should.not.be.empty() device1.payload.model.should.be.String() device1.payload.model.should.not.be.empty() device1.payload.android_version.should.be.Number() device1.payload.android_version.should.be.above(17) device1.payload.android_release.should.be.String() device1.payload.android_release.should.not.be.empty() }) it("should not be problem to get userAgent", function() { var yellowstone = /^Instagram\s[0-9\.]*\sAndroid\s\(18\/4.0.4\;\s424dpi\;\s1080x1920\;\sGoogle\;\sYellowstone\;\syellowstone\;\sen_US\)$/; device1.userAgent().should.match(yellowstone) }) })
mit
myaskevich/turing
turing/runtime/example.py
2370
import os import sys import traceback from turing.runtime.state import UserState, InitialMixin, FinalMixin, \ StateRegister from turing.runtime.machine import Turing, TerminateException from turing.tape import TapeError, TapeIsOverException, Tape from turing.const import Move, Action _states = set() class DoesNotEndWithZero_State(UserState, InitialMixin): name = "does not end with zero" def _resolve(self, machine): if machine.head == '0' : machine.assume('endswithzero') machine.do(Action.WRITE, 'x') else: machine.assume(self) machine.terminate() machine.move(Move.RIGHT) _states.add(DoesNotEndWithZero_State()) class EndsWithZero_State(UserState, FinalMixin): name = "ends with zero" def _resolve(self, machine): if machine.head == '0' : machine.assume(self) machine.do(Action.WRITE, 'x') else: machine.assume('doesnotendwithzero') machine.terminate() machine.move(Move.RIGHT) _states.add(EndsWithZero_State()) def make_state_table(): table = StateRegister() for state in _states: table.add_state(state) return table def main(args): msg = "Expected single command line argument, got " + str(len(args)) assert len(args) == 2, msg arg = args[1] if isinstance(arg, Tape): src = arg elif os.path.isfile(arg): src = "" with open(arg, 'rb') as file: src = file.read() else: src = arg turing = Turing(src) state_register = make_state_table() initial = state_register.get_initial() finals = state_register.get_finals() turing.set_state_register(state_register) state_register.set_current(initial.getid()) ret = 0 try: turing.start() except TapeIsOverException, e: # print e if turing._register.current not in finals: ret = 1 except TapeError, e: print "tape error:", str(e) ret = 2 except TerminateException, e: if turing._register.current not in finals: ret = 1 finally: out_tape = str(turing._tape) return ret if __name__ == '__main__': try: sys.exit(main(sys.args)) except Exception: traceback.print_exc() sys.exit(1)
mit
dvsa/mot
mot-api/module/SiteApi/src/SiteApi/Factory/Controller/TesterRiskScoreControllerFactory.php
1174
<?php namespace SiteApi\Factory\Controller; use Interop\Container\ContainerInterface; use SiteApi\Service\Mapper\TesterRiskScoreMapper; use Zend\ServiceManager\Factory\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use Zend\ServiceManager\ServiceManager; use SiteApi\Controller\TesterRiskScoreController; use SiteApi\Service\TesterRiskScoreService; /** * Class TesterRiskScoreControllerFactory. */ class TesterRiskScoreControllerFactory implements FactoryInterface { /** * @param ServiceLocatorInterface $controllerManager * * @return TesterRiskScoreControllerFactory */ public function createService(ServiceLocatorInterface $controllerManager) { return $this($controllerManager, TesterRiskScoreController::class); } public function __invoke(ContainerInterface $container, $requestedName, array $options = null) { /** @var ServiceManager $serviceLocator */ $serviceLocator = $container->getServiceLocator(); return new TesterRiskScoreController( $serviceLocator->get(TesterRiskScoreService::class), new TesterRiskScoreMapper() ); } }
mit
BlueDragon23/MIDIBlocks
src/main/blocks/gateStrategy/AbstractGateStrategy.java
1246
package blocks.gateStrategy; import MIDIBlocks.Note; import MIDIBlocks.NoteQueue; public abstract class AbstractGateStrategy { protected NoteQueue queue; protected Note currentNote; protected float notesPerTick; protected int notesReceived = 0; public AbstractGateStrategy(float notesPerTick) { queue = new NoteQueue(); currentNote = null; this.notesPerTick = notesPerTick; } abstract public void update(Note note); public boolean isNext() { return queue.size() > 0; } /** * Retrieves the next note and removes it from the queue * * @return */ public Note getNext() { Note note = queue.getNote(0); if (note != null) { queue.removeNote(0); } currentNote = null; return note; } abstract public String getName(); /** * Return true iff the note is in the queue * * @param note * @return */ public boolean contains(Note note) { return queue.contains(note); } /** * Reset the counter for number of notes received. Only useful for * first/last hold */ public void resetReceived() { notesReceived = 0; } }
mit
baez90/CommuneCalculator
CommuneCalculator/CommuneCalculator.WPF/IoC/ViewsIocModule.cs
976
using Autofac; using CommuneCalculator.Pages; using CommuneCalculator.Pages.Auswertung; using CommuneCalculator.Pages.Purchases.Create; using CommuneCalculator.Pages.Purchases.Overview; using CommuneCalculator.Pages.Roommates.Absences.CreateUpdate; using CommuneCalculator.Pages.Roommates.CreateUpdate; using CommuneCalculator.Pages.Roommates.Overview; namespace CommuneCalculator.IoC { public class ViewsIocModule : Module { protected override void Load(ContainerBuilder builder) { builder.Register(context => new AusgabenVerlauf()); builder.Register(context => new CreateUpdateRoommate()); builder.Register(context => new RoommateOverview()); builder.Register(context => new PurchasesOverview()); builder.Register(context => new CreatePurchase()); builder.Register(context => new Home()); builder.Register(context => new CreateUpdateAbsence()); } } }
mit
NetOfficeFw/NetOffice
Source/Excel/Interfaces/IWalls.cs
8245
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.ExcelApi { /// <summary> /// Interface IWalls /// SupportByVersion Excel, 9,10,11,12,14,15,16 /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] [EntityType(EntityType.IsInterface)] public class IWalls : COMObject { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(IWalls); return _type; } } #endregion #region Ctor /// <param name="factory">current used factory core</param> /// <param name="parentObject">object there has created the proxy</param> /// <param name="proxyShare">proxy share instead if com proxy</param> public IWalls(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public IWalls(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IWalls(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IWalls(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IWalls(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IWalls(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IWalls() : base() { } /// <param name="progId">registered progID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IWalls(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public NetOffice.ExcelApi.Application Application { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Application>(this, "Application", NetOffice.ExcelApi.Application.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public NetOffice.ExcelApi.Enums.XlCreator Creator { get { return Factory.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCreator>(this, "Creator"); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16), ProxyResult] public object Parent { get { return Factory.ExecuteReferencePropertyGet(this, "Parent"); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public string Name { get { return Factory.ExecuteStringPropertyGet(this, "Name"); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public NetOffice.ExcelApi.Border Border { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Border>(this, "Border", NetOffice.ExcelApi.Border.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public NetOffice.ExcelApi.Interior Interior { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Interior>(this, "Interior", NetOffice.ExcelApi.Interior.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public NetOffice.ExcelApi.ChartFillFormat Fill { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.ChartFillFormat>(this, "Fill", NetOffice.ExcelApi.ChartFillFormat.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public object PictureType { get { return Factory.ExecuteVariantPropertyGet(this, "PictureType"); } set { Factory.ExecuteVariantPropertySet(this, "PictureType", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public object PictureUnit { get { return Factory.ExecuteVariantPropertyGet(this, "PictureUnit"); } set { Factory.ExecuteVariantPropertySet(this, "PictureUnit", value); } } /// <summary> /// SupportByVersion Excel 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 12,14,15,16)] public Int32 Thickness { get { return Factory.ExecuteInt32PropertyGet(this, "Thickness"); } set { Factory.ExecuteValuePropertySet(this, "Thickness", value); } } /// <summary> /// SupportByVersion Excel 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 12,14,15,16)] public NetOffice.ExcelApi.ChartFormat Format { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.ChartFormat>(this, "Format", NetOffice.ExcelApi.ChartFormat.LateBindingApiWrapperType); } } #endregion #region Methods /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public object Select() { return Factory.ExecuteVariantMethodGet(this, "Select"); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public object ClearFormats() { return Factory.ExecuteVariantMethodGet(this, "ClearFormats"); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public Int32 Paste() { return Factory.ExecuteInt32MethodGet(this, "Paste"); } #endregion #pragma warning restore } }
mit
carnage/cqrs
src/Service/EventCatcher.php
1125
<?php namespace Carnage\Cqrs\Service; use Carnage\Cqrs\Event\DomainMessage; use Carnage\Cqrs\Event\EventInterface; use Carnage\Cqrs\MessageBus\MessageInterface; use Carnage\Cqrs\MessageHandler\MessageHandlerInterface; /** * Class EventCatcher * @package Carnage\Cqrs\Service */ class EventCatcher implements MessageHandlerInterface { /** * @var array */ private $events; /** * @var array */ private $eventsByType; /** * @return EventInterface[] */ public function getEvents() { return $this->events; } /** * @return EventInterface[] */ public function getEventsByType($eventType) { return $this->eventsByType[$eventType]; } /** * @param DomainMessage $message */ public function handleDomainMessage(DomainMessage $message) { $this->handle($message->getEvent()); } /** * @param MessageInterface $event */ public function handle(MessageInterface $event) { $this->events[] = $event; $this->eventsByType[get_class($event)][] = $event; } }
mit
leonardorifeli/morfeu
src/Morfeu/Bundle/BusinessBundle/Service/MailImportInformationService.php
600
<?php namespace Morfeu\Bundle\BusinessBundle\Service; use Doctrine\ORM\EntityManager; use Morfeu\Bundle\BusinessBundle\Service\BaseService; use Morfeu\Bundle\EntityBundle\Entity\Card; use Morfeu\Bundle\BusinessBundle\Enum\Status; class MailImportInformationService { private $imapMailService; public function __construct($imapMailService) { $this->imapMailService = $imapMailService; } public function getMailInAccount() { $mailInAccount = $this->imapMailService->connectImapAccountAndGetMail(); var_dump($mailInAccount); exit; } }
mit
inilotic/vims_crm_core
public/js/vks/day_calendar.js
3853
$(document).ready(function () { var modal = new Modal(); $(document).on("click", ".modal-event-ws", function () { modal.showPageInModal("?route=Vks/show/" + $(this).attr('event-id') + "/true") //getModalVks($(this).attr('event-id')); }); $(document).on("click", ".modal-event-ca", function () { getModalVksCa($(this).attr('event-id')); }); /* initialize the calendar -----------------------------------------------------------------*/ // var getVksSwitcherState = 13; $('#calendar').fullCalendar({ header: { left: '', center: '', // right: 'month,agendaWeek,agendaDay' right: '' }, axisFormat: "HH:mm", editable: false, defaultDate: currentDate, //defaultView: 'agendaDay', defaultView: 'agendaDay', events: "?route=CalendarFeed/feedMain", eventLimit: { 'agenda': 4, 'default': 4 }, allDaySlot: false, slotDuration: "00:15:00", // weekends: false, lang: 'ru', timeFormat: { '': 'h(:mm)' // default }, minTime: "08:00:00", maxTime: "20:00:00", slotEventOverlap: false, height: 'auto', pullServerLoadFrom: 0, eventRender: function (event, element) { element.addClass('pointer'); if (event.fromCa) { element.addClass('pointer modal-event-ca'); } else { element.addClass('pointer modal-event-ws'); } $(element).css("margin-right", "2px"); $(element).css("margin-bottom", "2px"); element.attr("event-id", event.id); element.find(".fc-time").html("<div>" + event.plankHtml + "</div>"); }, eventAfterAllRender: function () { $("#current_time").remove(); var now = moment().format("DD.MM.YYYY H:mm"); var hours = moment().format("H"); var minutes = moment().format("mm"); var year = moment().format("YYYY"); var day = moment().format("DD"); var mounth = moment().format("MM")-1; var currentOnGoing = null; if (minutes < 60 && minutes>= 45) { currentOnGoing = moment([year, mounth, day, hours, 45]).format("DD.MM.YYYY HH:mm"); } else if (minutes < 45 && minutes>= 30) { currentOnGoing = moment([year, mounth, day, hours, 30]).format("DD.MM.YYYY HH:mm"); } else if (minutes < 30 && minutes>= 15) { currentOnGoing = moment([year, mounth, day, hours, 15]).format("DD.MM.YYYY HH:mm"); } else if (minutes < 15 && minutes >=0) { currentOnGoing = moment([year, mounth, day, hours, 0]).format("DD.MM.YYYY HH:mm"); } var s = $(".timerow[data-datetime='" + currentOnGoing + "']"); if (s.length) { var o = s.offset(); var compile = $("<div/>").prop("id", "current_time"); if (o.top ==0) { o.top = -500; } compile.css({ 'left': o.left + "px", 'top': o.top + "px", 'position': 'absolute', 'z-index': 9999, 'min-height': '20px', 'height': '20px', 'min-width': 98 + "%", 'width': 98 + "%", 'background-color': 'yellow', 'opacity': 0.7 }); compile.html("<div class='text-center'><span style='width: 100%'>Сейчас</span></div>"); $('body').append(compile); } } }); });
mit
tobilen/react-nws
internals/webpack/webpack.base.babel.js
3036
/** * COMMON WEBPACK CONFIGURATION */ const path = require('path'); const webpack = require('webpack'); module.exports = (options) => ({ entry: options.entry, output: Object.assign({ // Compile into js/build.js path: path.resolve(process.cwd(), 'build'), publicPath: '/', }, options.output), // Merge with env dependent settings module: { loaders: [{ test: /\.js$/, // Transform all .js files required somewhere with Babel loader: 'babel-loader', exclude: /node_modules/, query: options.babelQuery, }, { // Do not transform vendor's CSS with CSS-modules // The point is that they remain in global scope. // Since we require these CSS files in our JS or CSS files, // they will be a part of our compilation either way. // So, no need for ExtractTextPlugin here. test: /\.css$/, loaders: ['style-loader?sourceMap', 'css-loader?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]'], }, { test: /.sass$/, loaders: ["style-loader?sourceMap", "css-loader?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]", "sass-loader"], include: path.resolve(__dirname, '../') }, { test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file-loader', }, { test: /\.(jpg|png|gif)$/, loaders: [ 'file-loader', { loader: 'image-webpack-loader', query: { progressive: true, optimizationLevel: 7, interlaced: false, pngquant: { quality: '65-90', speed: 4, }, }, }, ], }, { test: /\.html$/, loader: 'html-loader', }, { test: /\.json$/, loader: 'json-loader', }, { test: /\.(mp4|webm)$/, loader: 'url-loader', query: { limit: 10000, }, }, { test: /\.svg$/, loader: 'svg-sprite-loader?' + JSON.stringify({ name: 'icon-[1]', prefixize: true, regExp: 'assets/icons/(.*)\\.svg' }) }], }, plugins: options.plugins.concat([ new webpack.ProvidePlugin({ // make fetch available fetch: 'exports-loader?self.fetch!whatwg-fetch', }), // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV` // inside your code for any environment checks; UglifyJS will automatically // drop any unreachable code. new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV), }, }), new webpack.NamedModulesPlugin(), ]), resolve: { modules: ['app', 'node_modules'], extensions: [ '.js', '.jsx', '.react.js', ], mainFields: [ 'browser', 'jsnext:main', 'main', ], }, devtool: options.devtool, target: 'web', // Make web variables accessible to webpack, e.g. window performance: options.performance || {}, node: { fs: "empty" } });
mit
vita-software/export-formatter
src/Line.php
725
<?php declare(strict_types = 1); namespace Vita\ExportFormatter; /** * Class Line * @package Vita\ExportFormatter */ class Line { /** * @var string */ protected $name; /** * @var Field[] */ protected $fields; /** * Line constructor. * @param string $name * @param Field[] $fields */ public function __construct(string $name, array $fields) { $this->name = $name; $this->fields = $fields; } /** * @return string */ public function getName(): string { return $this->name; } /** * @return Field[] */ public function getFields(): array { return $this->fields; } }
mit
WilliamBZA/so-you-wanna-build-a-service-bus
Samples/MsmqSamples/Messages/LinkIsComingEvent.cs
189
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Messages { public class LinkIsComingEvent { } }
mit
Hayden345/UNSWAssignmentDroid
TaxTimeWithFriends/app/src/main/java/com/example/dylan/taxtimewithfriends/Databases/VehicleTable.java
3339
package com.example.dylan.taxtimewithfriends.Databases; import android.provider.BaseColumns; import java.util.Date; /** * Created by z5056635 on 18/10/2017. */ public class VehicleTable { private VehicleTable() {} public static class VehicleTableEntry implements BaseColumns { public static final String TABLE_NAME = "Vehicles"; public static final String COLUMN_NAME_REGISTRATION = "Registration"; public static final String COLUMN_NAME_MAKE = "Make"; public static final String COLUMN_NAME_MODEL = "Model"; public static final String COLUMN_NAME_YEAR = "Year"; public static final String COLUMN_NAME_ENGINE = "Engine"; } public static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + VehicleTableEntry.TABLE_NAME + " (" + ExpenseTable.ExpenseTableEntry._ID + "INTEGER PRIMARY KEY AUTOINCREMENT," + VehicleTableEntry.COLUMN_NAME_REGISTRATION + " TEXT," + VehicleTableEntry.COLUMN_NAME_MAKE + " TEXT," + VehicleTableEntry.COLUMN_NAME_MODEL + " TEXT," + VehicleTableEntry.COLUMN_NAME_YEAR + " DATE," + VehicleTableEntry.COLUMN_NAME_ENGINE + " TEXT)"; public static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + VehicleTableEntry.TABLE_NAME; /** * SQL compatible string for returning all rows of the Vehicle Table */ public static final String SQL_SELECT_ALL = "SELECT * FROM " + VehicleTableEntry.TABLE_NAME; /** * Returns an SQL compatible string that can be used to select a row from the Vehicle table using its id * * @param id the primary key of the row to be selected * @return an SQL compatible string that selects a row based on its primary key */ public static String selectVehicle(int id) { String SQL_Select = "SELECT * FROM " + VehicleTableEntry.TABLE_NAME + " WHERE " + VehicleTableEntry._ID + " = " + id; return SQL_Select; } /** * Returns an SQL compatible string that can be used to delete a row from the Vehicle table using its id * * @param id the primary key of the row to be deleted * @return an SQL compatible string that deletes a row based on its primary key */ public static String deleteVehicle(int id) { String SQL_Delete = "DELETE FROM " + VehicleTableEntry.TABLE_NAME + " WHERE " + VehicleTableEntry._ID + " = " + id; return SQL_Delete; } /** * Returns an SQL compatible string that can be used to insert a row into the vehicle table * @param registrationNumber the registration number of the vehicle * @param make the make of the vehicle * @param model the model of the vehicle * @param year the year of the vehicle * @param engine the engine size of the vehicle * @return the SQL compatible string */ public static String insertVehicle(String registrationNumber, String make, String model, Date year, String engine) { String SQL_Insert = "INSERT INTO " + VehicleTableEntry.TABLE_NAME + " VALUES (NULL, " + registrationNumber + "\", \"" + make + "\", \"" + model + "\", " + year + ", \"" + engine + "\")"; return SQL_Insert; } }
mit
Diviyan-Kalainathan/causal-humans
Cause-effect/util/file_to_kagf.py
1499
""" Convert Kaggle format data into 1 file by pair of variables """ import os import numpy as np import pandas as pd import csv def format_col(df): df.columns=['A','B'] A="" B="" for idx,row in df.iterrows(): A+=' '+str(float(row['A'])) B+=' ' + str(float(row['B'])) return A,B def file_to_kag(pthtofile): SplID=[] type_info=[] i=1 with open(pthtofile+'Dfinal_Pairs.csv','wb') as output: writer=csv.writer(output) writer.writerow(['SampleID','A','B']) while os.path.exists(pthtofile+str(i)+'.txt'): print(pthtofile+str(i)+'.txt') df=pd.read_csv(pthtofile+str(i)+'.txt',sep=' | | | ') A,B=format_col(df) SampleID= os.path.basename(pthtofile)+'D'+str(i) SplID.append(SampleID) type_info.append('Numerical') writer.writerow([SampleID,A,B]) if i==26091: break i+=1 print(len(SplID)) print(len(type_info)) info=pd.DataFrame([SplID,type_info,type_info]) info=info.transpose() info.columns=['SampleID','A type','B type'] #info['SampleID']=pd.Series(SplID,index=info.index) #info['Type-A']=pd.Series(type_info,index=info.index) #info['Type-B']=pd.Series(type_info,index=info.index) info.to_csv(pthtofile+'Dfinal_publicinfo.csv',index=False) if __name__ == '__main__': inputfile_type='/users/ao/diviyan/NoSave/DatasetD/pair' file_to_kag(inputfile_type)
mit
mgechev/ngrev
src/app/components/quick-access/quick-access.component.ts
3500
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, HostBinding, Input, OnDestroy, Output, ViewChild } from '@angular/core'; import { Theme } from '../../../shared/themes/color-map'; import { CONTROL, DOWN_ARROW, ESCAPE, META, P, UP_ARROW } from '@angular/cdk/keycodes'; import { fromEvent, Observable, Subject } from 'rxjs'; import { filter, map, takeUntil, tap } from 'rxjs/operators'; import { KeyValue } from '@angular/common'; import { IdentifiedStaticSymbol } from '../../../shared/data-format'; declare const require: any; const Fuse = require('fuse.js'); const MetaKeyCodes = [META, CONTROL]; @Component({ selector: 'ngrev-quick-access', templateUrl: './quick-access.component.html', styleUrls: ['./quick-access.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class QuickAccessComponent implements OnDestroy { @Input() theme!: Theme; @Input() set queryObject(query: string[]) { let list = []; if (this.fuse) { list = this.fuse.list; } this.fuse = new Fuse(list, { keys: query }); } @Input() set queryList(symbols: KeyValue<string, IdentifiedStaticSymbol>[]) { this.fuse.set(symbols); } @Output() select: EventEmitter<KeyValue<string, IdentifiedStaticSymbol>> = new EventEmitter<KeyValue<string, IdentifiedStaticSymbol>>(); @HostBinding('class.hidden') hidden: boolean = true; @ViewChild('input', {static: false}) set input(value: ElementRef) { value?.nativeElement.focus(); } searchQuery$: Subject<string> = new Subject<string>(); searchResult$: Observable<any>; private metaKeyDown = 0; private fuse: typeof Fuse = new Fuse([], { keys: ['name', 'filePath'] }); private _unsubscribe: Subject<void> = new Subject<void>(); constructor(private _changeDetectorRef: ChangeDetectorRef) { fromEvent(document, 'click').pipe( filter(() => !this.hidden), tap({ next: () => { this.hide(); } }), takeUntil(this._unsubscribe) ).subscribe(); fromEvent<KeyboardEvent>(document, 'keydown').pipe( tap((event: KeyboardEvent) => { if (MetaKeyCodes.indexOf(event.keyCode) >= 0) { this.metaKeyDown = event.keyCode; } if (event.keyCode === P && this.metaKeyDown) { this.show(); } if (event.keyCode === ESCAPE) { this.hide(); } if (event.keyCode === DOWN_ARROW || event.keyCode === UP_ARROW) { event.preventDefault(); } }), takeUntil(this._unsubscribe) ).subscribe(); fromEvent<KeyboardEvent>(document, 'keyup').pipe( tap((event: KeyboardEvent) => { if (MetaKeyCodes.indexOf(event.keyCode) >= 0 && this.metaKeyDown === event.keyCode) { this.metaKeyDown = 0; } }), takeUntil(this._unsubscribe) ).subscribe(); this.searchResult$ = this.searchQuery$.pipe( map((searchQuery: string) => { return this.fuse.search(searchQuery); }) ); } ngOnDestroy(): void { this._unsubscribe.next(); this._unsubscribe.complete(); } updateKeyword(searchText: string) { this.searchQuery$.next(searchText); } get boxShadow() { return `0 0 11px 3px ${this.theme.fuzzySearch.shadowColor}`; } hide() { this.hidden = true; this._changeDetectorRef.markForCheck(); } private show() { this.hidden = false; this._changeDetectorRef.markForCheck(); } }
mit
cob16/cs-221-group-project
src/RPSRec_proto/src/uk/me/jstott/jcoord/Test.java
5203
package uk.me.jstott.jcoord; /** * Class to illustrate the use of the various functions of the classes in the * Jcoord package. * * (c) 2006 Jonathan Stott * * Created on 11-Feb-2006 * * @author Jonathan Stott * @version 1.0 * @since 1.0 */ public class Test { /** * Main method * * @param args * not used * @since 1.0 */ public static void main(String[] args) { /* * Calculate Surface Distance between two Latitudes/Longitudes * * The distance() function takes a reference to a LatLng object as a * parameter and calculates the surface distance between the the given * object and this object in kilometres: */ System.out .println("Calculate Surface Distance between two Latitudes/Longitudes"); LatLng lld1 = new LatLng(40.718119, -73.995667); // New York System.out.println("New York Lat/Long: " + lld1.toString()); LatLng lld2 = new LatLng(51.499981, -0.125313); // London System.out.println("London Lat/Long: " + lld2.toString()); double d = lld1.distance(lld2); System.out.println("Surface Distance between New York and London: " + d + "km"); System.out.println(); /* * Convert OS Grid Reference to Latitude/Longitude * * Note that the OSGB-Latitude/Longitude conversions use the OSGB36 datum by * default. The majority of applications use the WGS84 datum, for which the * appropriate conversions need to be added. See the examples below to see * the difference between the two data. */ System.out.println("Convert OS Grid Reference to Latitude/Longitude"); // Using OSGB36 (convert an OSGB grid reference to a latitude and longitude // using the OSGB36 datum): System.out.println("Using OSGB36"); OSRef os1 = new OSRef(651409.903, 313177.270); System.out.println("OS Grid Reference: " + os1.toString() + " - " + os1.toSixFigureString()); LatLng ll1 = os1.toLatLng(); System.out.println("Converted to Lat/Long: " + ll1.toString()); System.out.println(); // Using WGS84 (convert an OSGB grid reference to a latitude and longitude // using the WGS84 datum): System.out.println("Using WGS84"); OSRef os1w = new OSRef(651409.903, 313177.270); System.out.println("OS Grid Reference: " + os1w.toString() + " - " + os1w.toSixFigureString()); LatLng ll1w = os1w.toLatLng(); ll1w.toWGS84(); System.out.println("Converted to Lat/Long: " + ll1w.toString()); System.out.println(); /* * Convert Latitude/Longitude to OS Grid Reference * * Note that the OSGB-Latitude/Longitude conversions use the OSGB36 datum by * default. The majority of applications use the WGS84 datum, for which the * appropriate conversions need to be added. See the examples below to see * the difference between the two data. */ System.out.println("Convert Latitude/Longitude to OS Grid Reference"); // Using OSGB36 (convert a latitude and longitude using the OSGB36 datum to // an OSGB grid reference): System.out.println("Using OSGB36"); LatLng ll2 = new LatLng(52.657570301933, 1.7179215806451); System.out.println("Latitude/Longitude: " + ll2.toString()); OSRef os2 = ll2.toOSRef(); System.out.println("Converted to OS Grid Ref: " + os2.toString() + " - " + os2.toSixFigureString()); System.out.println(); // Using WGS84 (convert a latitude and longitude using the WGS84 datum to an // OSGB grid reference): System.out.println("Using WGS84"); LatLng ll2w = new LatLng(52.657570301933, 1.7179215806451); System.out.println("Latitude/Longitude: " + ll2.toString()); ll2w.toOSGB36(); OSRef os2w = ll2w.toOSRef(); System.out.println("Converted to OS Grid Ref: " + os2w.toString() + " - " + os2w.toSixFigureString()); System.out.println(); /* * Convert Six-Figure OS Grid Reference String to an OSRef Object * * To convert a string representing a six-figure OSGB grid reference: */ System.out .println("Convert Six-Figure OS Grid Reference String to an OSRef Object"); String os6 = "TG514131"; System.out.println("Six figure string: " + os6); OSRef os6x = new OSRef(os6); System.out.println("Converted to OS Grid Ref: " + os6x.toString() + " - " + os6x.toSixFigureString()); System.out.println(); /* * Convert UTM Reference to Latitude/Longitude */ System.out.println("Convert UTM Reference to Latitude/Longitude"); UTMRef utm1 = new UTMRef(456463.99, 3335334.05, 'E', 12); System.out.println("UTM Reference: " + utm1.toString()); LatLng ll3 = utm1.toLatLng(); System.out.println("Converted to Lat/Long: " + ll3.toString()); System.out.println(); /* * Convert Latitude/Longitude to UTM Reference */ System.out.println("Convert Latitude/Longitude to UTM Reference"); LatLng ll4 = new LatLng(-60.1167, -111.7833); System.out.println("Latitude/Longitude: " + ll4.toString()); UTMRef utm2 = ll4.toUTMRef(); System.out.println("Converted to UTM Ref: " + utm2.toString()); System.out.println(); } }
mit
aattsai/phase-0
week-7/num_commas.js
3368
// Separate Numbers with Commas in JavaScript **Pairing Challenge** // I worked on this challenge with: Kyle Smith // Pseudocode // Input: An integer // Output: A string separated with commas at every third number. // Step 1: Define a function that takes an integer as an input // Step 2: Convert the integer to a string // Step 3: Reverse the order of the string // Step 4: Iterate over the string and add a comma to every third character // Step 5: Reverse it back and return the string with commas // Initial Solution // function separateComma(num) { // num = num.toString(); // var commanum = ""; // var reverse =""; // var finalnum = ""; // var finalfinal = ""; // for (var j = num.length-1 ; j>-1 ; j--) { // reverse += num[j]; // } // console.log(reverse); // for (var i = 0 ; i < num.length ; i++) { // commanum += reverse[i]; // if ((i - 2) % 3 === 0) { // commanum += ","; // } // } // for (var j = commanum.length-1 ; j > -1 ; j--) { // finalnum += commanum[j]; // } // if (finalnum[0]% 1 != 0) { // for (var i = 1; i < finalnum.length ; i++) { // finalfinal += finalnum[i]; // } // console.log(finalfinal) // } // else { // console.log(finalnum); // } // } // separateComma(123456); // Refactored Solution function separateComma(num) { num = num.toString(); var commanum = ""; var reverse =""; var finalnum = ""; var finalfinal = ""; for (var j = num.length-1 ; j>-1 ; j--) { reverse += num[j]; } //reverse string num for (var i in reverse) { //shorthand way to do a for loop commanum += reverse[i]; if ((i - 2) % 3 === 0) { commanum += ","; } }; //Add , to a new string commanum if the position starting at the third position (i === 2), then 6th position (i ==== 5) for (var j = commanum.length-1 ; j > -1 ; j--) { finalnum += commanum[j]; }; //Reverse the product of comma added string back to original if (isNaN(finalnum[0])) { //Check if the first position is a number or a comma, if a comma, then create a new string called finalfinal which iterate through finalnum from the second position (i === 1), omitting the first comma for (var i = 1; i < finalnum.length ; i++) { finalfinal += finalnum[i]; }; console.log(finalfinal) } else { //If the first position is a number, just print the result out as is. console.log(finalnum); } } separateComma(1234567); separateComma(12345678); separateComma(123456789); separateComma(1234567890); // Your Own Tests (OPTIONAL) // Reflection // What was it like to approach the problem from the perspective of JavaScript? Did you approach the problem differently? // -The way we began in breaking down the problem and coming up with pseudocode was the same. One of the biggest difference in approach we had was to implement lots of loops rather than built-in methods. // What did you learn about iterating over arrays in JavaScript? //We learned how to use for loops to iterate over arrays in JavaScript. // What was different about solving this problem in JavaScript? //There aren't that many built-in methods available to help us solve this problem. // What built-in methods did you find to incorporate in your refactored solution? //One built-in method we incorporated was isNaN to check whether the element is a number.
mit
plotly/plotly.py
packages/python/plotly/plotly/validators/scattermapbox/stream/_maxpoints.py
509
import _plotly_utils.basevalidators class MaxpointsValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="maxpoints", parent_name="scattermapbox.stream", **kwargs ): super(MaxpointsValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), max=kwargs.pop("max", 10000), min=kwargs.pop("min", 0), **kwargs )
mit
oliviertassinari/material-ui
docs/src/components/animation/FadeDelay.tsx
454
import * as React from 'react'; import Fade, { FadeProps } from '@mui/material/Fade'; export default function FadeDelay({ delay, ...props }: { delay: number } & FadeProps) { const [fadeIn, setFadeIn] = React.useState(false); React.useEffect(() => { const time = setTimeout(() => { setFadeIn(true); }, delay); return () => { clearTimeout(time); }; }, [delay]); return <Fade in={fadeIn} timeout={1000} {...props} />; }
mit
jameswilddev/SprigganTS
Engine/DOM/Transition.ts
6487
class TransitionStepRectangleInstance { private readonly Timer: Timer private readonly From: TransitionStepRectangleKeyFrame private readonly To: TransitionStepRectangleKeyFrame private readonly Element: HTMLDivElement constructor(wrappingElement: HTMLDivElement, timer: Timer, from: TransitionStepRectangleKeyFrame, to: TransitionStepRectangleKeyFrame) { this.From = from this.To = to this.Timer = timer this.Element = document.createElement("div") this.Element.style.position = "absolute" this.SetStyle(("transition" in this.Element.style) ? this.Timer.ElapsedUnitIntervalForTransitions() : 0) wrappingElement.appendChild(this.Element) if ("transition" in this.Element.style) { ForceStyleRefresh(this.Element) this.SetTransition(timer.DurationSeconds - timer.ElapsedSecondsForTransitions()) this.SetStyle(1) } } SetTransition(seconds: number): void { if (seconds < 0) seconds = 0 this.Element.style.transition = `left ${seconds}s linear, right ${seconds}s linear, top ${seconds}s linear, bottom ${seconds}s linear, opacity ${seconds}s linear, background ${seconds}s linear` } SetStyle(progress: number): void { this.Element.style.left = `${Mix(this.From.LeftSignedUnitInterval, this.To.LeftSignedUnitInterval, progress) * 50 + 50}%` this.Element.style.right = `${Mix(this.From.RightSignedUnitInterval, this.To.RightSignedUnitInterval, progress) * -50 + 50}%` this.Element.style.top = `${Mix(this.From.TopSignedUnitInterval, this.To.TopSignedUnitInterval, progress) * 50 + 50}%` this.Element.style.bottom = `${Mix(this.From.BottomSignedUnitInterval, this.To.BottomSignedUnitInterval, progress) * -50 + 50}%` function RgbChannel(from: number, to: number) { return Math.max(0, Math.min(255, Math.round(Mix(from, to, progress) * 255))) } this.Element.style.background = `rgb(${RgbChannel(this.From.RedUnitInterval, this.To.RedUnitInterval)}, ${RgbChannel(this.From.GreenUnitInterval, this.To.GreenUnitInterval)}, ${RgbChannel(this.From.BlueUnitInterval, this.To.BlueUnitInterval)})` this.Element.style.opacity = `${Mix(this.From.OpacityUnitInterval, this.To.OpacityUnitInterval, progress)}` this.Element.style.filter = `alpha(opacity=${Mix(this.From.OpacityUnitInterval, this.To.OpacityUnitInterval, progress) * 100})` } Pause(): void { this.Tick() if ("transition" in this.Element.style) { this.Element.style.transition = "initial" ForceStyleRefresh(this.Element) } } Resume(): void { if ("transition" in this.Element.style) { this.SetStyle(this.Timer.ElapsedUnitIntervalForTransitions()) ForceStyleRefresh(this.Element) this.SetTransition(this.Timer.DurationSeconds - this.Timer.ElapsedSecondsForTransitions()) this.SetStyle(1) } else { this.Tick() } } Tick(): void { this.SetStyle(this.Timer.ElapsedUnitInterval()) } } class TransitionStepInstance { private readonly WrappingElement: HTMLDivElement private readonly Rectangles: TransitionStepRectangleInstance[] = [] constructor(step: TransitionStep, call: () => void) { this.WrappingElement = document.createElement("div") this.WrappingElement.style.position = "absolute" this.WrappingElement.style.left = "0px" this.WrappingElement.style.top = "0px" this.Resize() document.body.appendChild(this.WrappingElement) const timer = new Timer(step.DurationSeconds, () => { call() document.body.removeChild(this.WrappingElement) }) for (const rectangle of step.Rectangles) this.Rectangles.push(new TransitionStepRectangleInstance(this.WrappingElement, timer, rectangle.From, rectangle.To)) } Pause(): void { for (const rectangle of this.Rectangles) rectangle.Pause() } Resume(): void { for (const rectangle of this.Rectangles) rectangle.Resume() } Tick(): void { for (const rectangle of this.Rectangles) rectangle.Tick() } Resize(): void { this.WrappingElement.style.width = `${Display.RealWidthPixels()}px` this.WrappingElement.style.height = `${Display.RealHeightPixels()}px` } } class TransitionInstance { private readonly EntryInstance: TransitionStepInstance private ExitInstance: TransitionStepInstance | undefined constructor(entry: TransitionStep, exit: TransitionStep, call: () => void) { SceneRoot.Instance.Disable() this.EntryInstance = new TransitionStepInstance(entry, () => { call() this.ExitInstance = new TransitionStepInstance(exit, () => { CurrentTransition = undefined SceneRoot.Instance.Enable() }) }) } Resize(): void { if (this.ExitInstance) this.ExitInstance.Resize() else this.EntryInstance.Resize() } Pause(): void { if (this.ExitInstance) this.ExitInstance.Pause() else this.EntryInstance.Pause() } Resume(): void { if (this.ExitInstance) this.ExitInstance.Resume() else this.EntryInstance.Resume() } Tick(): void { if (this.ExitInstance) this.ExitInstance.Tick() else this.EntryInstance.Tick() } } let CurrentTransition: TransitionInstance | undefined function Transition(entry: TransitionStep, exit: TransitionStep, call: () => void): void { if (CurrentTransition) throw "Cannot enter a transition while entering or exiting a previous transition" CurrentTransition = new TransitionInstance(entry, exit, call) } function TickTransition(): boolean { if (!CurrentTransition) return false // IE10+, Edge, Firefox, Chrome. if ("transition" in document.body.style) return false // IE9-. CurrentTransition.Tick() return true } function ResizeTransition(): void { if (!CurrentTransition) return CurrentTransition.Resize() } function PauseTransition(): void { if (!CurrentTransition) return CurrentTransition.Pause() } function ResumeTransition(): void { if (!CurrentTransition) return SceneRoot.Instance.Disable() CurrentTransition.Resume() }
mit
platanus/hound
spec/features/job_failures_spec.rb
1866
require "rails_helper" feature "Job failures" do QUEUE_NAME = "test-job-failures".freeze around :each do |example| previous_backend = Resque::Failure.backend Resque::Failure.backend = Resque::Failure::Redis cleanup_test_failures example.run cleanup_test_failures Resque::Failure.backend = previous_backend end scenario "Admin views all failures" do stub_const("Hound::ADMIN_GITHUB_USERNAMES", ["foo-user"]) user = create(:user, github_username: "foo-user") populate_failures(["Foo error", "Bar error", "Foo error"]) sign_in_as(user) visit admin_job_failures_path expect(table_row(1)).to have_failures("Foo error 0, 2") expect(table_row(2)).to have_failures("Bar error 1") end scenario "Cannot access as a non-admin user" do user = create(:user) populate_failures(["Foo error"]) sign_in_as(user) visit admin_job_failures_path expect(current_path).to eq repos_path expect(page).to have_no_text("Foo error") end scenario "Admin removes job failures" do stub_const("Hound::ADMIN_GITHUB_USERNAMES", ["foo-user"]) user = create(:user, github_username: "foo-user") populate_failures(["Foo error", "Bar error", "Foo error"]) sign_in_as(user) visit admin_job_failures_path find("tr:nth-of-type(1) a").click expect(table_row(1)).to have_failures("Bar error 0") expect(page).not_to have_text("Foo error") end def populate_failures(messages) messages.each do |message| Resque::Failure.create( exception: StandardError.new(message), payload: {}, queue: QUEUE_NAME, ) end end def cleanup_test_failures Resque::Failure.remove_queue(QUEUE_NAME) end def have_failures(text) have_text(text) end def table_row(position) find("tbody tr:nth-of-type(#{position})") end end
mit
Eduardo2505/Denticlick
application/views/productos/lista.php
8851
<!DOCTYPE html> <html lang="es"> <!--<![endif]--> <!-- BEGIN HEAD --> <head> <?php $this->load->view('plantilla/head') ?> </head> <body class="page-header-fixed page-quick-sidebar-over-content "> <!-- BEGIN HEADER --> <div class="page-header -i navbar navbar-fixed-top"> <!-- BEGIN HEADER INNER --> <?php echo $barra; ?> <!-- END HEADER INNER --> </div> <!-- END HEADER --> <div class="clearfix"> </div> <!-- BEGIN CONTAINER --> <div class="page-container"> <?php echo $menu; ?> <!-- END SIDEBAR --> <!-- BEGIN CONTENT --> <div class="page-content-wrapper"> <div class="page-content"> <!-- END PAGE HEADER--> <h3 class="page-title"> Productos <small> </small> </h3> <!-- BEGIN PAGE CONTENT--> <div class="row"> <div class="col-md-12"> <div class="row search-form-default"> <div class="col-md-12"> <form action="<?php echo site_url('') ?>avaluos/mostrar"> <div class="input-group"> <div class="input-cont"> <div class="col-md-12"> <input type="text" name="nombre" class="form-control" placeholder="Nombre .." maxlength="45"> </div> </div> <span class="input-group-btn"> <button type="submit" class="btn green-haze"> Buscar &nbsp; <i class="m-icon-swapright m-icon-white"></i> </button> </span> &nbsp; <span class="input-group-btn"> <a href="<?php echo site_url('') ?>demo/nuevoproductos" class="btn blue"> <i class="fa fa-times"></i> Nueva Producto </a> </span> </div> </form> </br> </div> </div> <div class="tabbable-line boxless tabbable-reversed"> <div class="tab-content"> <div class="tab-pane active" id="tab_1"> <div class="portlet box blue"> <div class="portlet-title"> <div class="caption"> <i class="fa icon-handbag"></i>Lista </div> </div> <div class="portlet-body"> <div class="table-scrollable"> <table class="table table-hover"> <thead> <tr> <th>Nombre</th> <th>Tamaño</th> <th>Unidad</th> <th>Acciones</th> </tr> </thead> <tbody> <tr> <td>Guantes Latex</td> <td>Mediano</td> <td>Talla</td> <td> <a href="<?php echo site_url('') ?>demo/editarproductos" title="Ficha" class="btn btn-sm input-circle blue"> <i class="fa fa-edit"></i> </a> <a href="#" onclick="eliminarH($(this))" title="Desctivar" class="btn input-circle btn-sm red eliminarclass"> <i class="fa fa-times"></i> </a> </td> </tr> </tbody> </table> </div> </div> <div class="pull-right" > <?php echo $pagination; ?> </div> </div> <div style="text-align: center"> <a href="javascript:;" class="btn btn-lg green"> <i class="fa fa-file-excel-o"></i> </a> <a href="javascript:;" class="btn btn-lg red"> <i class="fa fa-file-pdf-o"></i> </a> </div> </div> <div style="display: none"> <a class="btn default" data-target="#static" data-toggle="modal" id="btnmodal"> View Demo </a> </div> <div id="static" class="modal fade" tabindex="-1" data-backdrop="static" data-keyboard="false"> <input type="hidden" id="idHistorial"> <div class="modal-body"> <h4 class="modal-title">¿Esta seguro de eliminar el avalúo ?</h4> </div> <div class="modal-footer"> <button type="button" class="btn btn-success btn-clean" data-dismiss="modal" id="btnaceptar">SI</button> <button type="button" class="btn btn-danger btn-clean" data-dismiss="modal">NO</button> </div> </div> </div> </div> </div> </div> <!-- END PAGE CONTENT--> </div> </div> <!-- END CONTENT --> </div> <!-- END CONTAINER --> <!-- BEGIN FOOTER --> <div class="page-footer"> <div class="page-footer-inner"> 2016 &copy; HelpMex.com.mx </div> <div class="scroll-to-top"> <i class="icon-arrow-up"></i> </div> </div> <!-- END JAVASCRIPTS --> <?php $this->load->view('plantilla/script') ?> <script> jQuery(document).ready(function() { // initiate layout and plugins Layout.init(); // init current layout QuickSidebar.init(); // init quick sidebar Metronic.init(); // init metronic core components Demo.init(); // init demo features ComponentsPickers.init(); }); </script> </body> <!-- END BODY --> </html>
mit
vutranminh/myprofile
public/modules/workplaces/config/workplaces.client.routes.js
124
'use strict'; //Setting up route angular.module('workplaces').config(['$stateProvider', function($stateProvider) { } ]);
mit
ExclamationLabs/sevr
lib/type-loader.js
1396
'use strict' /** * TypeLoader * --- * Load all type definitions from a single * directory and extend the default mongoose * types. Directory path is relative to * `process.cwd()`. * * ## Usage * ``` * const types = TypeLoader('path/to/types') * ``` */ const requireAll = require('require-all') const Types = require('mongoose').Schema.Types module.exports = defPath => { let loadedModules // Load types from directory if (defPath) { loadedModules = requireAll({ dirname: process.cwd() + '/' + defPath, map: name => { return name.replace(/^([a-z])/, (match, char) => { return char.toUpperCase() }) .replace(/[-_]([a-z0-9])/g, (match, char) => { return char.toUpperCase() }) }, resolve: type => { return ext => { let typeObj = Object.assign({}, type(Types), ext) if(!typeObj.name){ typeObj.name = typeObj.type.name } return typeObj } } }) } else { loadedModules = {} } // Wrap the default mongoose types const defaultTypes = Object.keys(Types).reduce((obj, key) => { const name = key.replace(/^(A-Z)/, (match, char) => { return char.toLowerCase() }) const tmpObj = Object.assign({}, obj, { [key]: ext => { return Object.assign({}, { name, type: Types[key] }, ext) } }) return tmpObj }, {}) return Object.assign({}, defaultTypes, loadedModules) }
mit
vasilchavdarov/SoftUniHomework
Matrix - Lab/GrupNumbers/Program.cs
765
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GrupNumbers { class Program { static void Main(string[] args) { var numbers = Console.ReadLine().Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); var zero = numbers.Where(n => Math.Abs(n) % 3 == 0).ToArray(); var one = numbers.Where(n => Math.Abs(n) % 3 == 1).ToArray(); var two = numbers.Where(n => Math.Abs(n) % 3 == 2).ToArray(); Console.WriteLine(string.Join(" ",zero)); Console.WriteLine(string.Join(" ", one)); Console.WriteLine(string.Join(" ", two)); } } }
mit
3pillarlabs/hailstorm-sdk
hailstorm-gem/lib/hailstorm/support/quantile.rb
1169
# frozen_string_literal: true require 'hailstorm/support' # Quartile uses a histogram approach to calculate quartiles with a fast algorithm # without resorting to sorting. # @author Sayantam Dey class Hailstorm::Support::Quantile attr_reader :histogram def initialize @histogram = [] @samples_count = 0 end def push(*elements) elements.each do |e| element = e.to_i if histogram[element].nil? histogram[element] = 1 else histogram[element] += 1 end @samples_count += 1 end end def quantile(at) quantile_value = 0 if @samples_count <= 1000 samples = [] histogram.each_with_index do |freq, value| freq&.times { samples.push(value) } end samples.sort! quantile_index = ((samples.length * at) / 100) - 1 quantile_index = 0 if quantile_index.negative? quantile_value = samples[quantile_index] else sum = 0 index = 0 sum_max = (@samples_count * at) / 100 while sum <= sum_max sum += (histogram[index] || 0) index += 1 end quantile_value = index end quantile_value end end
mit
Styyxxyx/InfiniControl
src/me/xinnir/nscp/listeners/onLogin.java
615
package me.xinnir.nscp.listeners; import me.xinnir.nscp.NSCP; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; /** * Created by maverick on 12/24/13. */ public class onLogin implements Listener { @EventHandler(priority = EventPriority.HIGH) public void playerLoginEvent(PlayerJoinEvent event) { NSCP.getNetwork().createUserData(event.getPlayer().getName(), event.getPlayer().getAddress().toString()); NSCP.getNetwork().initializeChatData(event.getPlayer().getName()); } }
mit
gitadept/instagram-private-api
client/v1/feeds/account-following.js
1182
var _ = require('lodash'); var util = require('util'); var FeedBase = require('./feed-base'); function AccountFollowingFeed(session, accountId, limit) { this.accountId = accountId; this.limit = limit || 7500; // Should be enought for 7500 records this.timeout = 10 * 60 * 1000; FeedBase.apply(this, arguments); } util.inherits(AccountFollowingFeed, FeedBase); module.exports = AccountFollowingFeed; var Request = require('../request'); var Helpers = require('../../../helpers'); var Account = require('../account'); AccountFollowingFeed.prototype.get = function (opts = {}) { var that = this; return new Request(that.session) .setMethod('GET') .setResource('followingFeed', { id: that.accountId, maxId: that.getCursor(), rankToken: Helpers.generateUUID() }) .send(opts) .then(function(data) { that.moreAvailable = !!data.next_max_id; if (that.moreAvailable) that.setCursor(data.next_max_id); return _.map(data.users, function (user) { return new Account(that.session, user); }); }) };
mit
TheTazza/StRADRL
settings/options.py
4114
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf def get_options(option_type): """ option_type: string 'training' or 'diplay' or 'visualize' """ # name tf.app.flags.DEFINE_string("training_name","pong_v1_skipanddropout","name of next training in log") # Common tf.app.flags.DEFINE_string("env_type", "gym", "environment type (lab or gym or maze)") tf.app.flags.DEFINE_string("env_name", "Pong-ram-v4", "environment name (for lab)") tf.app.flags.DEFINE_integer("env_max_steps", 400000, "max number of steps in environment") tf.app.flags.DEFINE_boolean("use_base", False, "whether to use base A3C for aux network") tf.app.flags.DEFINE_boolean("use_pixel_change", False, "whether to use pixel change") tf.app.flags.DEFINE_boolean("use_value_replay", False, "whether to use value function replay") tf.app.flags.DEFINE_boolean("use_reward_prediction", False, "whether to use reward prediction") tf.app.flags.DEFINE_boolean("use_temporal_coherence", False, "whether to use temporal coherence") tf.app.flags.DEFINE_boolean("use_proportionality", False, "whether to use proportionality") tf.app.flags.DEFINE_boolean("use_causality", False, "whether to use causality") tf.app.flags.DEFINE_boolean("use_repeatability", False, "whether to use repeatability") tf.app.flags.DEFINE_string("checkpoint_dir", "/tmp/StRADRL/checkpoints", "checkpoint directory") tf.app.flags.DEFINE_string("temp_dir", "/tmp/StRADRL/tensorboard/", "base directory for tensorboard") tf.app.flags.DEFINE_string("log_dir", "/tmp/StRADRL/log/", "base directory for logs") # For training if option_type == 'training': tf.app.flags.DEFINE_integer("max_time_step", 10**7, "max time steps") tf.app.flags.DEFINE_integer("save_interval_step", 10**8, "saving interval steps") tf.app.flags.DEFINE_boolean("grad_norm_clip", 400.0, "gradient norm clipping") #base tf.app.flags.DEFINE_float("initial_learning_rate", 0.0001, "learning rate") tf.app.flags.DEFINE_float("gamma", 0.99, "discount factor for rewards") tf.app.flags.DEFINE_float("entropy_beta", 0.001, "entropy regurarlization constant") tf.app.flags.DEFINE_float("value_lambda", 0.001, "value ratio for base loss") tf.app.flags.DEFINE_float("base_lambda", 0.9, "generalized adv. est. lamba for short-long sight") # auxiliary tf.app.flags.DEFINE_integer("parallel_size", 1, "parallel thread size") tf.app.flags.DEFINE_float("aux_initial_learning_rate", 0.001, "learning rate") tf.app.flags.DEFINE_float("aux_lambda", 0.0, "generalized adv. est. lamba for short-long sight (aux)") tf.app.flags.DEFINE_float("gamma_pc", 0.9, "discount factor for pixel control") tf.app.flags.DEFINE_float("pixel_change_lambda", 0.0001, "pixel change lambda") # 0.05, 0.01 ~ 0.1 for lab, 0.0001 ~ 0.01 for gym tf.app.flags.DEFINE_float("temporal_coherence_lambda", 1., "temporal coherence lambda") tf.app.flags.DEFINE_float("proportionality_lambda", 100., "proportionality lambda") tf.app.flags.DEFINE_float("causality_lambda", 1., "causality lambda") tf.app.flags.DEFINE_float("repeatability_lambda", 100., "repeatability lambda") tf.app.flags.DEFINE_integer("experience_history_size", 100000, "experience replay buffer size") # queuer tf.app.flags.DEFINE_integer("local_t_max", 20, "repeat step size") tf.app.flags.DEFINE_integer("queue_length", 5, "max number of batches (of length local_t_max) in queue") tf.app.flags.DEFINE_integer("env_runner_sync", 1, "number of env episodes before sync to global") tf.app.flags.DEFINE_float("action_freq", 0, "number of actions per second in env") # For display if option_type == 'display': tf.app.flags.DEFINE_string("frame_save_dir", "/tmp/StRADRL_frames", "frame save directory") tf.app.flags.DEFINE_boolean("recording", False, "whether to record movie") tf.app.flags.DEFINE_boolean("frame_saving", False, "whether to save frames") return tf.app.flags.FLAGS
mit
chiave/gamp
public_html/ckeditor/lang/el.js
4753
/** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.lang} object, for the * Greek language. */ /**#@+ @type String @example */ /** * Contains the dictionary of language entries. * @namespace */ CKEDITOR.lang[ 'el' ] = { // ARIA description. editor: 'Επεξεργαστής Πλούσιου Κειμένου', editorPanel: 'Πίνακας Επεξεργαστή Πλούσιου Κειμένου', // Common messages and labels. common: { // Screenreader titles. Please note that screenreaders are not always capable // of reading non-English words. So be careful while translating it. editorHelp: 'Πατήστε το ALT 0 για βοήθεια', browseServer: 'Εξερεύνηση Διακομιστή', url: 'URL', protocol: 'Πρωτόκολλο', upload: 'Αποστολή', uploadSubmit: 'Αποστολή στον Διακομιστή', image: 'Εικόνα', flash: 'Flash', form: 'Φόρμα', checkbox: 'Κουτί Επιλογής', radio: 'Κουμπί Επιλογής', textField: 'Πεδίο Κειμένου', textarea: 'Περιοχή Κειμένου', hiddenField: 'Κρυφό Πεδίο', button: 'Κουμπί', select: 'Πεδίο Επιλογής', imageButton: 'Κουμπί Εικόνας', notSet: '<δεν έχει ρυθμιστεί>', id: 'Id', name: 'Όνομα', langDir: 'Κατεύθυνση Κειμένου', langDirLtr: 'Αριστερά προς Δεξιά (LTR)', langDirRtl: 'Δεξιά προς Αριστερά (RTL)', langCode: 'Κωδικός Γλώσσας', longDescr: 'Αναλυτική Περιγραφή URL', cssClass: 'Κλάσεις Φύλλων Στυλ', advisoryTitle: 'Ενδεικτικός Τίτλος', cssStyle: 'Μορφή Κειμένου', ok: 'OK', cancel: 'Ακύρωση', close: 'Κλείσιμο', preview: 'Προεπισκόπηση', resize: 'Αλλαγή Μεγέθους', generalTab: 'Γενικά', advancedTab: 'Για Προχωρημένους', validateNumberFailed: 'Αυτή η τιμή δεν είναι αριθμός.', confirmNewPage: 'Οι όποιες αλλαγές στο περιεχόμενο θα χαθούν. Είσαστε σίγουροι ότι θέλετε να φορτώσετε μια νέα σελίδα;', confirmCancel: 'Μερικές επιλογές έχουν αλλάξει. Είσαστε σίγουροι ότι θέλετε να κλείσετε το παράθυρο διαλόγου;', options: 'Επιλογές', target: 'Προορισμός', targetNew: 'Νέο Παράθυρο (_blank)', targetTop: 'Αρχική Περιοχή (_top)', targetSelf: 'Ίδιο Παράθυρο (_self)', targetParent: 'Γονεϊκό Παράθυρο (_parent)', langDirLTR: 'Αριστερά προς Δεξιά (LTR)', langDirRTL: 'Δεξιά προς Αριστερά (RTL)', styles: 'Μορφή', cssClasses: 'Κλάσεις Φύλλων Στυλ', width: 'Πλάτος', height: 'Ύψος', align: 'Στοίχιση', alignLeft: 'Αριστερά', alignRight: 'Δεξιά', alignCenter: 'Κέντρο', alignTop: 'Πάνω', alignMiddle: 'Μέση', alignBottom: 'Κάτω', invalidValue : 'Μη έγκυρη τιμή.', invalidHeight: 'Το ύψος πρέπει να είναι ένας αριθμός.', invalidWidth: 'Το πλάτος πρέπει να είναι ένας αριθμός.', invalidCssLength: 'Η τιμή που ορίζεται για το πεδίο "%1" πρέπει να είναι ένας θετικός αριθμός με ή χωρίς μια έγκυρη μονάδα μέτρησης CSS (px, %, in, cm, mm, em, ex, pt, ή pc).', invalidHtmlLength: 'Η τιμή που ορίζεται για το πεδίο "%1" πρέπει να είναι ένας θετικός αριθμός με ή χωρίς μια έγκυρη μονάδα μέτρησης HTML (px ή %).', invalidInlineStyle: 'Η τιμή για το εν σειρά στυλ πρέπει να περιέχει ένα ή περισσότερα ζεύγη με την μορφή "όνομα: τιμή" διαχωρισμένα με Ελληνικό ερωτηματικό.', cssLengthTooltip: 'Εισάγεται μια τιμή σε pixel ή έναν αριθμό μαζί με μια έγκυρη μονάδα μέτρησης CSS (px, %, in, cm, mm, em, ex, pt, ή pc).', // Put the voice-only part of the label in the span. unavailable: '%1<span class="cke_accessibility">, δεν είναι διαθέσιμο</span>' } };
mit
jhogsett/linkit
python/fun8.py
922
import serial import time import random s = None inter_command_delay = 0.0 def command(cmd_text): s.write((cmd_text + '|').encode()) time.sleep(inter_command_delay) def setup(): global s s = serial.Serial("/dev/ttyS0", 57600) # command("fade") # time.sleep(2) command("erase") blink_map = { 0 : "blink1", 1 : "blink2", 2 : "blink3", 3 : "blink4", 4 : "blink5", 5 : "blink6" } def run(): while True: command("pause") for x in range(0, 8): choice = random.randrange(0, 6) for y in range(0, 6): blink = blink_map[choice] command("random") command(blink) for y in range(0, 2): command('random|static') command("continue") time.sleep(10.0) if __name__ == '__main__': setup() run()
mit
QuackerTeam/quacker
src/Quacker.Filtering/FilteringApp.cs
683
using Quacker.Filtering.Interfaces; using System; namespace Quacker.Filtering { public static class FilteringApp { public static void Initialize(Action<IFilteringConfiguration> configurationAction) { if (configurationAction == null) throw new ArgumentNullException(nameof(configurationAction)); try { configurationAction(new FilteringConfiguration()); } catch (Exception ex) { throw new InvalidOperationException("Uncaught error ocurred in initialization. See inner exception for further details.", ex); } } } }
mit
cuckata23/wurfl-data
data/nokia_7380_ver1_sub0380.php
132
<?php return array ( 'id' => 'nokia_7380_ver1_sub0380', 'fallback' => 'nokia_7380_ver1', 'capabilities' => array ( ), );
mit
elfadl/OCFA_Client
application/config/config.php
17878
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | Base Site URL |-------------------------------------------------------------------------- | | URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash: | | http://example.com/ | | If this is not set then CodeIgniter will try guess the protocol, domain | and path to your installation. However, you should always configure this | explicitly and never rely on auto-guessing, especially in production | environments. | */ $config['base_url'] = 'http://localhost/OCFA_Client/'; /* |-------------------------------------------------------------------------- | Index File |-------------------------------------------------------------------------- | | Typically this will be your index.php file, unless you've renamed it to | something else. If you are using mod_rewrite to remove the page set this | variable so that it is blank. | */ $config['index_page'] = ''; /* |-------------------------------------------------------------------------- | URI PROTOCOL |-------------------------------------------------------------------------- | | This item determines which server global should be used to retrieve the | URI string. The default setting of 'REQUEST_URI' works for most servers. | If your links do not seem to work, try one of the other delicious flavors: | | 'REQUEST_URI' Uses $_SERVER['REQUEST_URI'] | 'QUERY_STRING' Uses $_SERVER['QUERY_STRING'] | 'PATH_INFO' Uses $_SERVER['PATH_INFO'] | | WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded! */ $config['uri_protocol'] = 'REQUEST_URI'; /* |-------------------------------------------------------------------------- | URL suffix |-------------------------------------------------------------------------- | | This option allows you to add a suffix to all URLs generated by CodeIgniter. | For more information please see the user guide: | | http://codeigniter.com/user_guide/general/urls.html */ $config['url_suffix'] = ''; /* |-------------------------------------------------------------------------- | Default Language |-------------------------------------------------------------------------- | | This determines which set of language files should be used. Make sure | there is an available translation if you intend to use something other | than english. | */ $config['language'] = 'english'; /* |-------------------------------------------------------------------------- | Default Character Set |-------------------------------------------------------------------------- | | This determines which character set is used by default in various methods | that require a character set to be provided. | | See http://php.net/htmlspecialchars for a list of supported charsets. | */ $config['charset'] = 'UTF-8'; /* |-------------------------------------------------------------------------- | Enable/Disable System Hooks |-------------------------------------------------------------------------- | | If you would like to use the 'hooks' feature you must enable it by | setting this variable to TRUE (boolean). See the user guide for details. | */ $config['enable_hooks'] = FALSE; /* |-------------------------------------------------------------------------- | Class Extension Prefix |-------------------------------------------------------------------------- | | This item allows you to set the filename/classname prefix when extending | native libraries. For more information please see the user guide: | | http://codeigniter.com/user_guide/general/core_classes.html | http://codeigniter.com/user_guide/general/creating_libraries.html | */ $config['subclass_prefix'] = 'MY_'; /* |-------------------------------------------------------------------------- | Composer auto-loading |-------------------------------------------------------------------------- | | Enabling this setting will tell CodeIgniter to look for a Composer | package auto-loader script in application/vendor/autoload.php. | | $config['composer_autoload'] = TRUE; | | Or if you have your vendor/ directory located somewhere else, you | can opt to set a specific path as well: | | $config['composer_autoload'] = '/path/to/vendor/autoload.php'; | | For more information about Composer, please visit http://getcomposer.org/ | | Note: This will NOT disable or override the CodeIgniter-specific | autoloading (application/config/autoload.php) */ $config['composer_autoload'] = FALSE; /* |-------------------------------------------------------------------------- | Allowed URL Characters |-------------------------------------------------------------------------- | | This lets you specify which characters are permitted within your URLs. | When someone tries to submit a URL with disallowed characters they will | get a warning message. | | As a security measure you are STRONGLY encouraged to restrict URLs to | as few characters as possible. By default only these are allowed: a-z 0-9~%.:_- | | Leave blank to allow all characters -- but only if you are insane. | | The configured value is actually a regular expression character group | and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i | | DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! | */ $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; /* |-------------------------------------------------------------------------- | Enable Query Strings |-------------------------------------------------------------------------- | | By default CodeIgniter uses search-engine friendly segment based URLs: | example.com/who/what/where/ | | By default CodeIgniter enables access to the $_GET array. If for some | reason you would like to disable it, set 'allow_get_array' to FALSE. | | You can optionally enable standard query string based URLs: | example.com?who=me&what=something&where=here | | Options are: TRUE or FALSE (boolean) | | The other items let you set the query string 'words' that will | invoke your controllers and its functions: | example.com/index.php?c=controller&m=function | | Please note that some of the helpers won't work as expected when | this feature is enabled, since CodeIgniter is designed primarily to | use segment based URLs. | */ $config['allow_get_array'] = TRUE; $config['enable_query_strings'] = FALSE; $config['controller_trigger'] = 'c'; $config['function_trigger'] = 'm'; $config['directory_trigger'] = 'd'; /* |-------------------------------------------------------------------------- | Error Logging Threshold |-------------------------------------------------------------------------- | | You can enable error logging by setting a threshold over zero. The | threshold determines what gets logged. Threshold options are: | | 0 = Disables logging, Error logging TURNED OFF | 1 = Error Messages (including PHP errors) | 2 = Debug Messages | 3 = Informational Messages | 4 = All Messages | | You can also pass an array with threshold levels to show individual error types | | array(2) = Debug Messages, without Error Messages | | For a live site you'll usually only enable Errors (1) to be logged otherwise | your log files will fill up very fast. | */ $config['log_threshold'] = 0; /* |-------------------------------------------------------------------------- | Error Logging Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/logs/ directory. Use a full server path with trailing slash. | */ $config['log_path'] = ''; /* |-------------------------------------------------------------------------- | Log File Extension |-------------------------------------------------------------------------- | | The default filename extension for log files. The default 'php' allows for | protecting the log files via basic scripting, when they are to be stored | under a publicly accessible directory. | | Note: Leaving it blank will default to 'php'. | */ $config['log_file_extension'] = ''; /* |-------------------------------------------------------------------------- | Log File Permissions |-------------------------------------------------------------------------- | | The file system permissions to be applied on newly created log files. | | IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal | integer notation (i.e. 0700, 0644, etc.) */ $config['log_file_permissions'] = 0644; /* |-------------------------------------------------------------------------- | Date Format for Logs |-------------------------------------------------------------------------- | | Each item that is logged has an associated date. You can use PHP date | codes to set your own date formatting | */ $config['log_date_format'] = 'Y-m-d H:i:s'; /* |-------------------------------------------------------------------------- | Error Views Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/views/errors/ directory. Use a full server path with trailing slash. | */ $config['error_views_path'] = ''; /* |-------------------------------------------------------------------------- | Cache Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/cache/ directory. Use a full server path with trailing slash. | */ $config['cache_path'] = ''; /* |-------------------------------------------------------------------------- | Cache Include Query String |-------------------------------------------------------------------------- | | Whether to take the URL query string into consideration when generating | output cache files. Valid options are: | | FALSE = Disabled | TRUE = Enabled, take all query parameters into account. | Please be aware that this may result in numerous cache | files generated for the same page over and over again. | array('q') = Enabled, but only take into account the specified list | of query parameters. | */ $config['cache_query_string'] = FALSE; /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | If you use the Encryption class, you must set an encryption key. | See the user guide for more info. | | http://codeigniter.com/user_guide/libraries/encryption.html | */ $config['encryption_key'] = ''; /* |-------------------------------------------------------------------------- | Session Variables |-------------------------------------------------------------------------- | | 'sess_driver' | | The storage driver to use: files, database, redis, memcached | | 'sess_cookie_name' | | The session cookie name, must contain only [0-9a-z_-] characters | | 'sess_expiration' | | The number of SECONDS you want the session to last. | Setting to 0 (zero) means expire when the browser is closed. | | 'sess_save_path' | | The location to save sessions to, driver dependent. | | For the 'files' driver, it's a path to a writable directory. | WARNING: Only absolute paths are supported! | | For the 'database' driver, it's a table name. | Please read up the manual for the format with other session drivers. | | IMPORTANT: You are REQUIRED to set a valid save path! | | 'sess_match_ip' | | Whether to match the user's IP address when reading the session data. | | WARNING: If you're using the database driver, don't forget to update | your session table's PRIMARY KEY when changing this setting. | | 'sess_time_to_update' | | How many seconds between CI regenerating the session ID. | | 'sess_regenerate_destroy' | | Whether to destroy session data associated with the old session ID | when auto-regenerating the session ID. When set to FALSE, the data | will be later deleted by the garbage collector. | | Other session cookie settings are shared with the rest of the application, | except for 'cookie_prefix' and 'cookie_httponly', which are ignored here. | */ $config['sess_driver'] = 'files'; $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_save_path'] = NULL; $config['sess_match_ip'] = FALSE; $config['sess_time_to_update'] = 300; $config['sess_regenerate_destroy'] = FALSE; /* |-------------------------------------------------------------------------- | Cookie Related Variables |-------------------------------------------------------------------------- | | 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions | 'cookie_domain' = Set to .your-domain.com for site-wide cookies | 'cookie_path' = Typically will be a forward slash | 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists. | 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript) | | Note: These settings (with the exception of 'cookie_prefix' and | 'cookie_httponly') will also affect sessions. | */ $config['cookie_prefix'] = ''; $config['cookie_domain'] = ''; $config['cookie_path'] = '/'; $config['cookie_secure'] = FALSE; $config['cookie_httponly'] = FALSE; /* |-------------------------------------------------------------------------- | Standardize newlines |-------------------------------------------------------------------------- | | Determines whether to standardize newline characters in input data, | meaning to replace \r\n, \r, \n occurrences with the PHP_EOL value. | | This is particularly useful for portability between UNIX-based OSes, | (usually \n) and Windows (\r\n). | */ $config['standardize_newlines'] = FALSE; /* |-------------------------------------------------------------------------- | Global XSS Filtering |-------------------------------------------------------------------------- | | Determines whether the XSS filter is always active when GET, POST or | COOKIE data is encountered | | WARNING: This feature is DEPRECATED and currently available only | for backwards compatibility purposes! | */ $config['global_xss_filtering'] = FALSE; /* |-------------------------------------------------------------------------- | Cross Site Request Forgery |-------------------------------------------------------------------------- | Enables a CSRF cookie token to be set. When set to TRUE, token will be | checked on a submitted form. If you are accepting user data, it is strongly | recommended CSRF protection be enabled. | | 'csrf_token_name' = The token name | 'csrf_cookie_name' = The cookie name | 'csrf_expire' = The number in seconds the token should expire. | 'csrf_regenerate' = Regenerate token on every submission | 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks */ $config['csrf_protection'] = FALSE; $config['csrf_token_name'] = 'csrf_test_name'; $config['csrf_cookie_name'] = 'csrf_cookie_name'; $config['csrf_expire'] = 7200; $config['csrf_regenerate'] = TRUE; $config['csrf_exclude_uris'] = array(); /* |-------------------------------------------------------------------------- | Output Compression |-------------------------------------------------------------------------- | | Enables Gzip output compression for faster page loads. When enabled, | the output class will test whether your server supports Gzip. | Even if it does, however, not all browsers support compression | so enable only if you are reasonably sure your visitors can handle it. | | Only used if zlib.output_compression is turned off in your php.ini. | Please do not use it together with httpd-level output compression. | | VERY IMPORTANT: If you are getting a blank page when compression is enabled it | means you are prematurely outputting something to your browser. It could | even be a line of whitespace at the end of one of your scripts. For | compression to work, nothing can be sent before the output buffer is called | by the output class. Do not 'echo' any values with compression enabled. | */ $config['compress_output'] = FALSE; /* |-------------------------------------------------------------------------- | Master Time Reference |-------------------------------------------------------------------------- | | Options are 'local' or any PHP supported timezone. This preference tells | the system whether to use your server's local time as the master 'now' | reference, or convert it to the configured one timezone. See the 'date | helper' page of the user guide for information regarding date handling. | */ $config['time_reference'] = 'local'; /* |-------------------------------------------------------------------------- | Rewrite PHP Short Tags |-------------------------------------------------------------------------- | | If your PHP installation does not have short tag support enabled CI | can rewrite the tags on-the-fly, enabling you to utilize that syntax | in your view files. Options are TRUE or FALSE (boolean) | | Note: You need to have eval() enabled for this to work. | */ $config['rewrite_short_tags'] = FALSE; /* |-------------------------------------------------------------------------- | Reverse Proxy IPs |-------------------------------------------------------------------------- | | If your server is behind a reverse proxy, you must whitelist the proxy | IP addresses from which CodeIgniter should trust headers such as | HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify | the visitor's IP address. | | You can use both an array or a comma-separated list of proxy addresses, | as well as specifying whole subnets. Here are a few examples: | | Comma-separated: '10.0.1.200,192.168.5.0/24' | Array: array('10.0.1.200', '192.168.5.0/24') */ $config['proxy_ips'] = '';
mit
cdeil/slippy-astro-images
visiomatic/main.js
1172
var header_url = "https://raw.githubusercontent.com/cdeil/fermi-ts-maps/master/header.txt"; var header; jQuery.get(header_url, function(data) { header = data; }); // var map = L.map('map', {crs = L.CRS.wcs(hdr)}); // create the slippy map var map = L.map('map', { minZoom: 1, maxZoom: 4, center: [0, 0], zoom: 1, // crs: L.CRS.Simple crs: L.CRS.wcs(header) }); // dimensions of the image var w = 10001; var h = 401; var url = 'https://raw.githubusercontent.com/cdeil/fermi-ts-maps/master/emin_0030_emax_0100.png'; // calculate the edges of the image, in coordinate space var southWest = map.unproject([0, h], map.getMaxZoom()-1); var northEast = map.unproject([w, 0], map.getMaxZoom()-1); var bounds = new L.LatLngBounds(southWest, northEast); // add the image overlay, // so that it covers the entire map L.imageOverlay(url, bounds).addTo(map); // tell leaflet that the map is exactly as big as the image map.setMaxBounds(bounds); L.marker([200, 50]).addTo(map); L.marker(map.unproject([200, 50])).addTo(map); var circle = L.circle(map.unproject([300, 10]), 1000, { color: 'green', fillColor: 'green', fillOpacity: 0.3 }).addTo(map);
mit
alex-cory/google-students
old/config.php
594
<?php // SITE CONSTANTS /* ----------------------------------------------- PATHS -------------------------------------------------*/ //define ("ABSOLUTE_PATH", "/home/alexcory"); define("URL_ROOT", 'http://techtalksfsu.edu/'); // LOCALHOST define("ROOT_PATH", $_SERVER["DOCUMENT_ROOT"] . "/"); //(goes in includes & requires) define("HELLO_WORLD", "hello effing world"); define('CSS_PATH', 'css/'); define('JS_PATH', 'js/'); // define ('IMG_PATH'); /* ----------------------------------------------- OTHER -------------------------------------------------*/ ?>
mit
miled/wordpress-social-login
hybridauth/library/src/Provider/Telegram.php
6171
<?php namespace Hybridauth\Provider; use Hybridauth\HttpClient\Util; use Hybridauth\Data\Collection; use Hybridauth\User\Profile; use Hybridauth\Adapter\AbstractAdapter; use Hybridauth\Adapter\AdapterInterface; use Hybridauth\Exception\InvalidApplicationCredentialsException; use Hybridauth\Exception\InvalidAuthorizationCodeException; use Hybridauth\Exception\UnexpectedApiResponseException; /** * Telegram provider adapter. * * To set up Telegram you need to interactively create a bot using the * Telegram mobile app, talking to botfather. The minimum conversation * will look like: * * /newbot * My Bot Title * nameofmynewbot * /setdomain * @nameofmynewbot * mydomain.com * * Example: * * $config = [ * 'callback' => Hybridauth\HttpClient\Util::getCurrentUrl(), * 'keys' => ['id' => 'your_bot_name', 'secret' => 'your_bot_token'], * ]; * * $adapter = new Hybridauth\Provider\Telegram($config); * * try { * $adapter->authenticate(); * * $userProfile = $adapter->getUserProfile(); * } catch (\Exception $e) { * print $e->getMessage(); * } */ class Telegram extends AbstractAdapter implements AdapterInterface { protected $botId = ''; protected $botSecret = ''; protected $callbackUrl = ''; /** * IPD API Documentation * * OPTIONAL. * * @var string */ protected $apiDocumentation = 'https://core.telegram.org/bots'; /** * {@inheritdoc} */ protected function configure() { $this->botId = $this->config->filter('keys')->get('id'); $this->botSecret = $this->config->filter('keys')->get('secret'); $this->callbackUrl = $this->config->get('callback'); if (!$this->botId || !$this->botSecret) { throw new InvalidApplicationCredentialsException( 'Your application id is required in order to connect to ' . $this->providerId ); } } /** * {@inheritdoc} */ protected function initialize() { } /** * {@inheritdoc} */ public function authenticate() { $this->logger->info(sprintf('%s::authenticate()', get_class($this))); if (!filter_input(INPUT_GET, 'hash')) { $this->authenticateBegin(); } else { $this->authenticateCheckError(); $this->authenticateFinish(); } return null; } /** * {@inheritdoc} */ public function isConnected() { $authData = $this->getStoredData('auth_data'); return !empty($authData); } /** * {@inheritdoc} */ public function getUserProfile() { $data = new Collection($this->getStoredData('auth_data')); if (!$data->exists('id')) { throw new UnexpectedApiResponseException('Provider API returned an unexpected response.'); } $userProfile = new Profile(); $userProfile->identifier = $data->get('id'); $userProfile->firstName = $data->get('first_name'); $userProfile->lastName = $data->get('last_name'); $userProfile->displayName = $data->get('username'); $userProfile->photoURL = $data->get('photo_url'); $username = $data->get('username'); if (!empty($username)) { // Only some accounts have usernames. $userProfile->profileURL = "https://t.me/{$username}"; } return $userProfile; } /** * See: https://telegram.im/widget-login.php * See: https://gist.github.com/anonymous/6516521b1fb3b464534fbc30ea3573c2 */ protected function authenticateCheckError() { $auth_data = $this->parseAuthData(); $check_hash = $auth_data['hash']; unset($auth_data['hash']); $data_check_arr = []; foreach ($auth_data as $key => $value) { if (!empty($value)) { $data_check_arr[] = $key . '=' . $value; } } sort($data_check_arr); $data_check_string = implode("\n", $data_check_arr); $secret_key = hash('sha256', $this->botSecret, true); $hash = hash_hmac('sha256', $data_check_string, $secret_key); if (strcmp($hash, $check_hash) !== 0) { throw new InvalidAuthorizationCodeException( sprintf('Provider returned an error: %s', 'Data is NOT from Telegram') ); } if ((time() - $auth_data['auth_date']) > 86400) { throw new InvalidAuthorizationCodeException( sprintf('Provider returned an error: %s', 'Data is outdated') ); } } /** * See: https://telegram.im/widget-login.php */ protected function authenticateBegin() { $this->logger->debug(sprintf('%s::authenticateBegin(), redirecting user to:', get_class($this))); $nonce = $this->config->get('nonce'); $nonce_code = empty($nonce) ? '' : "nonce=\"{$nonce}\""; exit( <<<HTML <center> <script async src="https://telegram.org/js/telegram-widget.js?7" {$nonce_code} data-telegram-login="{$this->botId}" data-size="large" data-auth-url="{$this->callbackUrl}" data-request-access="write"> </script> </center> HTML ); } protected function authenticateFinish() { $this->logger->debug( sprintf('%s::authenticateFinish(), callback url:', get_class($this)), [Util::getCurrentUrl(true)] ); $this->storeData('auth_data', $this->parseAuthData()); $this->initialize(); } protected function parseAuthData() { return [ 'id' => filter_input(INPUT_GET, 'id'), 'first_name' => filter_input(INPUT_GET, 'first_name'), 'last_name' => filter_input(INPUT_GET, 'last_name'), 'username' => filter_input(INPUT_GET, 'username'), 'photo_url' => filter_input(INPUT_GET, 'photo_url'), 'auth_date' => filter_input(INPUT_GET, 'auth_date'), 'hash' => filter_input(INPUT_GET, 'hash'), ]; } }
mit
escoffon/fl-framework
app/controllers/fl/framework/attachments_controller.rb
3514
require_dependency "fl/framework/application_controller" module Fl::Framework class AttachmentsController < ApplicationController include Fl::Framework::Controller::Helper include Fl::Framework::Controller::Access # This method is a placeholder for access control. Applications that support a notion of a logged-in # users will provide their own implementation, and must remove this one. # For example: # module Fl::Framework # class AttachmentsController < ::ApplicationController # before_action :authenticate_user!, except: [ :index, :show ] # end # end def current_user() nil end # GET /attachments def index @attachments = Attachment.all end # GET /attachments/1 def show p = normalize_params(params) service = Fl::Framework::Service::Attachment::ActiveRecord.new(Fl::Framework::Comment::ActiveRecord::Comment, current_user, p) if get_and_check(service, Fl::Framework::Access::Grants::READ, '@attachment') respond_to do |format| format.json do render(:json => { :attachment => hash_one_object(@attachment, p[:to_hash]) }, status: :ok) end end else respond_to do |format| format.html format.json do error_response(generate_error_info(service)) end end end end # GET /attachments/new def new @attachment = Attachment.new end # GET /attachments/1/edit def edit end # POST /attachments def create @attachment = Attachment.new(attachment_params) if @attachment.save redirect_to @attachment, notice: 'Attachment was successfully created.' else render :new end end # PATCH/PUT /attachments/1 def update service = Fl::Framework::Service::Attachment::ActiveRecord.new(Fl::Framework::Comment::ActiveRecord::Comment, current_user, nil, self) @attachment = service.update() if @attachment && service.success? respond_to do |format| format.json do render(:json => { :attachment => hash_one_object(@attachment, service.params[:to_hash]) }, status: :ok) end end else respond_to do |format| format.html format.json do error_response(generate_error_info(service, @attachment)) end end end end # DELETE /attachments/1 def destroy p = normalize_params(params) service = Fl::Framework::Service::Attachment::ActiveRecord.new(Fl::Framework::Comment::ActiveRecord::Comment, current_user, p) if get_and_check(service, Fl::Framework::Access::Grants::DESTROY, '@attachment') fingerprint = @attachment.fingerprint if @attachment.destroy respond_to do |format| format.json do status_response({ status: Fl::Framework::Service::OK, message: tx('fl.framework.attachment.controller.actions.destroy.deleted', fingerprint: fingerprint) }) end end else respond_to do |format| format.html format.json do error_response(generate_error_info(service)) end end end end end private end end
mit
lukaszsliwa/hardcoded_enumeration
lib/hardcoded_enumeration/base.rb
1624
module HardcodedEnumeration class Base attr_reader :symbol attr_reader :id def self.enumerates(*symbol_list) @instances = [] @instances_by_symbol = {} @instances_by_id = {} symbol_list.each_with_index do |symbol, id| instance = new(symbol, id + 1) @instances << instance @instances_by_id[instance.id] = instance @instances_by_symbol[instance.symbol] = instance define_method("#{symbol}?") do self == instance end end end def self.instances @instances end def self.find_by_key(key) case key when self then key when Symbol then @instances_by_symbol[key] when Integer then @instances_by_id[key] when String then @instances_by_id[key.to_i] end end def self.find(key) key == :all ? @instances : self[key] end def self.[](key) find_by_key(key) or raise ActiveRecord::RecordNotFound.new("No #{self.class} instance for #{key} #{key.class}") end def ==(key) RAILS_DEFAULT_LOGGER.debug "Comparing #{self.inspect} to #{key}(#{key.class})" case key when Symbol then @symbol == key when self.class then @id == key.id else false end end def inspect "#<#{self.class}:#{self.object_id}(id: #{@id}, symbol: #{@symbol})>" end def to_param id end def to_s symbol.to_s end def to_sym symbol end protected def initialize(symbol, id) @symbol = symbol @id = id end end end
mit
sindresorhus/archs
test.js
156
import process from 'node:process'; import test from 'ava'; import archs from './index.js'; test('main', t => { t.true(archs.includes(process.arch)); });
mit
Symfony-Plugins/sfTrafficCMSPlugin
lib/sfCMSImage.class.php
1392
<?php class sfCMSImage { public static function get($category, $name, $default = '') { if ($content = sfTrafficCMSImageTable::getInstance()->findOneBycategoryAndName($category, $name)) { return $content; } return $default; } public static function getAll($category, $name) { $images = array(); foreach (sfTrafficCMSImageTable::getInstance()->findByCategoryAndName($category, $name) as $content) { $images[] = $content; } return $images; } public static function getSrc($category, $name, $default = '') { if ($content = self::get($category, $name, $default)) { return $content->getImageSrc('main'); } return $default; } public static function getSrcAll($category, $name) { $values = array(); foreach (self::getAll($category, $name) as $content) { $values[] = $content->getImageSrc('main'); } return $values; } public static function getAlt($category, $name, $default = '') { if ($content = self::get($category, $name, $default)) { return $content->alt; } return $default; } public static function getAltAll($category, $name) { $values = array(); foreach (self::getAll($category, $name) as $content) { $values[] = $content->alt; } return $values; } }
mit
mideveloper/jasolver
Jasolver/Properties/AssemblyInfo.cs
1392
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("JaSolver")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("JaSolver")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2bd46046-2b3d-4e2b-b753-cb98074db95e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
RThomasHyde/Ephemera.Tiff
Ephemera.Tiff.Test/TiffDocumentTest.cs
11331
using System; using System.IO; using System.Reflection; using Ephemera.Tiff; using Xunit; namespace TiffDocumentTest { /// <summary> /// These unit tests cover all of the images from the libtiff sample set. Each image /// is loaded from disk into a TiffDocument instance, which is then saved to a memory /// stream, which is subsequently loaded back into a new TiffDocument instance. The /// fields of each directory of the latter are then checked against the original values /// (derived from the output of tiffdump for each image) to insure that: /// a) the data is being read from the tiff file correctly, and /// b) all directories and their fields survive a roundtrip intact. /// /// These tests do not confirm that TIFF files produced by a TiffDocument instance /// are able to be decoded (i.e. are valid image files). Not all of the images in the /// libtiff sample set are able to be decoded by .NET, so I am not sure how to /// reliably test this without taking a dependency (in the test project) on another /// library which knows how to decode all the different TIFF flavors (e.g. LibTiff.Net). /// </summary> public class TiffDocumentTest : IDisposable { private readonly string inputDir; private readonly string outputDir; public TiffDocumentTest() { var codeBaseUrl = new Uri(Assembly.GetExecutingAssembly().CodeBase); var codeBasePath = Uri.UnescapeDataString(codeBaseUrl.AbsolutePath); var dirPath = Path.GetDirectoryName(codeBasePath) ?? ""; inputDir = Path.Combine(dirPath, "TestImages"); outputDir = Path.Combine(dirPath, "TestOutput"); Directory.CreateDirectory(outputDir); } public void Dispose() { Directory.Delete(outputDir, true); } [Fact] public void TestCramps() { var imagePath = Path.Combine(inputDir, "cramps.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckCramps(saved.Directories[0]); } [Fact] public void TestCrampsTiled() { var imagePath = Path.Combine(inputDir, "cramps-tile.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckCrampsTiled(saved.Directories[0]); } [Fact] public void TestFax2D() { var imagePath = Path.Combine(inputDir, "fax2d.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckFax2D(saved.Directories[0]); } [Fact] public void TestG3Test() { var imagePath = Path.Combine(inputDir, "g3test.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckG3Test(saved.Directories[0]); } [Fact] public void TestJello() { var imagePath = Path.Combine(inputDir, "jello.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckJello(saved.Directories[0]); } [Fact] public void TestJim___Ah() { var imagePath = Path.Combine(inputDir, "jim___ah.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckJim___Ah(saved.Directories[0]); } [Fact] public void TestJim___Cg() { var imagePath = Path.Combine(inputDir, "jim___cg.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckJim___Cg(saved.Directories[0]); } [Fact] public void TestJim___Dg() { var imagePath = Path.Combine(inputDir, "jim___dg.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckJim___Dg(saved.Directories[0]); } [Fact] public void TestJim___Gg() { var imagePath = Path.Combine(inputDir, "jim___gg.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckJim___Gg(saved.Directories[0]); } [Fact] public void TestOff_L16() { var imagePath = Path.Combine(inputDir, "off_l16.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckOff_L16(saved.Directories[0]); } [Fact] public void TestOff_Luv24() { var imagePath = Path.Combine(inputDir, "off_luv24.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckOff_Luv24(saved.Directories[0]); } [Fact] public void TestOff_Luv32() { var imagePath = Path.Combine(inputDir, "off_luv32.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckOff_Luv32(saved.Directories[0]); } [Fact] public void TestOxford() { var imagePath = Path.Combine(inputDir, "oxford.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckOxford(saved.Directories[0]); } [Fact] public void TestQuadJpeg() { var imagePath = Path.Combine(inputDir, "quad-jpeg.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckQuadJpeg(saved.Directories[0]); } [Fact] public void TestQuadLzw() { var imagePath = Path.Combine(inputDir, "quad-lzw.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckQuadLzw(saved.Directories[0]); } [Fact] public void TestQuadTile() { var imagePath = Path.Combine(inputDir, "quad-tile.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckQuadTile(saved.Directories[0]); } [Fact] public void TestSmallliz() { var imagePath = Path.Combine(inputDir, "smallliz.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckSmallliz(saved.Directories[0]); } [Fact] public void TestStrike() { var imagePath = Path.Combine(inputDir, "strike.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckStrike(saved.Directories[0]); } [Fact] public void TestText() { var imagePath = Path.Combine(inputDir, "text.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); Assert.Equal(2, saved.PageCount); TestUtils.FieldCheckTextPage1(saved.Directories[0]); TestUtils.FieldCheckTextPage2(saved.Directories[1]); } [Fact] public void TestYcbcrCat() { var imagePath = Path.Combine(inputDir, "ycbcr-cat.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckYcbcrCat(saved.Directories[0]); } [Fact] public void TestZackTheCat() { var imagePath = Path.Combine(inputDir, "zackthecat.tif"); var tiffDoc = new TiffDocument(imagePath); TiffDocument saved = TestUtils.SaveLoad(tiffDoc); TestUtils.FieldCheckZackTheCat(saved.Directories[0]); } [Fact] public void TestReadSpecificPage() { var imagePath = Path.Combine(inputDir, "text.tif"); var tiffDoc = new TiffDocument(imagePath, 2); Assert.Equal(1, tiffDoc.PageCount); TestUtils.FieldCheckTextPage2(tiffDoc.Directories[0]); } [Fact] public void TestCountPages() { var imagePath = Path.Combine(inputDir, "text.tif"); Assert.Equal(2, TiffDocument.CountPages(imagePath)); } [Fact] public void TestWriteAppendFile() { var sourcePath = Path.Combine(inputDir, "cramps.tif"); var targetPath = Path.Combine(outputDir, "merged.tif"); File.Copy(sourcePath, targetPath, true); sourcePath = Path.Combine(inputDir, "text.tif"); var tiffDoc = new TiffDocument(sourcePath); tiffDoc.WriteAppend(targetPath); tiffDoc = new TiffDocument(targetPath); Assert.Equal(3, tiffDoc.PageCount); TestUtils.FieldCheckCramps(tiffDoc.Directories[0]); TestUtils.FieldCheckTextPage1(tiffDoc.Directories[1]); TestUtils.FieldCheckTextPage2(tiffDoc.Directories[2]); } [Fact] public void TestWriteAppendSpecificPage() { var sourcePath = Path.Combine(inputDir, "cramps.tif"); var targetPath = Path.Combine(outputDir, "merged.tif"); File.Copy(sourcePath, targetPath, true); sourcePath = Path.Combine(inputDir, "text.tif"); var tiffDoc = new TiffDocument(sourcePath); tiffDoc.WriteAppend(targetPath, 1); tiffDoc = new TiffDocument(targetPath); Assert.Equal(2, tiffDoc.PageCount); TestUtils.FieldCheckCramps(tiffDoc.Directories[0]); TestUtils.FieldCheckTextPage1(tiffDoc.Directories[1]); } [Fact] public void TestReadFailsWhenImageInvalid() { var imagePath = Path.Combine(inputDir, "NonTiff.bmp"); Assert.Throws<TiffException>(() => new TiffDocument(imagePath)); } [Fact] public void TestWriteAppendFailsWhenTargetInvalid() { var sourcePath = Path.Combine(inputDir, "NonTiff.bmp"); var targetPath = Path.Combine(outputDir, "nontiff.tif"); File.Copy(sourcePath, targetPath, true); var imagePath = Path.Combine(inputDir, "cramps.tif"); var tiffDoc = new TiffDocument(imagePath); Assert.Throws<TiffException>(() => tiffDoc.WriteAppend(targetPath)); } } }
mit
lobocv/anonymoususage
anonymoususage/__init__.py
178
__version__ = '1.14' try: from anonymoususage import AnonymousUsageTracker from tables import NO_STATE from exceptions import * except ImportError as e: print e
mit
evelynkharisma/CEJ
application/views/operation/operation_order_resource_original_history_view.php
2666
<!-- order tab --> <div class="right_col" role="main"> <div class="operation_order_stationary"> <div class="page-title"> <div class="title_left"> <h3>Resource Order (Original) - History</h3> </div> </div> <div class="clearfix"></div> <?php if ($this->nativesession->get('success')): ?> <div class="alert alert-success"> <?php echo $this->nativesession->get('success'); $this->nativesession->delete('success');?> </div> <?php endif; ?> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="x_panel"> <div class="x_title"> <div class="clearfix"></div> </div> <div class="x_content"> <table id="directoryView" class="table table-striped table-bordered"> <thead> <tr> <th>Date Accepted</th> <th>Total Quantity</th> <th>Action</th> </tr> </thead> <tbody> <?php if($orders){ $index = 0; foreach($orders as $order){ ?> <tr role="row" class="<?php if ($index % 2 == 0) {echo "odd";} else{echo "even";}?>"> <td><?php echo $order['completion'] ?></td> <td><?php echo $order['remains'] ?></td> <td><a href="<?php echo base_url() ?>index.php/operation/completeBookOrder/<?php echo $order['completion'] ?>" class="btn <?php if ($order['status']=='2'){echo 'btn-default disable';}else{echo "btn-success";}?>"><?php if ($order['status']=='2'){echo "View Order";}else{echo "Finish Order";}?></a></td> </tr> <?php $index += 1; }} else {?> <tr> <td colspan="3"><?php echo 'No book history request, please check again later' ?></td> </tr> <?php } ?> </tbody> </table> </form> </div> </div> </div> </div> </div> </div>
mit
dereknutile/communications-contact-directory
project/database/migrations_to_import/2014_10_12_000000_create_users_table.php
833
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('first_name'); $table->string('last_name'); $table->string('email')->unique(); $table->boolean('author', 0); $table->boolean('admin', 0); $table->string('password', 60); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
mit
rogelio-o/csmongo
csmongo/src/main/java/com/cloudsiness/csmongo/helpers/serializers/JsonObjectSerializer.java
834
package com.cloudsiness.csmongo.helpers.serializers; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.RawSerializer; import io.vertx.core.json.JsonObject; public class JsonObjectSerializer extends JsonSerializer<JsonObject> { private RawSerializer<String> rawSerializer = new RawSerializer<String>(String.class); @Override public void serialize(JsonObject o, JsonGenerator j, SerializerProvider s) throws IOException, JsonProcessingException { if(o == null) { j.writeNull(); } else { rawSerializer.serialize(o.toString(), j, s); } } }
mit
ECAM-Brussels/PeacIn
modules/core/client/app/init.js
2497
'use strict'; //Start by defining the main module and adding the module dependencies angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies); // Setting HTML5 Location Mode angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider', '$httpProvider', function ($locationProvider, $httpProvider) { $locationProvider.html5Mode(true).hashPrefix('!'); $httpProvider.interceptors.push('authInterceptor'); }]); angular.module(ApplicationConfiguration.applicationModuleName).run(function ($rootScope, $state, Authentication, amMoment) { // Check authentication before changing state $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { if (toState.data && toState.data.roles && toState.data.roles.length > 0) { var allowed = false; toState.data.roles.forEach(function (role) { if (Authentication.user.roles !== undefined && Authentication.user.roles.indexOf(role) !== -1) { allowed = true; return true; } }); if (! allowed) { event.preventDefault(); if (Authentication.user !== undefined && typeof Authentication.user === 'object') { $state.go('forbidden'); } else { $state.go('authentication.signin'); } } } }); // Record previous state $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) { if (! fromState.data || ! fromState.data.ignoreState) { $state.previous = { state: fromState, params: fromParams, href: $state.href(fromState, fromParams) }; } }); // Setup french language for moment amMoment.changeLocale('fr'); }); // Then define the init function for starting up the application angular.element(document).ready(function() { // Fixing facebook bug with redirect if (window.location.hash && window.location.hash === '#_=_') { if (window.history && history.pushState) { window.history.pushState('', document.title, window.location.pathname); } else { // Prevent scrolling by storing the page's current scroll offset var scroll = { top: document.body.scrollTop, left: document.body.scrollLeft }; window.location.hash = ''; // Restore the scroll offset, should be flicker free document.body.scrollTop = scroll.top; document.body.scrollLeft = scroll.left; } } // Then init the app angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]); });
mit
jpcercal/resume
src/File/TemplateFile.php
756
<?php namespace Jpcercal\Resume\File; use Jpcercal\Resume\Contract\FileInterface; use Jpcercal\Resume\Exception\FileNotExistsException; use Jpcercal\Resume\File\AbstractFile; use Symfony\Component\Console\Input\InputInterface; class TemplateFile extends AbstractFile implements FileInterface { /** * @inheritdoc */ public function __construct(InputInterface $input) { $this->filename = sprintf( '%s/index.twig', $input->getOption('template') ); if (!file_exists(APP_RESOURCES_TWIG_PATH . DS . $this->filename)) { throw new FileNotExistsException(sprintf( 'The template "%s" not exists.', $this->filename )); } } }
mit
koshigoe/aws-ssm-console
lib/aws/ssm/console/cli.rb
421
module Aws module SSM module Console class CLI attr_reader :options def initialize(argv) @options = Options.new(argv) end def run runner = Aws::SSM::Console::Runner.new(options.instance_ids) if options.command runner.invoke(options.command) else runner.run end end end end end end
mit
TheSylence/GSD
GSD/ViewServices/ConfirmationService.cs
1213
using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using MahApps.Metro.Controls; using MahApps.Metro.Controls.Dialogs; namespace GSD.ViewServices { internal interface IConfirmationService : IViewService { } [ExcludeFromCodeCoverage] internal class ConfirmationService : IConfirmationService { public async Task<object> Execute( MetroWindow window, object args ) { ConfirmationServiceArgs csa = args as ConfirmationServiceArgs; Debug.Assert( csa != null ); MetroDialogSettings settings = new MetroDialogSettings { AffirmativeButtonText = csa.OkText, NegativeButtonText = csa.CancelText }; var result = await window.ShowMessageAsync( csa.Title, csa.Message, MessageDialogStyle.AffirmativeAndNegative, settings ); return result == MessageDialogResult.Affirmative; } } internal class ConfirmationServiceArgs { public ConfirmationServiceArgs( string title, string message, string yes, string no ) { Title = title; Message = message; CancelText = no; OkText = yes; } public string CancelText { get; } public string Message { get; } public string OkText { get; } public string Title { get; } } }
mit
icoin/glaricoin
src/qt/guiutil.cpp
16189
#include <QApplication> #include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #if QT_VERSION >= 0x050000 #include <QUrlQuery> #else #include <QUrl> #endif #include <QTextDocument> // for Qt::mightBeRichText #include <QAbstractItemView> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { // return if URI is not valid or is no bitcoin URI if(!uri.isValid() || uri.scheme() != QString("bitcoin")) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; #if QT_VERSION < 0x050000 QList<QPair<QString, QString> > items = uri.queryItems(); #else QUrlQuery uriQuery(uri); QList<QPair<QString, QString> > items = uriQuery.queryItems(); #endif for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert bitcoin:// to bitcoin: // // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host, // which will lower-case it (and thus invalidate the address). if(uri.startsWith("bitcoin://")) { uri.replace(0, 10, "bitcoin:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { #if QT_VERSION < 0x050000 QString escaped = Qt::escape(str); #else QString escaped = str.toHtmlEscaped(); #endif if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item (global clipboard) QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Clipboard); // Copy first item (global mouse selection for e.g. X11 - NOP on Windows) QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Selection); } } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { #if QT_VERSION < 0x050000 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); #else myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); #endif } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != qApp->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip)) { // Prefix <qt/> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt/>" + HtmlEscape(tooltip, true); widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin.lnk"; } bool GetStartOnSystemStartup() { // check for Bitcoin.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "bitcoin.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a bitcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=GlariCoin\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #elif defined(Q_OS_MAC) // based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m #include <CoreFoundation/CoreFoundation.h> #include <CoreServices/CoreServices.h> LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl); LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl) { // loop through the list of startup items and try to find the bitcoin app CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL); for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) { LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i); UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; CFURLRef currentItemURL = NULL; LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, NULL); if(currentItemURL && CFEqual(currentItemURL, findUrl)) { // found CFRelease(currentItemURL); return item; } if(currentItemURL) { CFRelease(currentItemURL); } } return NULL; } bool GetStartOnSystemStartup() { CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); return !!foundItem; // return boolified object } bool SetStartOnSystemStartup(bool fAutoStart) { CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); if(fAutoStart && !foundItem) { // add bitcoin app to startup item list LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL); } else if(!fAutoStart && foundItem) { // remove item LSSharedFileListItemRemove(loginItems, foundItem); } return true; } #else bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("GlariCoin-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " bitcoin-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n" + " -choosedatadir " + tr("Choose data directory on startup (default: 0)") + "\n"; setWindowTitle(tr("GlariCoin-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stdout, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil
mit
chenke91/ihaveablog
app/main/__init__.py
470
from flask import Blueprint main = Blueprint('main', __name__) @main.before_app_request def before_request(): from flask import g from app.models import Category, User, Blog categories = Category.query.all() admin = User.get_admin() top_reads = Blog.get_top_read() top_replies = Blog.get_top_reply() g.categories = categories g.admin = admin g.top_reads = top_reads g.top_replies = top_replies from . import views, errors
mit
trampster/Jsonics
Jsonics/ToJson/NullableIntEmitter.cs
2522
using System; using System.Reflection; namespace Jsonics.ToJson { internal class NullableIntEmitter : ToJsonEmitter { internal override void EmitProperty(IJsonPropertyInfo property, Action<JsonILGenerator> getValueOnStack, JsonILGenerator generator) { var propertyType = property.Type; var propertyValueLocal = generator.DeclareLocal(propertyType); var endLabel = generator.DefineLabel(); var nonNullLabel = generator.DefineLabel(); getValueOnStack(generator); //loading parent object property.EmitGetValue(generator); generator.StoreLocal(propertyValueLocal); generator.LoadLocalAddress(propertyValueLocal); //check for null generator.Call(propertyType.GetTypeInfo().GetMethod("get_HasValue", new Type[0])); generator.BrIfTrue(nonNullLabel); //property is null generator.Append($"\"{property.Name}\":null"); generator.Branch(endLabel); //property is not null generator.Mark(nonNullLabel); generator.Append($"\"{property.Name}\":"); generator.LoadLocalAddress(propertyValueLocal); generator.Call(propertyType.GetTypeInfo().GetMethod("get_Value", new Type[0])); generator.AppendInt(); generator.Mark(endLabel); } internal override void EmitValue(Type type, Action<JsonILGenerator, bool> getValueOnStack, JsonILGenerator generator) { getValueOnStack(generator, true); var hasValueLabel = generator.DefineLabel(); var endLabel = generator.DefineLabel(); generator.Call(typeof(int?).GetTypeInfo().GetMethod("get_HasValue", new Type[0])); generator.BrIfTrue(hasValueLabel); generator.Append("null"); generator.Branch(endLabel); generator.Mark(hasValueLabel); getValueOnStack(generator, true); generator.Call(type.GetTypeInfo().GetMethod("get_Value", new Type[0])); generator.AppendInt(); generator.Mark(endLabel); } internal override bool TypeSupported(Type type) { Type underlyingType = Nullable.GetUnderlyingType(type); if(underlyingType == null) { return false; } return underlyingType == typeof(int) || underlyingType.GetTypeInfo().IsEnum; } } }
mit
PrincessMadMath/LOG8415-Advanced_Cloud
TP1/Sources/utils.py
408
import os import re # If directony don't exist will create it! def checkDirectory(directoryPath): if not os.path.exists(directoryPath): os.makedirs(directoryPath) def extractResult(outputDirectory, fileName, regexPattern): file = open("{}/{}".format(outputDirectory, fileName)) text = file.read() matchObjList = re.findall(regexPattern, text, re.M|re.I) return matchObjList
mit
philr/putty-key
lib/putty/key/ppk.rb
31474
# frozen_string_literal: true require 'openssl' module PuTTY module Key # Represents a PuTTY private key (.ppk) file. # # The {PPK} {#initialize constructor} can be used to either create an # uninitialized key or to read a .ppk file (from file or an `IO`-like # instance). # # The {#save} method can be used to write a {PPK} instance to a .ppk file or # `IO`-like instance. # # The {#algorithm}, {#comment}, {#public_blob} and {#private_blob} # attributes provide access to the high level fields of the PuTTY private # key as binary `String` instances. The structure of the two blobs will vary # based on the algorithm. # # Encrypted .ppk files can be read and written by specifying a passphrase # when loading or saving. Files are encrypted using AES in CBC mode with a # 256-bit key derived from the passphrase. # # The {PPK} class supports files corresponding to PuTTY's formats 2 and 3. # Format 1 (not supported) was only used briefly early on in the development # of the .ppk format and was never released. Format 2 is supported by PuTTY # version 0.52 onwards. Format 3 is supported by PuTTY version 0.75 onwards. # {PPK#save} defaults to format 2. Use the `format` parameter to select # format 3. # # libargon2 (https://github.com/P-H-C/phc-winner-argon2) is required to load # and save encrypted format 3 files. Binaries are typically available with # your OS distribution. For Windows, binaries are available at # https://github.com/philr/argon2-windows/releases - use either # Argon2OptDll.dll for CPUs supporting AVX or Argon2RefDll.dll otherwise. class PPK # String used in the computation of the format 3 MAC. FORMAT_2_MAC_KEY = 'putty-private-key-file-mac-key' private_constant :FORMAT_2_MAC_KEY # Length of the key used for the format 3 MAC. FORMAT_3_MAC_KEY_LENGTH = 32 private_constant :FORMAT_3_MAC_KEY_LENGTH # The default (and only supported) encryption algorithm. DEFAULT_ENCRYPTION_TYPE = 'aes256-cbc'.freeze # The default PuTTY private key file format. DEFAULT_FORMAT = 2 # The mimimum supported PuTTY private key file format. MINIMUM_FORMAT = 2 # The maximum supported PuTTY private key file format. MAXIMUM_FORMAT = 3 # Default Argon2 key derivation parameters for use with format 3. DEFAULT_ARGON2_PARAMS = Argon2Params.new.freeze # The key's algorithm, for example, 'ssh-rsa' or 'ssh-dss'. # # @return [String] The key's algorithm, for example, 'ssh-rsa' or # 'ssh-dss'. attr_accessor :algorithm # A comment to describe the PuTTY private key. # # @return [String] A comment to describe the PuTTY private key. attr_accessor :comment # Get or set the public component of the key. # # @return [String] The public component of the key. attr_accessor :public_blob # The private component of the key (after decryption when loading and # before encryption when saving). # # Note that when loading an encrypted .ppk file, this may include # additional 'random' suffix used as padding. # # @return [String] The private component of the key attr_accessor :private_blob # Constructs a new {PPK} instance either uninitialized, or initialized # by reading from a .ppk file or an `IO`-like instance. # # To read from a file set `path_or_io` to the file path, either as a # `String` or a `Pathname`. To read from an `IO`-like instance set # `path_or_io` to the instance. The instance must respond to `#read`. # `#binmode` will be called before reading if supported by the instance. # # @param path_or_io [Object] Set to the path of a .ppk file to load the # file as a `String` or `Pathname`, or an `IO`-like instance to read the # .ppk file from that instance. Set to `nil` to leave the new {PPK} # instance uninitialized. # @param passphrase [String] The passphrase to use when loading an # encrypted .ppk file. # # @raise [Errno::ENOENT] If the file specified by `path` does not exist. # @raise [ArgumentError] If the .ppk file was encrypted, but either no # passphrase or an incorrect passphrase was supplied. # @raise [FormatError] If the .ppk file is malformed or not supported. # @raise [LoadError] If opening an encrypted format 3 .ppk file and # libargon2 could not be loaded. # @raise [Argon2Error] If opening an encrypted format 3 .ppk file and # libargon2 reported an error hashing the passphrase. def initialize(path_or_io = nil, passphrase = nil) passphrase = nil if passphrase && passphrase.to_s.empty? if path_or_io Reader.open(path_or_io) do |reader| format, @algorithm = reader.field_matching(/PuTTY-User-Key-File-(\d+)/) format = format.to_i raise FormatError, "The ppk file is using a format that is too new (#{format})" if format > MAXIMUM_FORMAT raise FormatError, "The ppk file is using an old unsupported format (#{format})" if format < MINIMUM_FORMAT encryption_type = reader.field('Encryption') @comment = reader.field('Comment') @public_blob = reader.blob('Public') if encryption_type == 'none' passphrase = nil mac_key = derive_keys(format).first @private_blob = reader.blob('Private') else raise FormatError, "The ppk file is encrypted with #{encryption_type}, which is not supported" unless encryption_type == DEFAULT_ENCRYPTION_TYPE raise ArgumentError, 'The ppk file is encrypted, a passphrase must be supplied' unless passphrase argon2_params = if format >= 3 type = get_argon2_type(reader.field('Key-Derivation')) memory = reader.unsigned_integer('Argon2-Memory', maximum: 2**32) passes = reader.unsigned_integer('Argon2-Passes', maximum: 2**32) parallelism = reader.unsigned_integer('Argon2-Parallelism', maximum: 2**32) salt = reader.field('Argon2-Salt') unless salt =~ /\A(?:[0-9a-fA-F]{2})+\z/ raise FormatError, "Expected the Argon2-Salt field to be a hex string, but found #{salt}" end Argon2Params.new(type: type, memory: memory, passes: passes, parallelism: parallelism, salt: [salt].pack('H*')) end cipher = ::OpenSSL::Cipher::AES.new(256, :CBC) cipher.decrypt mac_key, cipher.key, cipher.iv = derive_keys(format, cipher, passphrase, argon2_params) cipher.padding = 0 encrypted_private_blob = reader.blob('Private') @private_blob = if encrypted_private_blob.bytesize > 0 partial = cipher.update(encrypted_private_blob) final = cipher.final partial + final else encrypted_private_blob end end private_mac = reader.field('Private-MAC') expected_private_mac = compute_private_mac(format, mac_key, encryption_type, @private_blob) unless private_mac == expected_private_mac raise ArgumentError, 'Incorrect passphrase supplied' if passphrase raise FormatError, "Invalid Private MAC (expected #{expected_private_mac}, but found #{private_mac})" end end end end # Writes this PuTTY private key instance to a .ppk file or `IO`-like # instance. # # To write to a file, set `path_or_io` to the file path, either as a # `String` or a `Pathname`. To write to an `IO`-like instance set # `path_or_io` to the instance. The instance must respond to `#write`. # `#binmode` will be called before writing if supported by the instance. # # If a file with the given path already exists, it will be overwritten. # # The {#algorithm}, {#private_blob} and {#public_blob} attributes must # have been set before calling {#save}. # # @param path_or_io [Object] The path to write to as a `String` or # `Pathname`, or an `IO`-like instance to write to. # @param passphrase [String] Set `passphrase` to encrypt the .ppk file # using the specified passphrase. Leave as `nil` to create an # unencrypted .ppk file. # @param encryption_type [String] The encryption algorithm to use. # Defaults to and currently only supports `'aes256-cbc'`. # @param format [Integer] The format of .ppk file to create. Defaults to # `2`. Supports `2` and `3`. # @param argon2_params [Argon2Params] The parameters to use with Argon2 # to derive the encryption key, initialization vector and MAC key when # saving an encrypted format 3 .ppk file. # # @return [Integer] The number of bytes written to the file. # # @raise [InvalidStateError] If either of the {#algorithm}, # {#private_blob} or {#public_blob} attributes have not been set. # @raise [ArgumentError] If `path` is nil. # @raise [ArgumentError] If a passphrase has been specified and # `encryption_type` is not `'aes256-cbc'`. # @raise [ArgumentError] If `format` is not `2` or `3`. # @raise [ArgumentError] If `argon2_params` is `nil`, a passphrase has # been specified and `format` is `3`. # @raise [Errno::ENOENT] If a directory specified by `path` does not # exist. # @raise [LoadError] If saving an encrypted format 3 .ppk file and # libargon2 could not be loaded. # @raise [Argon2Error] If saving an encrypted format 3 .ppk file and # libargon2 reported an error hashing the passphrase. def save(path_or_io, passphrase = nil, encryption_type: DEFAULT_ENCRYPTION_TYPE, format: DEFAULT_FORMAT, argon2_params: DEFAULT_ARGON2_PARAMS) raise InvalidStateError, 'algorithm must be set before calling save' unless @algorithm raise InvalidStateError, 'public_blob must be set before calling save' unless @public_blob raise InvalidStateError, 'private_blob must be set before calling save' unless @private_blob raise ArgumentError, 'An output path or io instance must be specified' unless path_or_io passphrase = nil if passphrase && passphrase.to_s.empty? raise ArgumentError, 'A format must be specified' unless format raise ArgumentError, "Unsupported format: #{format}" unless format >= MINIMUM_FORMAT && format <= MAXIMUM_FORMAT if passphrase raise ArgumentError, 'An encryption_type must be specified if a passphrase is specified' unless encryption_type raise ArgumentError, "Unsupported encryption_type: #{encryption_type}" unless encryption_type == DEFAULT_ENCRYPTION_TYPE raise ArgumentError, 'argon2_params must be specified if a passphrase is specified with format 3' unless format < 3 || argon2_params cipher = ::OpenSSL::Cipher::AES.new(256, :CBC) cipher.encrypt mac_key, cipher.key, cipher.iv, kdf_params = derive_keys(format, cipher, passphrase, argon2_params) cipher.padding = 0 # Pad using an SHA-1 hash of the unpadded private blob in order to # prevent an easily known plaintext attack on the last block. padding_length = cipher.block_size - ((@private_blob.bytesize - 1) % cipher.block_size) - 1 padded_private_blob = @private_blob padded_private_blob += ::OpenSSL::Digest::SHA1.new(@private_blob).digest.byteslice(0, padding_length) if padding_length > 0 encrypted_private_blob = if padded_private_blob.bytesize > 0 partial = cipher.update(padded_private_blob) final = cipher.final partial + final else padded_private_blob end else encryption_type = 'none' mac_key = derive_keys(format).first kdf_params = nil padded_private_blob = @private_blob encrypted_private_blob = padded_private_blob end private_mac = compute_private_mac(format, mac_key, encryption_type, padded_private_blob) Writer.open(path_or_io) do |writer| writer.field("PuTTY-User-Key-File-#{format}", @algorithm) writer.field('Encryption', encryption_type) writer.field('Comment', @comment) writer.blob('Public', @public_blob) if kdf_params # Only Argon2 is currently supported. writer.field('Key-Derivation', "Argon2#{kdf_params.type}") writer.field('Argon2-Memory', kdf_params.memory) writer.field('Argon2-Passes', kdf_params.passes) writer.field('Argon2-Parallelism', kdf_params.parallelism) writer.field('Argon2-Salt', kdf_params.salt.unpack('H*').first) end writer.blob('Private', encrypted_private_blob) writer.field('Private-MAC', private_mac) end end private # Returns the Argon2 type (`:d`, `:i` or `:id`) corresponding to the value # of the Key-Derivation field in the .ppk file. # # @param key_derivation [String] The value of the Key-Derivation field. # # @return [Symbol] The Argon2 type. # # @raise [FormatError] If `key_derivation` is unrecognized. def get_argon2_type(key_derivation) unless key_derivation =~ /\AArgon2(d|id?)\z/ raise FormatError, "Unrecognized key derivation type: #{key_derivation}" end $1.to_sym end # Derives the MAC key, encryption key and initialization vector from the # passphrase (if the file is encrypted). # # @param format [Integer] The format of the .ppk file. # @param cipher [OpenSSL::Cipher] The cipher being used to encrypt or # decrypt the .ppk file or `nil` if not encrypted. # @param passphrase [String] The passphrase used in the derivation or # `nil` if the .ppk file is not encrypted. The raw bytes of the # passphrase are used in the derivation. # @param argon2_params [Argon2Params] Parameters used with the Argon2 hash # function. May be `nil` if the .ppk file is not encrypted or `format` # is less than 3. # # @return [Array<String, String, String, Argon2Params>] The MAC key, # encryption key, initialization vector and final Argon2 parameters. # The encryption key and initialization vector will be `nil` if `cipher` # is `nil`. The final Argon2 parameters will only be set if `format` is # greater than or equal to 3 and `cipher` is not nil. The final Argon2 # parameters will differ from `argon2_params` if the salt and passes # options were left unspecified. # # @raise [LoadError] If `format` is at least 3, `cipher` is specified and # libargon2 could not be loaded. # @raise [Argon2Error] If `format` is at least 3, `cipher` is specified # and libargon2 reported an error hashing the passphrase. def derive_keys(format, cipher = nil, passphrase = nil, argon2_params = nil) if format >= 3 return derive_format_3_keys(cipher, passphrase, argon2_params) if cipher return [''.b, nil, nil, nil] end mac_key = derive_format_2_mac_key(passphrase) if cipher key = derive_format_2_encryption_key(passphrase, cipher.key_len) iv = "\0".b * cipher.iv_len else key = nil iv = nil end [mac_key, key, iv, nil] end # Initializes the Argon2 salt if required, determines the number of passes # to use to meet the time requirement unless preset and then derives the # MAC key, encryption key and initalization vector. # # @param cipher [OpenSSL::Cipher] The cipher being used to encrypt or # decrypt the .ppk file. # @param passphrase [String] The passphrase used in the derivation. The # raw bytes of the passphrase are used in the derivation. # @param argon2_params [Argon2Params] Parameters used with the Argon2 hash # function. # # @return [Array<String, String, String, Argon2Params>] The MAC key, # encryption key, initialization vector and final Argon2 parameters. # The encryption key and initialization vector will be `nil` if `cipher` # is `nil`. The final Argon2 parameters will differ from `argon2_params` # if the salt and passes options were left unspecified. # # @raise [LoadError] If libargon2 could not be loaded. # @raise [Argon2Error] If libargon2 reported an error hashing the # passphrase. def derive_format_3_keys(cipher, passphrase, argon2_params) # Defer loading of libargon2 to avoid a mandatory dependency. require_relative 'libargon2' salt = argon2_params.salt || ::OpenSSL::Random.random_bytes(16) passphrase_ptr = pointer_for_bytes(passphrase) salt_ptr = pointer_for_bytes(salt) hash_ptr = FFI::MemoryPointer.new(:char, cipher.key_len + cipher.iv_len + FORMAT_3_MAC_KEY_LENGTH) begin passes = argon2_params.passes if passes argon2_hash(argon2_params.type, argon2_params.passes, argon2_params.memory, argon2_params.parallelism, passphrase_ptr, salt_ptr, hash_ptr) else # Only require the time taken to be approximately correct. Scale up # geometrically using Fibonacci numbers (as per PuTTY's # implementation). prev_passes = 1 passes = 1 loop do start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) argon2_hash(argon2_params.type, passes, argon2_params.memory, argon2_params.parallelism, passphrase_ptr, salt_ptr, hash_ptr) elapsed = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000 break if (elapsed >= argon2_params.desired_time) hash_ptr.clear new_passes = passes + prev_passes break if new_passes > 2**32 # maximum allowed by argon2_hash parameter data type prev_passes, passes = passes, new_passes end end passphrase_ptr.clear key = hash_ptr.get_bytes(0, cipher.key_len) iv = hash_ptr.get_bytes(cipher.key_len, cipher.iv_len) mac_key = hash_ptr.get_bytes(cipher.key_len + cipher.iv_len, FORMAT_3_MAC_KEY_LENGTH) argon2_params = argon2_params.complete(passes, salt) hash_ptr.clear [mac_key, key, iv, argon2_params] ensure # Calling free isn't actually required, but this releases the memory # sooner. hash_ptr.free salt_ptr.free passphrase_ptr.free end end # Creates an `FFI::MemoryPointer` containing the raw bytes from `string` # without a null terminator. # # @param string [String] The bytes to use for the `FFI::MemoryPointer`. # # @return [FFI::MemoryPointer] A new `FFI::MemoryPointer` containing the # raw bytes from `string`. def pointer_for_bytes(string) FFI::MemoryPointer.new(:char, string.bytesize).tap do |ptr| ptr.put_bytes(0, string) end end # Calls the libargon2 `argon2_hash` function to obtain a raw hash using # version 13 of the algorithm. # # @param type [Symbol] The variant of Argon2 to use. (`:d`, `:i` or # `:id`). # @param iterations [Integer] The number of iterations to use. # @param memory [Integer] Memory usage in kibibytes. # @param passhrase [FFI::MemoryPointer] The passphrase. # @param salt [FFI::MemoryPointer] The salt. # @param hash [FFI::MemoryPointer] A buffer to write the raw hash to. # # @raise [Argon2Error] If `argon2_hash` returns an error. def argon2_hash(type, iterations, memory, parallelism, passphrase, salt, hash) res = Libargon2.argon2_hash(iterations, memory, parallelism, passphrase, passphrase.size, salt, salt.size, hash, hash.size, FFI::Pointer::NULL, 0, type, :version_13) unless res == Libargon2::ARGON2_OK raise Argon2Error.new(res, Libargon2.argon2_error_message(res)) end end # Derives an encryption key of the specified length from a passphrase for # use in format 2 files. # # @param passphrase [String] The passphrase to use. # @param key_length [Integer] The length of the desired key in bytes. # # @return [String] The derived encryption key. def derive_format_2_encryption_key(passphrase, key_length) key = String.new key_digest = ::OpenSSL::Digest::SHA1.new iteration = 0 while true key_digest.update([iteration].pack('N')) key_digest.update(passphrase.bytes.pack('c*')) key += key_digest.digest break if key.bytesize > key_length key_digest.reset iteration += 1 end key[0, key_length] end # Derives a MAC key from a passphrase for use in format 2 files. # # @param passphrase [String] The passphrase to use or `nil` if not # encrypted. # # @return [String] The derived MAC key. def derive_format_2_mac_key(passphrase) key = ::OpenSSL::Digest::SHA1.new key.update(FORMAT_2_MAC_KEY) key.update(passphrase) if passphrase key.digest end # Computes the value of the Private-MAC field given the passphrase, # encryption type and padded private blob (the value of the private blob # after padding bytes have been appended prior to encryption). # # @param format [Integer] The format of the .ppk file. # @param passphrase [String] The encryption passphrase. # @param encryption_type [String] The value of the Encryption field. # @param padded_private_blob [String] The private blob after padding bytes # have been appended prior to encryption. # # @return [String] The computed private MAC. def compute_private_mac(format, mac_key, encryption_type, padded_private_blob) digest = format <= 2 ? ::OpenSSL::Digest::SHA1 : ::OpenSSL::Digest::SHA256 data = Util.ssh_pack(@algorithm, encryption_type, @comment || '', @public_blob, padded_private_blob) ::OpenSSL::HMAC.hexdigest(digest.new, mac_key, data) end # Handles reading .ppk files. # # @private class Reader # Opens a .ppk file for reading (or uses the provided `IO`-like # instance), creates a new instance of `Reader` and yields it to the # caller. # # @param path_or_io [Object] The path of the .ppk file to be read or an # `IO`-like object. # # @return [Object] The result of yielding to the caller. # # raise [Errno::ENOENT] If the file specified by `path` does not exist. def self.open(path_or_io) if path_or_io.kind_of?(String) || path_or_io.kind_of?(Pathname) File.open(path_or_io.to_s, 'rb') do |file| yield Reader.new(file) end else path_or_io.binmode if path_or_io.respond_to?(:binmode) unless path_or_io.respond_to?(:getbyte) path_or_io = GetbyteIo.new(path_or_io) end yield Reader.new(path_or_io) end end # Initializes a new {Reader} with an `IO`-like instance to read from. # # @param file [Object] The `IO`-like instance to read from. def initialize(file) @file = file @consumed_byte = nil end # Reads the next field from the file. # # @param name [String] The expected field name. # # @return [String] The value of the field. # # @raise [FormatError] If the current position in the file was not the # start of a field with the expected name. def field(name) line = read_line raise FormatError, "Expected field #{name}, but found #{line}" unless line.start_with?("#{name}: ") line.byteslice(name.bytesize + 2, line.bytesize - name.bytesize - 2) end # Reads the next field from the file. # # @param name_regexp [Regexp] A `Regexp` that matches the expected field # name. # # @return [String] The value of the field if the regular expression has # no captures. # @return [Array] An array containing the regular expression captures as # the first elements and the value of the field as the last element. # # @raise [FormatError] If the current position in the file was not the # start of a field with the expected name. def field_matching(name_regexp) line = read_line line_regexp = Regexp.new("\\A#{name_regexp.source}: ", name_regexp.options) match = line_regexp.match(line) raise FormatError, "Expected field matching #{name_regexp}, but found #{line}" unless match prefix = match[0] value = line.byteslice(prefix.bytesize, line.bytesize - prefix.bytesize) captures = match.captures captures.empty? ? value : captures + [value] end # Reads the next field from the file as an unsigned integer. # # @param name [String] The expected field name. # # @return [Integer] The value of the field. # # @raise [FormatError] If the current position in the file was not the # start of a field with the expected name. # @raise [FormatError] If the field did not contain a positive integer. def unsigned_integer(name, maximum: nil) value = field(name) value = value =~ /\A[0-9]+\z/ && value.to_i raise FormatError, "Expected field #{name} to contain an unsigned integer value, but found #{value}" unless value raise FormatError, "Expected field #{name} to have a maximum of #{maximum}, but found #{value}" if maximum && value > maximum value end # Reads a blob from the file consisting of a Lines field whose value # gives the number of Base64 encoded lines in the blob. # # @return [String] The Base64-decoded value of the blob. # # @raise [FormatError] If there is not a blob starting at the current # file position. # @raise [FormatError] If the value of the Lines field is not a # positive integer. def blob(name) lines = unsigned_integer("#{name}-Lines") lines.times.map { read_line }.join("\n").unpack('m48').first end private # Reads a single new-line (\n, \r\n or \r) terminated line from the # file, removing the new-line character. # # @return [String] The line. # # @raise [FormatError] If the end of file was detected before reading a # line. def read_line line = ''.b if @consumed_byte line << @consumed_byte @consumed_byte = nil end while byte = @file.getbyte return line if byte == 0x0a if byte == 0x0d byte = @file.getbyte return line if !byte || byte == 0x0a @consumed_byte = byte return line end line << byte end return line if line.bytesize > 0 raise FormatError, 'Truncated ppk file detected' end end private_constant :Reader # Wraps an `IO`-like instance, providing an implementation of `#getbyte`. # Allows reading from `IO`-like instances that only provide `#read`. class GetbyteIo # Initializes a new {GetbyteIO} with the given `IO`-like instance. # # @param io [Object] An `IO`-like instance. def initialize(io) @io = io @outbuf = ' '.b end # Gets the next 8-bit byte (0..255) from the `IO`-like instance. # # @return [Integer] the next byte or `nil` if the end of the stream has # been reached. def getbyte s = @io.read(1, @outbuf) s && s.getbyte(0) end end private_constant :GetbyteIo # Handles writing .ppk files. # # @private class Writer # The number of bytes that have been written. # # @return [Integer] The number of bytes that have been written. attr_reader :bytes_written # Opens a .ppk file for writing (or uses the provided `IO`-like # instance), creates a new instance of `Writer` and yields it to the # caller. # # @param path_or_io [Object] The path of the .ppk file to be written or # an `IO`-like instance. # # @return [Object] The result of yielding to the caller. # # @raise [Errno::ENOENT] If a directory specified by `path` does not # exist. def self.open(path_or_io) if path_or_io.kind_of?(String) || path_or_io.kind_of?(Pathname) File.open(path_or_io.to_s, 'wb') do |file| yield Writer.new(file) end else path_or_io.binmode if path_or_io.respond_to?(:binmode) yield Writer.new(path_or_io) end end # Initializes a new {Writer} with an `IO`-like instance to write to. # # @param file [Object] The `IO`-like instance to write to. def initialize(file) @file = file @bytes_written = 0 end # Writes a field to the file. # # @param name [String] The field name. # @param value [Object] The field value. def field(name, value) write(name) write(': ') write(value.to_s) write_line end # Writes a blob to the file (Lines field and Base64 encoded value). # # @param name [String] The name of the blob (used as a prefix for the # lines field). # @param blob [String] The value of the blob. This is Base64 encoded # before being written to the file. def blob(name, blob) lines = [blob].pack('m48').split("\n") field("#{name}-Lines", lines.length) lines.each do |line| write(line) write_line end end private # Writes a line separator to the file (\n on all platforms). def write_line write("\n") end # Writes a string to the file. # # @param string [String] The string to be written. def write(string) @bytes_written += @file.write(string) end end private_constant :Writer end end end
mit
SupremeTechnopriest/react-blueprint
cli/generator/templates/src/containers/App/App.js
699
/** * App.js * */ import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import Radium, { Style } from 'radium'; import { View } from 'react-blueprint'; import { colors, type } from 'utils/style'; import { app as copy } from 'utils/copy'; @Radium @connect() export default class App extends Component { static propTypes = {}; static defaultProps = {}; state = {}; render() { return ( <View> <Style rules={rules} /> <View> <h1>{copy.title}</h1> {this.props.children} </View> </View> ); } }; const rules = { html: { background: colors.grey100 }, body: { margin: 0, fontFamily: type.regular } };
mit
AxonInteractive/bridge-server
src/logger.js
2937
"use strict"; var winston = require( 'winston' ); var fs = require( 'fs' ); var path = require( 'path' ); var mkdirp = require( 'mkdirp' ); var config = require( '../server' ).config.logger; var app = require( '../server' ).app; var _ = require( 'lodash')._; config.server.filename = path.normalize( config.server.filename ); var dir; if ( config.server.filename[ 0 ] === '/' ){ dir = path.resolve( config.server.filename ); } else { dir = path.resolve( path.join( path.dirname( require.main.filename ), path.dirname( config.server.filename ) ) ); } winston.verbose( "Verifying that server log directory exists..." ); winston.debug( dir ); if ( !fs.existsSync( dir ) ) { winston.warn( "Log directory '" + dir + "' doesn't exist. Attempting to make directory now..." ); mkdirp( dir, function ( err ) { if ( err ) { winston.error( "Error making server directory '" + dir + "', Reason: " + err ); return; } winston.info( "Log directory created successfully." ); } ); } else { winston.verbose( "Server Log directory found." ); } config.exception.filename = path.normalize( config.exception.filename ); dir = path.resolve( path.dirname( config.exception.filename ) ); winston.verbose( "Verifying that exception log directory exists..." ); winston.debug( dir ); if ( !fs.existsSync( dir ) ) { winston.warn("Log directory '" + dir + "' doesn't exist. Attempting to make directory now..."); mkdirp( dir, function ( err ) { if ( err ) { winston.error( "Error making exception directory '" + dir + "', Reason: " + err ); return; } winston.info( "Exception log directory created successfully." ); } ); } else { winston.verbose( "Exception log directory found." ); } console.log( "logger level: " + config.server.level ); console.log( "console logger level: " + config.server.consoleLevel ); var loggerConstObj = { transports: [ new winston.transports.DailyRotateFile( { filename: config.server.filename, level: config.server.level, timestamp: true, silent: false, json: false } ), new winston.transports.Console( { level: config.server.consoleLevel, colorize: true, silent: false, timestamp: false, json: false, prettyPrint: true } ) ], exceptionHandlers: [ new winston.transports.DailyRotateFile( { filename: config.exception.filename, handleExceptions: true, json: false } ) ], exitOnError: false }; if ( config.exception.writetoconsole === true ) { loggerConstObj.exceptionHandlers.push( new winston.transports.Console( { prettyPrint: true, colorize: true } ) ); } app.log = new( winston.Logger )( loggerConstObj );
mit
TheModevShop/craft-app
src/routes/Configs/components/Configs.js
3300
import React from 'react'; import AddConfig from 'components/AddConfig/AddConfig.js' import _ from 'lodash'; import {Link} from 'react-router'; import './configs.less'; class Configs extends React.Component { constructor(...args) { super(...args); this.state = { }; } componentDidMount() { const resourceId = _.get(this.props.membership, 'membership_id'); if (resourceId && _.get(this.props.membership, 'membership_type') === 'resource') { this.props.getConfigsForResource(resourceId); } } render() { const {membership} = this.props; return ( <div className="configs-page-wrapper page-wrapper"> { !_.get(this.props.configs, 'items.length') ? <div className="banner card"> <span> <h2 className="bold" style={{marginTop: '5px'}}>Linking Your First Report.</h2> <h5 style={{maxWidth: 500}}>Linking a report configuration to your current distribution data allows us to automatically map where your products can be found. After you link the report, you will then setup the fields.</h5> <h5 style={{margin: '20px 0 20px 0'}}><a className="secondary-link" target="_blank" href="https://docs.google.com/document/d/1c_ltkjJCpVcaCVIaJFY7GtETHGg2ZvxLnJtI4nkJlGM/edit?usp=sharing">HOW TO SETUP YOUR REPORT (encompass users only)</a></h5> <h4 style={{marginBottom: '10px'}}></h4> </span> { !this.state.showForm ? <button style={{minWidth: '210px', marginLeft: '0px'}} className="primary-btn-large" onClick={() => this.setState({showForm: !this.state.showForm})}> Add Your First Report Config </button> : null } </div> : null } <div className="add-a-config"> { _.get(this.props.configs, 'items.length') && !_.find(_.get(this.props.configs, 'items'), (item) => item.vip_id) ? <div className="dotted-button" onClick={() => this.setState({showForm: !this.state.showForm})}> <span className="plus"></span> <span>{!this.state.showForm ? 'Add a New Report' : 'Hide Report Form'}</span> </div> : null } { this.state.showForm ? <AddConfig hideForm={() => this.setState({showForm: false})} {...this.props} membership={membership} /> : null } </div> { _.map(_.orderBy(_.take(_.get(this.props.configs, 'items', []), 100), 'created_at', 'desc'), (c, i) => { return ( <div className="card" key={i}> <Link className="secondary-link" to={`/admin/configs/${c.id}`}> <h4 className="bold">{c.report_name}</h4> <h4>{c.distribution_platform}</h4> <h4>{c.report_url}</h4> { c.new ? <h4 className="tag">new</h4> : null } </Link> </div> ) }) } </div> ); } } Configs.propTypes = { membership: React.PropTypes.object.isRequired, configs: React.PropTypes.object, getConfigsForResource: React.PropTypes.func.isRequired, }; export default Configs;
mit
MeshCollider/Omnicoin
src/qt/locale/omnicoin_sq.ts
24247
<TS language="sq" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Kliko me të djathtën për të ndryshuar adresën ose etiketen.</translation> </message> <message> <source>Create a new address</source> <translation>Krijo një adresë të re</translation> </message> <message> <source>&amp;New</source> <translation>&amp;E re</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopjo adresën e zgjedhur në memorjen e sistemit </translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Kopjo</translation> </message> <message> <source>&amp;Copy Address</source> <translation>&amp;Kopjo adresen</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Fshi adresen e selektuar nga lista</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Fshi</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Zgjidh adresen ku do te dergoni monedhat</translation> </message> <message> <source>Sending addresses</source> <translation>Duke derguar adresen</translation> </message> <message> <source>Receiving addresses</source> <translation>Duke marr adresen</translation> </message> <message> <source>These are your Omnicoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Këto janë Omnicoin adresat e juaja për të dërguar pagesa. Gjithmon kontrolloni shumën dhe adresën pranuese para se të dërgoni monedha.</translation> </message> <message> <source>These are your Omnicoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation>Këto janë Omnicoin adresat e juaja për të pranuar pagesa. Rekomandohet që gjithmon të përdorni një adresë të re për çdo transaksion.</translation> </message> <message> <source>Copy &amp;Label</source> <translation>Kopjo &amp;Etiketë</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Ndrysho</translation> </message> <message> <source>Export Address List</source> <translation>Eksporto listën e adresave</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Skedar i ndarë me pikëpresje(*.csv)</translation> </message> <message> <source>Exporting Failed</source> <translation>Eksportimi dështoj</translation> </message> <message> <source>There was an error trying to save the address list to %1. Please try again.</source> <translation>Gabim gjatë ruajtjes së listës së adresave në %1. Ju lutem provoni prapë.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Etiketë</translation> </message> <message> <source>Address</source> <translation>Adresë</translation> </message> <message> <source>(no label)</source> <translation>(pa etiketë)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Enter passphrase</source> <translation>Futni frazkalimin</translation> </message> <message> <source>New passphrase</source> <translation>Frazkalim i ri</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Përsërisni frazkalimin e ri</translation> </message> <message> <source>Encrypt wallet</source> <translation>Kripto portofolin</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ky veprim ka nevojë per frazkalimin e portofolit tuaj që të ç'kyç portofolin.</translation> </message> <message> <source>Unlock wallet</source> <translation>ç'kyç portofolin.</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ky veprim kërkon frazkalimin e portofolit tuaj që të dekriptoj portofolin.</translation> </message> <message> <source>Decrypt wallet</source> <translation>Dekripto portofolin</translation> </message> <message> <source>Change passphrase</source> <translation>Ndrysho frazkalimin</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>Konfirmoni enkriptimin e portofolit</translation> </message> <message> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Jeni te sigurt te enkriptoni portofolin tuaj?</translation> </message> <message> <source>Wallet encrypted</source> <translation>Portofoli u enkriptua</translation> </message> <message> <source>Wallet encryption failed</source> <translation>Enkriptimi i portofolit dështoi</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Enkriptimi i portofolit dështoi për shkak të një gabimi të brëndshëm. portofoli juaj nuk u enkriptua.</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>Frazkalimet e plotësuara nuk përputhen.</translation> </message> <message> <source>Wallet unlock failed</source> <translation>ç'kyçja e portofolit dështoi</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Frazkalimi i futur për dekriptimin e portofolit nuk ishte i saktë.</translation> </message> <message> <source>Wallet decryption failed</source> <translation>Dekriptimi i portofolit dështoi</translation> </message> </context> <context> <name>BanTableModel</name> </context> <context> <name>OmnicoinGUI</name> <message> <source>Synchronizing with network...</source> <translation>Duke u sinkronizuar me rrjetin...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Përmbledhje</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Trego një përmbledhje te përgjithshme të portofolit</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transaksionet</translation> </message> <message> <source>Browse transaction history</source> <translation>Shfleto historinë e transaksioneve</translation> </message> <message> <source>Quit application</source> <translation>Mbyllni aplikacionin</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Opsione</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Ndrysho frazkalimin e përdorur per enkriptimin e portofolit</translation> </message> <message> <source>Omnicoin</source> <translation>Omnicoin</translation> </message> <message> <source>Wallet</source> <translation>Portofol</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;Dergo</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;Merr</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;Shfaq / Fsheh</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Skedar</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Konfigurimet</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Ndihmë</translation> </message> <message> <source>Tabs toolbar</source> <translation>Shiriti i mjeteve</translation> </message> <message> <source>Omnicoin</source> <translation>Berthama Omnicoin</translation> </message> <message> <source>&amp;About Omnicoin</source> <translation>Rreth Berthames Bitkoin</translation> </message> <message> <source>%1 and %2</source> <translation>%1 dhe %2</translation> </message> <message> <source>%1 behind</source> <translation>%1 Pas</translation> </message> <message> <source>Error</source> <translation>Problem</translation> </message> <message> <source>Information</source> <translation>Informacion</translation> </message> <message> <source>Up to date</source> <translation>I azhornuar</translation> </message> <message> <source>Catching up...</source> <translation>Duke u azhornuar...</translation> </message> <message> <source>Sent transaction</source> <translation>Dërgo transaksionin</translation> </message> <message> <source>Incoming transaction</source> <translation>Transaksion në ardhje</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Portofoli po &lt;b&gt; enkriptohet&lt;/b&gt; dhe është &lt;b&gt; i ç'kyçur&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Portofoli po &lt;b&gt; enkriptohet&lt;/b&gt; dhe është &lt;b&gt; i kyçur&lt;/b&gt;</translation> </message> </context> <context> <name>ClientModel</name> </context> <context> <name>CoinControlDialog</name> <message> <source>Coin Selection</source> <translation>Zgjedhja e monedhes</translation> </message> <message> <source>Amount:</source> <translation>Shuma:</translation> </message> <message> <source>Amount</source> <translation>Sasia</translation> </message> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Copy address</source> <translation>Kopjo adresën</translation> </message> <message> <source>yes</source> <translation>po</translation> </message> <message> <source>no</source> <translation>jo</translation> </message> <message> <source>(no label)</source> <translation>(pa etiketë)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Ndrysho Adresën</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Etiketë</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Adresa</translation> </message> <message> <source>New receiving address</source> <translation>Adresë e re pritëse</translation> </message> <message> <source>New sending address</source> <translation>Adresë e re dërgimi</translation> </message> <message> <source>Edit receiving address</source> <translation>Ndrysho adresën pritëse</translation> </message> <message> <source>Edit sending address</source> <translation>ndrysho adresën dërguese</translation> </message> <message> <source>The entered address "%1" is already in the address book.</source> <translation>Adresa e dhënë "%1" është e zënë në librin e adresave. </translation> </message> <message> <source>Could not unlock wallet.</source> <translation>Nuk mund të ç'kyçet portofoli.</translation> </message> <message> <source>New key generation failed.</source> <translation>Krijimi i çelësit të ri dështoi.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>name</source> <translation>emri</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>Omnicoin</source> <translation>Berthama Omnicoin</translation> </message> <message> <source>version</source> <translation>versioni</translation> </message> <message> <source>About Omnicoin</source> <translation>Rreth Berthames Bitkoin</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation>Miresevini</translation> </message> <message> <source>Welcome to Omnicoin.</source> <translation>Miresevini ne Berthamen Omnicoin</translation> </message> <message> <source>Omnicoin</source> <translation>Berthama Omnicoin</translation> </message> <message> <source>Error</source> <translation>Problem</translation> </message> </context> <context> <name>OpenURIDialog</name> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Opsionet</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Formilarë</translation> </message> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Sasia</translation> </message> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> <message> <source>&amp;Open</source> <translation>&amp;Hap</translation> </message> <message> <source>&amp;Clear</source> <translation>&amp;Pastro</translation> </message> <message> <source>never</source> <translation>asnjehere</translation> </message> <message> <source>Unknown</source> <translation>i/e panjohur</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Label:</source> <translation>&amp;Etiketë:</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>Address</source> <translation>Adresë</translation> </message> <message> <source>Amount</source> <translation>Sasia</translation> </message> <message> <source>Label</source> <translation>Etiketë</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Label</source> <translation>Etiketë</translation> </message> <message> <source>Amount</source> <translation>Sasia</translation> </message> <message> <source>(no label)</source> <translation>(pa etiketë)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Dërgo Monedha</translation> </message> <message> <source>Amount:</source> <translation>Shuma:</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Dërgo marrësve të ndryshëm njëkohësisht</translation> </message> <message> <source>Balance:</source> <translation>Balanca:</translation> </message> <message> <source>Confirm the send action</source> <translation>Konfirmo veprimin e dërgimit</translation> </message> <message> <source>Confirm send coins</source> <translation>konfirmo dërgimin e monedhave</translation> </message> <message> <source>The amount to pay must be larger than 0.</source> <translation>Shuma e paguar duhet të jetë më e madhe se 0.</translation> </message> <message> <source>(no label)</source> <translation>(pa etiketë)</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>Sh&amp;uma:</translation> </message> <message> <source>Pay &amp;To:</source> <translation>Paguaj &amp;drejt:</translation> </message> <message> <source>Enter a label for this address to add it to your address book</source> <translation>Krijoni një etiketë për këtë adresë që t'ja shtoni librit të adresave</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etiketë:</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Ngjit nga memorja e sistemit</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> </context> <context> <name>ShutdownWindow</name> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Ngjit nga memorja e sistemit</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>Omnicoin</source> <translation>Berthama Omnicoin</translation> </message> <message> <source>[testnet]</source> <translation>[testo rrjetin]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> <message> <source>Open until %1</source> <translation>Hapur deri më %1</translation> </message> <message> <source>%1/unconfirmed</source> <translation>%1/I pakonfirmuar</translation> </message> <message> <source>%1 confirmations</source> <translation>%1 konfirmimet</translation> </message> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Amount</source> <translation>Sasia</translation> </message> <message> <source>, has not been successfully broadcast yet</source> <translation>, nuk është transmetuar me sukses deri tani</translation> </message> <message> <source>unknown</source> <translation>i/e panjohur</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <source>Transaction details</source> <translation>Detajet e transaksionit</translation> </message> <message> <source>This pane shows a detailed description of the transaction</source> <translation>Ky panel tregon një përshkrim të detajuar të transaksionit</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Type</source> <translation>Lloji</translation> </message> <message> <source>Open until %1</source> <translation>Hapur deri më %1</translation> </message> <message> <source>Confirmed (%1 confirmations)</source> <translation>I/E konfirmuar(%1 konfirmime)</translation> </message> <message> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Ky bllok është marrë nga ndonjë nyje dhe ka shumë mundësi të mos pranohet! </translation> </message> <message> <source>Generated but not accepted</source> <translation>I krijuar por i papranuar</translation> </message> <message> <source>Label</source> <translation>Etiketë</translation> </message> <message> <source>Received with</source> <translation>Marrë me</translation> </message> <message> <source>Sent to</source> <translation>Dërguar drejt</translation> </message> <message> <source>Payment to yourself</source> <translation>Pagesë ndaj vetvetes</translation> </message> <message> <source>Mined</source> <translation>Minuar</translation> </message> <message> <source>(n/a)</source> <translation>(p/a)</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>Received with</source> <translation>Marrë me</translation> </message> <message> <source>Sent to</source> <translation>Dërguar drejt</translation> </message> <message> <source>Mined</source> <translation>Minuar</translation> </message> <message> <source>Copy address</source> <translation>Kopjo adresën</translation> </message> <message> <source>Exporting Failed</source> <translation>Eksportimi dështoj</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Skedar i ndarë me pikëpresje(*.csv)</translation> </message> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Type</source> <translation>Lloji</translation> </message> <message> <source>Label</source> <translation>Etiketë</translation> </message> <message> <source>Address</source> <translation>Adresë</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>Dërgo Monedha</translation> </message> </context> <context> <name>WalletView</name> </context> <context> <name>omnicoin-core</name> <message> <source>Information</source> <translation>Informacion</translation> </message> <message> <source>Insufficient funds</source> <translation>Fonde te pamjaftueshme</translation> </message> <message> <source>Rescanning...</source> <translation>Rikerkim</translation> </message> <message> <source>Error</source> <translation>Problem</translation> </message> </context> </TS>
mit
AndreyZaets/rita
catalog/model/rosava/wherebuy/point.php
1007
<?php class ModelRosavaWherebuyPoint extends Model { public function getPoints($groups = '', $trade = '') { $sql = "SELECT name, address, telephone, image, open, email, web, lat, lng, groups, trade FROM " . DB_PREFIX . "location"; if (!empty($groups)) { $sql .= " WHERE groups = " . $groups . ""; if (!empty($trade)) { $sql .= " AND trade = " . $trade . ""; } } elseif (!empty($trade)) { $sql .= " WHERE trade = " . $trade . ""; } $query = $this->db->query($sql); return json_encode($query->rows, JSON_NUMERIC_CHECK); } public function getGroups() { $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "groups WHERE language_id = '" . (int)$this->config->get('config_language_id') . "'"); return $query->rows; } public function getTrade() { $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "trade WHERE language_id = '" . (int)$this->config->get('config_language_id') . "'"); return $query->rows; } }
mit
ruby-numo/gnuplot-demo
gnuplot/script/606smooth.rb
2624
# # binning/histograms # http://gnuplot.sourceforge.net/demo_4.6/smooth.html require_relative "gpl" # bin(x, s) = s*int(x/s) # # set zeroaxis # # # Uniform # set title "Uniform Distribution" # set key top right # set boxwidth 0.05 # plot [-0.1:1.1][-0.4:1.5] "random-points" u 1:(0.25*rand(0)-.35) t '', \ # "" u (bin($1,0.05)):(20/300.) s f t 'smooth frequency' w boxes, \ # "" u 1:(1/300.) s cumul t 'smooth cumulative' gpl do run "bin(x, s) = s*int(x/s)" set :zeroaxis set title:"Uniform Distribution" set :key, :top, :right set boxwidth:0.05 plot -0.1..1.1, -0.4..1.5, ["\"random-points\"", u:'1:(0.25*rand(0)-.35)', t:''], ["\"\"", u:'(bin($1,0.05)):(20/300.)', s:true, f:true, t:'smooth frequency', w:"boxes"], ["\"\"", u:'1:(1/300.)', s:"cumul", t:'smooth cumulative'] end # # Normal # set title "Normal Distribution" # set key top left # set boxwidth 0.05 # plot "random-points" u 2:(0.25*rand(0)-.35) t '', \ # "" u (bin($2,0.05)):(20/300.) s f t 'smooth frequency' w boxes, \ # "" u 2:(1/300.) s cumul t 'smooth cumulative' gpl do set title:"Normal Distribution" set :key, :top, :left set boxwidth:0.05 plot ["\"random-points\"", u:'2:(0.25*rand(0)-.35)', t:''], ["\"\"", u:'(bin($2,0.05)):(20/300.)', s:true, f:true, t:'smooth frequency', w:"boxes"], ["\"\"", u:'2:(1/300.)', s:"cumul", t:'smooth cumulative'] end # # Lognormal # set title "Lognormal Distribution" # set key top right # set boxwidth 0.1 # plot [0:] "random-points" u 3:(0.25*rand(0)-.35) t '', \ # "" u (bin($3,0.1)):(10/300.) s f t 'smooth frequency' w boxes, \ # "" u 3:(1/300.) s cumul t 'smooth cumulative' gpl do set title:"Lognormal Distribution" set :key, :top, :right set boxwidth:0.1 plot "[0:]", ["\"random-points\"", u:'3:(0.25*rand(0)-.35)', t:''], ["\"\"", u:'(bin($3,0.1)):(10/300.)', s:true, f:true, t:'smooth frequency', w:"boxes"], ["\"\"", u:'3:(1/300.)', s:"cumul", t:'smooth cumulative'] end # # Mixed # set title "Mixed Distribution (Lognormal with shifted Gaussian)" # set key top right # set boxwidth 0.1 # plot "random-points" u 4:(0.25*rand(0)-.35) t '', \ # "" u (bin($4,0.1)):(10/300.) s f t 'smooth frequency' w boxes, \ # "" u 4:(1/300.) s cumul t 'smooth cumulative' gpl do set title:"Mixed Distribution (Lognormal with shifted Gaussian)" set :key, :top, :right set boxwidth:0.1 plot ["\"random-points\"", u:'4:(0.25*rand(0)-.35)', t:''], ["\"\"", u:'(bin($4,0.1)):(10/300.)', s:true, f:true, t:'smooth frequency', w:"boxes"], ["\"\"", u:'4:(1/300.)', s:"cumul", t:'smooth cumulative'] end
mit
bitmxittz/Bitmxittz
src/qt/locale/bitcoin_fa_IR.ts
107521
<?xml version="1.0" ?><!DOCTYPE TS><TS language="fa_IR" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Bitmxittz</source> <translation>در مورد بیتکویین</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Bitmxittz&lt;/b&gt; version</source> <translation>&lt;b&gt;Bitmxittz&lt;/b&gt; version</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The Bitmxittz developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>دفترچه آدرس</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>برای ویرایش آدرس/برچسب دوبار کلیک نمایید</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>یک آدرس جدید بسازید</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>آدرس انتخاب شده را در کلیپ بوردِ سیستم کپی کنید</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>و آدرس جدید</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Bitmxittz addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>و کپی آدرس</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>نشان و کد QR</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Bitmxittz address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>صدور داده نوار جاری به یک فایل</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Bitmxittz address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>و حذف</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Bitmxittz addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>کپی و برچسب</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>و ویرایش</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>انتقال اطلاعات دفترچه آدرس</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>سی.اس.وی. (فایل جداگانه دستوری)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>صدور پیام خطا</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>قابل کپی در فایل نیست %1</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>برچسب</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>آدرس</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(برچسب ندارد)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>رمز/پَس فرِیز را وارد کنید</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>رمز/پَس فرِیز جدید را وارد کنید</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>رمز/پَس فرِیز را دوباره وارد کنید</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>رمز/پَس فرِیز جدید را در wallet وارد کنید. برای انتخاب رمز/پَس فرِیز از 10 کاراکتر تصادفی یا بیشتر و یا هشت کلمه یا بیشتر استفاده کنید. </translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>wallet را رمزگذاری کنید</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>برای انجام این عملکرد به رمز/پَس فرِیزِwallet نیاز است تا آن را از حالت قفل درآورد.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>باز کردن قفل wallet </translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>برای کشف رمز wallet، به رمز/پَس فرِیزِwallet نیاز است.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>کشف رمز wallet</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>تغییر رمز/پَس فرِیز</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>رمز/پَس فرِیزِ قدیم و جدید را در wallet وارد کنید</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>رمزگذاری wallet را تایید کنید</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITMXITTZS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>تایید رمزگذاری</translation> </message> <message> <location line="-56"/> <source>Bitmxittz will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitmxittzs from being stolen by malware infecting your computer.</source> <translation>Bitmxittz برای اتمام فرایند رمزگذاری بسته خواهد شد. به خاطر داشته باشید که رمزگذاری WALLET شما، کامپیوتر شما را از آلودگی به بدافزارها مصون نمی دارد.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>رمزگذاری تایید نشد</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>رمزگذاری به علت خطای داخلی تایید نشد. wallet شما رمزگذاری نشد</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>رمزهای/پَس فرِیزهایِ وارد شده با هم تطابق ندارند</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>قفل wallet باز نشد</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>رمزهای/پَس فرِیزهایِ وارد شده wallet برای کشف رمز اشتباه است.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>کشف رمز wallet انجام نشد</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>امضا و پیام</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>به روز رسانی با شبکه...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>و بازبینی</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>نمای کلی از wallet را نشان بده</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>و تراکنش</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>تاریخچه تراکنش را باز کن</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>فهرست آدرسها و برچسبهای ذخیره شده را ویرایش کن</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>فهرست آدرسها را برای دریافت وجه نشان بده</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>خروج</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>از &quot;درخواست نامه&quot;/ application خارج شو</translation> </message> <message> <location line="+4"/> <source>Show information about Bitmxittz</source> <translation>اطلاعات در مورد Bitmxittz را نشان بده</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>درباره و QT</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>نمایش اطلاعات درباره QT</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>و انتخابها</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>و رمزگذاری wallet</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>و گرفتن نسخه پیشتیبان از wallet</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>تغییر رمز/پَس فرِیز</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a Bitmxittz address</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Modify configuration options for Bitmxittz</source> <translation>اصلاح انتخابها برای پیکربندی Bitmxittz</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>گرفتن نسخه پیشتیبان در آدرسی دیگر</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>رمز مربوط به رمزگذاریِ wallet را تغییر دهید</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>Bitmxittz</source> <translation>bitmxittz</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>کیف پول</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About Bitmxittz</source> <translation>&amp;در مورد بیتکویین</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;نمایش/ عدم نمایش و</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Bitmxittz addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Bitmxittz addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>و فایل</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>و تنظیمات</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>و راهنما</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>نوار ابزار</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>Bitmxittz client</source> <translation>مشتری bitmxittz</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Bitmxittz network</source> <translation><numerusform>%n ارتباط فعال به شبکه Bitmxittz %n ارتباط فعال به شبکه Bitmxittz</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>روزآمد</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>در حال روزآمد سازی..</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>ارسال تراکنش</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>تراکنش دریافتی</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>تاریخ: %1⏎ میزان وجه : %2⏎ نوع: %3⏎ آدرس: %4⏎ </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Bitmxittz address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>wallet رمزگذاری شد و در حال حاضر از حالت قفل در آمده است</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>wallet رمزگذاری شد و در حال حاضر قفل است</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Bitmxittz can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>هشدار شبکه</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>ویرایش آدرسها</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>و برچسب</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>برچسب مربوط به این دفترچه آدرس</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>و آدرس</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>برچسب مربوط به این دفترچه آدرس و تنها ب</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>آدرسِ دریافت کننده جدید</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>آدرس ارسال کننده جدید</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>ویرایش آدرسِ دریافت کننده</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>ویرایش آدرسِ ارسال کننده</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>آدرس وارد شده %1 قبلا به فهرست آدرسها اضافه شده بوده است.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Bitmxittz address.</source> <translation>آدرس وارد شده &quot;%1&quot; یک آدرس صحیح برای bitmxittz نسشت</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>عدم توانیی برای قفل گشایی wallet</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>عدم توانیی در ایجاد کلید جدید</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Bitmxittz-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation>نسخه</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>میزان استفاده:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>انتخاب/آپشن</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start Bitmxittz after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Bitmxittz on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the Bitmxittz client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the Bitmxittz network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Bitmxittz.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show Bitmxittz addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>و نمایش آدرسها در فهرست تراکنش</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>و تایید</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>و رد</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>و به کار گرفتن</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>پیش فرض</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Bitmxittz.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>فرم</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Bitmxittz network after a connection is established, but this process has not completed yet.</source> <translation>اطلاعات نمایش داده شده ممکن است روزآمد نباشد. wallet شما به صورت خودکار بعد از برقراری اتصال با شبکه bitmxittz به روز می شود اما این فرایند هنوز تکمیل نشده است.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>مانده حساب:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>تایید نشده</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>کیف پول</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>تراکنشهای اخیر</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>مانده حساب جاری</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>تعداد تراکنشهایی که نیاز به تایید دارند و هنوز در مانده حساب جاری شما به حساب نیامده اند</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>خارج از روزآمد سازی</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start bitmxittz: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>درخواست وجه</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>میزان وجه:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>برچسب:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>پیام:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>و ذخیره با عنوانِ...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>متن وارد شده طولانی است، متنِ برچسب/پیام را کوتاه کنید</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>تصاویر با فرمت PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the Bitmxittz-Qt help message to get a list with possible Bitmxittz command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>Bitmxittz - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Bitmxittz Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Bitmxittz debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Bitmxittz RPC console.</source> <translation>به کنسول آر.پی.سی. BITMXITTZ خوش آمدید</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>سکه های ارسالی</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>ارسال همزمان به گیرنده های متعدد</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>تمامی فیلدهای تراکنش حذف شوند</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>مانده حساب:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>تایید عملیات ارسال </translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>و ارسال</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>%1 به %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>تایید ارسال سکه ها</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>شما مطمئن هستید که می خواهید %1 را ارسال کنید؟</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>و</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>میزان پرداخت باید بیشتر از 0 باشد</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>خطا: تراکنش تایید نشد. این خطا ممکن است به این دلیل اتفاق بیافتد که سکه های wallet شما خرج شده باشند مثلا اگر wallet.dat را مپی کرده باشید و سکه های شما در آن کپی استفاده شده باشند اما در اینجا نمایش داده نشده اند.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>فرم</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>و میزان وجه</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>پرداخت و به چه کسی</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Bb59pmrmnM1nTwNMBwFGtzcQTJh68tMe26)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>یک برچسب برای این آدرس بنویسید تا به دفترچه آدرسهای شما اضافه شود</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>و برچسب</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>آدرس از فهرست آدرس انتخاب کنید</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt و A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>آدرس را بر کلیپ بورد کپی کنید</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt و P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>این گیرنده را حذف کن</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Bitmxittz address (e.g. Bb59pmrmnM1nTwNMBwFGtzcQTJh68tMe26)</source> <translation>یک آدرس bitmxittz وارد کنید (مثال Bb59pmrmnM1nTwNMBwFGtzcQTJh68tMe26)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>و امضای پیام </translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Bb59pmrmnM1nTwNMBwFGtzcQTJh68tMe26)</source> <translation>یک آدرس bitmxittz وارد کنید (مثال Bb59pmrmnM1nTwNMBwFGtzcQTJh68tMe26)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>آدرس از فهرست آدرس انتخاب کنید</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt و A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>آدرس را بر کلیپ بورد کپی کنید</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt و P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Bitmxittz address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Bb59pmrmnM1nTwNMBwFGtzcQTJh68tMe26)</source> <translation>یک آدرس bitmxittz وارد کنید (مثال Bb59pmrmnM1nTwNMBwFGtzcQTJh68tMe26)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Bitmxittz address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Bitmxittz address (e.g. Bb59pmrmnM1nTwNMBwFGtzcQTJh68tMe26)</source> <translation>یک آدرس bitmxittz وارد کنید (مثال Bb59pmrmnM1nTwNMBwFGtzcQTJh68tMe26)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter Bitmxittz signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Bitmxittz developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>باز کن تا %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1 غیرقابل تایید</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 تاییدها</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation>برچسب</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation>پیام</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>میزان</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>تا به حال با موفقیت انتشار نیافته است</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>ناشناس</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>جزئیات تراکنش</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>این بخش جزئیات تراکنش را نشان می دهد</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>نوع</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>آدرس</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>میزان وجه</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>باز کن تا %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>برون خطی (%1 تاییدها)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>تایید نشده (%1 از %2 تاییدها)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>تایید شده (%1 تاییدها)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>این block توسط گره های دیگری دریافت نشده است و ممکن است قبول نشود</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>تولید شده اما قبول نشده است</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>قبول با </translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>دریافت شده از</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>ارسال به</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>وجه برای شما </translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>استخراج شده</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>خالی</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>وضعیت تراکنش. با اشاره به این بخش تعداد تاییدها نمایش داده می شود</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>زمان و تاریخی که تراکنش دریافت شده است</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>نوع تراکنش</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>آدرس مقصد در تراکنش</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>میزان وجه کم شده یا اضافه شده به حساب</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>همه</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>امروز</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>این هفته</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>این ماه</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>ماه گذشته</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>این سال</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>حدود..</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>دریافت با</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>ارسال به</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>به شما</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>استخراج شده</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>دیگر</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>آدرس یا برچسب را برای جستجو وارد کنید</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>حداقل میزان وجه</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>آدرس را کپی کنید</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>برچسب را کپی کنید</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>میزان وجه کپی شود</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>برچسب را ویرایش کنید</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>داده های تراکنش را صادر کنید</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv) فایل جداگانه دستوری</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>تایید شده</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>نوع</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>برچسب</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>آدرس</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>میزان</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>شناسه کاربری</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>خطا در ارسال</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>قابل کپی به فایل نیست %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>دامنه:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>به</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>سکه های ارسالی</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>صدور داده نوار جاری به یک فایل</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Bitmxittz version</source> <translation>نسخه bitmxittz</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>میزان استفاده:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or bitmxittzd</source> <translation>ارسال دستور به سرور یا bitmxittzed</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>فهرست دستورها</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>درخواست کمک برای یک دستور</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>انتخابها:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: bitmxittz.conf)</source> <translation>فایل پیکربندیِ را مشخص کنید (پیش فرض: bitmxittz.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: bitmxittzd.pid)</source> <translation>فایل pid را مشخص کنید (پیش فرض: bitmxittzd.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>دایرکتوری داده را مشخص کن</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>حافظه بانک داده را به مگابایت تنظیم کنید (پیش فرض: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 14433 or testnet: 15433)</source> <translation>ارتباطات را در &lt;PORT&gt; بشنوید (پیش فرض: 14433 or testnet: 15433)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>نگهداری &lt;N&gt; ارتباطات برای قرینه سازی (پیش فرض:125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>آستانه قطع برای قرینه سازی اشتباه (پیش فرض:100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>تعداد ثانیه ها برای اتصال دوباره قرینه های اشتباه (پیش فرض:86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 14432 or testnet: 15432)</source> <translation>ارتباطاتِ JSON-RPC را در &lt;port&gt; گوش کنید (پیش فرض:14432)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>command line و JSON-RPC commands را قبول کنید</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>به عنوان daemon بک گراند را اجرا کنید و دستورات را قبول نمایید</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>از تستِ شبکه استفاده نمایید</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bitmxittzrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Bitmxittz Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Bitmxittz is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Bitmxittz will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>برونداد اشکال زدایی با timestamp</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Bitmxittz Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>ارسال اطلاعات پیگیری/خطایابی به کنسول به جای ارسال به فایل debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>ارسال اطاعات خطایابی/پیگیری به سیستم خطایاب</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>تعیین مدت زمان وقفه (time out) به هزارم ثانیه</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>شناسه کاربری برای ارتباطاتِ JSON-RPC</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>رمز برای ارتباطاتِ JSON-RPC</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>ارتباطاتِ JSON-RPC را از آدرس آی.پی. مشخصی برقرار کنید.</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>دستورات را به گره اجرا شده در&lt;ip&gt; ارسال کنید (پیش فرض:127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>دستور را وقتی بهترین بلاک تغییر کرد اجرا کن (%s در دستور توسط block hash جایگزین شده است)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>wallet را به جدیدترین نسخه روزآمد کنید</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>حجم key pool را به اندازه &lt;n&gt; تنظیم کنید (پیش فرض:100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>زنجیره بلاک را برای تراکنش جا افتاده در WALLET دوباره اسکن کنید</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>برای ارتباطاتِ JSON-RPC از OpenSSL (https) استفاده کنید</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>فایل certificate سرور (پیش فرض server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>رمز اختصاصی سرور (پیش فرض: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>ciphers قابل قبول (پیش فرض: default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>این پیام راهنما</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>لود شدن آدرسها..</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>خطا در هنگام لود شدن wallet.dat: Wallet corrupted</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Bitmxittz</source> <translation>خطا در هنگام لود شدن wallet.dat. به نسخه جدید Bitocin برای wallet نیاز است.</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Bitmxittz to complete</source> <translation>wallet نیاز به بازنویسی دارد. Bitmxittz را برای تکمیل عملیات دوباره اجرا کنید.</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>خطا در هنگام لود شدن wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>میزان اشتباه است for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>میزان اشتباه است</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>وجوه ناکافی</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>لود شدن نمایه بلاکها..</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>یک گره برای اتصال اضافه کنید و تلاش کنید تا اتصال را باز نگاه دارید</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Bitmxittz is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>هزینه بر اساس کیلو بایت برای اضافه شدن به تراکنشی که ارسال کرده اید</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>wallet در حال لود شدن است...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>قابلیت برگشت به نسخه قبلی برای wallet امکان پذیر نیست</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>آدرس پیش فرض قابل ذخیره نیست</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>اسکنِ دوباره...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>اتمام لود شدن</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>برای استفاده از %s از اختیارات</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>خطا</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>شما باید یک رمز rpcpassword=&lt;password&gt; را در فایل تنظیمات ایجاد کنید⏎ %s ⏎ اگر فایل ایجاد نشده است، آن را با یک فایل &quot;فقط متنی&quot; ایجاد کنید. </translation> </message> </context> </TS>
mit
bo-blog/bw
index.php
513
<?php /** * * @link http://bw.bo-blog.com * @copyright (c) 2014 bW Development Team * @license MIT */ //Only modify the below line manually when necessary. define ('FORCE_UGLY_URL', 0); if (!defined ('P')) { define ('P', './'); } define ('FPATH', dirname (__FILE__)); include_once (P . 'inc/system.php'); if (isset ($_REQUEST['list'])) { //two hidden mode, for static page mode aka "Mill" project. define ('M', 'list'); } $canonical = new bwCanonicalization; include_once ($canonical -> loader ());
mit
alexandr1221/drf-angularjs-todolist
btodolist/views.py
270
from django.shortcuts import render_to_response from django.template import RequestContext def home(request): """ A index view. """ template_name = "index.html" return render_to_response(template_name, context_instance=RequestContext(request))
mit
yeputons/ofeed
src/net/yeputons/ofeed/MainActivity.java
14350
package net.yeputons.ofeed; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.stmt.UpdateBuilder; import com.vk.sdk.VKAccessToken; import com.vk.sdk.VKCallback; import com.vk.sdk.VKSdk; import com.vk.sdk.api.*; import com.vk.sdk.api.methods.VKApiFeed; import com.vk.sdk.api.model.*; import net.yeputons.ofeed.db.*; import net.yeputons.ofeed.web.DeepWebPageSaver; import net.yeputons.ofeed.web.DownloadCompleteListener; import net.yeputons.ofeed.web.ResourceDownload; import net.yeputons.ofeed.web.WebResource; import java.net.URI; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Callable; public class MainActivity extends Activity implements VKCallback<VKAccessToken> { private static final String TAG = MainActivity.class.getName(); private Menu optionsMenu; private FeedListViewAdapter adapter; private int loadStep = 50; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); adapter = new FeedListViewAdapter(this); ListView listFeed = (ListView) findViewById(R.id.listFeed); listFeed.setAdapter(adapter); listFeed.setEmptyView(findViewById(R.id.textEmptyFeed)); listFeed.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { VKApiFeedItem feedItem = adapter.getItem(position).feedItem; if (feedItem != null) { Intent intent = new Intent(MainActivity.this, PostActivity.class); intent.putExtra(PostActivity.EXTRA_POST, feedItem); startActivity(intent); } } }); if (VKAccessToken.currentToken() == null) { logout(null); login(null); } else { onResult(VKAccessToken.currentToken()); } } @Override protected void onDestroy() { optionsMenu = null; adapter = null; super.onDestroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (!VKSdk.onActivityResult(requestCode, resultCode, data, this)) { super.onActivityResult(requestCode, resultCode, data); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); optionsMenu = menu; updateMenuStatus(); return true; } public void login(MenuItem item) { VKSdk.login(this, "friends", "wall"); } public void loadBeginning(MenuItem item) { new VKApiFeed().get(VKParameters.from( VKApiConst.COUNT, loadStep, VKApiFeed.FILTERS, VKApiFeed.FILTERS_POST )).executeWithListener(feedGetListener); } public void loadFrom(final String startFrom) { new VKApiFeed().get(VKParameters.from( VKApiConst.COUNT, loadStep, VKApiFeed.FILTERS, VKApiFeed.FILTERS_POST, VKApiFeed.START_FROM, startFrom )).executeWithListener(new VKRequest.VKRequestListener() { @Override public void onComplete(VKResponse response) { feedGetListener.onComplete(response); UpdateBuilder<CachedFeedItem, String> update = DbHelper.get().getCachedFeedItemDao().updateBuilder(); try { update.where().eq(CachedFeedItem.NEXT_PAGE_TO_LOAD, startFrom); update.updateColumnValue(CachedFeedItem.NEXT_PAGE_TO_LOAD, ""); update.update(); DbHelper.get().getCachedFeedItemDao().deleteById(CachedFeedItem.getPageEndId(startFrom)); } catch (SQLException e) { Log.e(TAG, "Unable to remove 'next page' marker from some feed items", e); } adapter.completePageLoad(startFrom); adapter.notifyDataSetChanged(); } @Override public void attemptFailed(VKRequest request, int attemptNumber, int totalAttempts) { feedGetListener.attemptFailed(request, attemptNumber, totalAttempts); adapter.completePageLoad(startFrom); adapter.notifyDataSetChanged(); } @Override public void onError(VKError error) { feedGetListener.onError(error); adapter.completePageLoad(startFrom); adapter.notifyDataSetChanged(); } @Override public void onProgress(VKRequest.VKProgressType progressType, long bytesLoaded, long bytesTotal) { feedGetListener.onProgress(progressType, bytesLoaded, bytesTotal); adapter.completePageLoad(startFrom); adapter.notifyDataSetChanged(); } }); } public void loadStep2(MenuItem item) { loadStep = 2; } public void loadStep50(MenuItem item) { loadStep = 50; } public void clearCache(MenuItem item) { DbHelper h = DbHelper.get(); try { h.getCachedFeedItemDao().deleteBuilder().delete(); h.getCachedGroupDao().deleteBuilder().delete(); h.getCachedUserDao().deleteBuilder().delete(); h.getCachedWebResourcesDao().deleteBuilder().delete(); h.getCachedWebPageDao().deleteBuilder().delete(); } catch (SQLException e) { Log.e(TAG, "Unable to clear cache", e); Toast.makeText(this, "Error while clearing cache, it may become inconsistent", Toast.LENGTH_LONG).show(); } adapter.notifyDataSetChanged(); } public void logout(MenuItem item) { VKSdk.logout(); clearCache(item); updateMenuStatus(); } private void updateMenuStatus() { if (optionsMenu == null) { return; } boolean isLoggedIn = VKAccessToken.currentToken() != null; optionsMenu.findItem(R.id.menuItemLogin).setEnabled(!isLoggedIn); optionsMenu.findItem(R.id.menuItemLoadBeginning).setEnabled(isLoggedIn); optionsMenu.findItem(R.id.menuItemLogout).setEnabled(isLoggedIn); } private final VKRequest.VKRequestListener feedGetListener = new VKRequest.VKRequestListener() { @Override public void onComplete(VKResponse response) { final VKApiFeedPage page = (VKApiFeedPage) response.parsedModel; final Dao<CachedUser, Integer> userDao = DbHelper.get().getCachedUserDao(); final Dao<CachedGroup, Integer> groupDao = DbHelper.get().getCachedGroupDao(); final ArrayList<CachedFeedItem> feed = new ArrayList<CachedFeedItem>(); if (page.items.length == 0) { return; } Set<String> occuredItems = new HashSet<>(); for (VKApiFeedItem item : page.items) { CachedFeedItem item2 = new CachedFeedItem(item); if (occuredItems.contains(item2.id)) { Log.w(TAG, "Received duplicated item in response from VK: " + item2.id); continue; } occuredItems.add(item2.id); feed.add(item2); if (item.post != null && item.post.attachments != null) { for (VKAttachments.VKApiAttachment a : item.post.attachments) { if (a instanceof VKApiLink) { VKApiLink l = (VKApiLink) a; final URI uri = URI.create(l.url); if (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")) { DeepWebPageSaver saver = new DeepWebPageSaver(OfeedApplication.getDownloader()); final WebResource resource = saver.savePage(uri); saver.setDownloadCompleteListener(new DownloadCompleteListener() { @Override public void onDownloadComplete() { CachedWebPage page = new CachedWebPage(); page.uri = uri.toString(); ResourceDownload d = resource.getDownloaded(); if (d == null) { Log.e(TAG, "Oops, unable to deep save web page"); return; } page.localFile = d.getLocalFile().getAbsolutePath(); try { DbHelper.get().getCachedWebPageDao().create(page); adapter.notifyDataSetChanged(); } catch (SQLException e) { Log.e(TAG, "Cannot save deep downloaded page info to db", e); } } }); } } } } } final CachedFeedItem pageEndPlaceholder = new CachedFeedItem(page.items[page.items.length - 1], page.next_from); final Dao<CachedFeedItem, String> itemDao = DbHelper.get().getCachedFeedItemDao(); try { userDao.callBatchTasks(new Callable<Void>() { @Override public Void call() throws Exception { for (VKApiUser u : page.profiles) { userDao.createOrUpdate(new CachedUser(u)); } return null; } }); groupDao.callBatchTasks(new Callable<Void>() { @Override public Void call() throws Exception { for (VKApiCommunity g : page.groups) { groupDao.createOrUpdate(new CachedGroup(g)); } return null; } }); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { for (VKApiUser u : page.profiles) { WebResourcesCache.getDownloadingWebResource(URI.create(u.photo_100)); } for (VKApiCommunity g : page.groups) { WebResourcesCache.getDownloadingWebResource(URI.create(g.photo_100)); } return null; } }.execute(); itemDao.callBatchTasks(new Callable<Void>() { @Override public Void call() throws Exception { boolean pageDoesNotContinue = true; for (int i = 0; i < feed.size(); i++) { CachedFeedItem item = feed.get(i); CachedFeedItem old = itemDao.queryForFirst( itemDao.queryBuilder() .selectColumns("nextPageToLoad") .where().eq("id", item.id).prepare()); if (i + 1 == feed.size()) { if (old != null && old.nextPageToLoad.isEmpty()) { item.nextPageToLoad = ""; pageDoesNotContinue = false; } else { item.nextPageToLoad = page.next_from; } } else { if (old != null && !old.nextPageToLoad.isEmpty()) { itemDao.deleteById(CachedFeedItem.getPageEndId(old.nextPageToLoad)); } item.nextPageToLoad = ""; } itemDao.createOrUpdate(item); } if (pageDoesNotContinue) { itemDao.createOrUpdate(pageEndPlaceholder); } return null; } }); } catch (Exception e) { Log.e(TAG, "Unable to update db with received feed items", e); } adapter.notifyDataSetChanged(); Log.d(TAG, "next_from=" + page.next_from); } @Override public void onError(VKError error) { Toast.makeText(MainActivity.this, "Error: " + error.toString(), Toast.LENGTH_SHORT).show(); } @Override public void onProgress(VKRequest.VKProgressType progressType, long bytesLoaded, long bytesTotal) { Toast.makeText( MainActivity.this, String.format("Progress %d/%d", bytesLoaded, bytesTotal), Toast.LENGTH_SHORT ).show(); } }; @Override public void onResult(final VKAccessToken res) { updateMenuStatus(); } @Override public void onError(VKError error) { Toast.makeText(this, "Error while logging in: " + error, Toast.LENGTH_LONG).show(); } }
mit
aspartam206/BahasaPemrograman
BaproA/src/com/wicaku/BaproA.java
112
package com.wicaku; public class BaproA { public static void main(String[] args) { } }
mit
GregoryComer/rust-x86asm
src/test/instruction_tests/instr_vpsubusb.rs
7985
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn vpsubusb_1() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM7)), operand3: Some(Direct(XMM6)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 193, 216, 238], OperandSize::Dword) } #[test] fn vpsubusb_2() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM7)), operand3: Some(Indirect(ESI, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 193, 216, 14], OperandSize::Dword) } #[test] fn vpsubusb_3() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM5)), operand3: Some(Direct(XMM2)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 209, 216, 202], OperandSize::Qword) } #[test] fn vpsubusb_4() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM2)), operand3: Some(Indirect(RBX, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 233, 216, 35], OperandSize::Qword) } #[test] fn vpsubusb_5() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(YMM1)), operand2: Some(Direct(YMM4)), operand3: Some(Direct(YMM3)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 221, 216, 203], OperandSize::Dword) } #[test] fn vpsubusb_6() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(YMM4)), operand2: Some(Direct(YMM7)), operand3: Some(IndirectScaledIndexed(ESI, EDI, Two, Some(OperandSize::Ymmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 197, 216, 36, 126], OperandSize::Dword) } #[test] fn vpsubusb_7() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(YMM1)), operand2: Some(Direct(YMM4)), operand3: Some(Direct(YMM4)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 221, 216, 204], OperandSize::Qword) } #[test] fn vpsubusb_8() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(YMM0)), operand2: Some(Direct(YMM2)), operand3: Some(IndirectDisplaced(RBX, 2146804369, Some(OperandSize::Ymmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 237, 216, 131, 145, 162, 245, 127], OperandSize::Qword) } #[test] fn vpsubusb_9() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM3)), operand3: Some(Direct(XMM5)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 241, 101, 139, 216, 245], OperandSize::Dword) } #[test] fn vpsubusb_10() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM5)), operand3: Some(IndirectScaledIndexedDisplaced(EAX, ECX, Four, 1203704777, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 241, 85, 137, 216, 180, 136, 201, 19, 191, 71], OperandSize::Dword) } #[test] fn vpsubusb_11() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(XMM12)), operand2: Some(Direct(XMM7)), operand3: Some(Direct(XMM8)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 81, 69, 138, 216, 224], OperandSize::Qword) } #[test] fn vpsubusb_12() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(XMM17)), operand2: Some(Direct(XMM1)), operand3: Some(Indirect(RDX, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 225, 117, 143, 216, 10], OperandSize::Qword) } #[test] fn vpsubusb_13() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(YMM3)), operand2: Some(Direct(YMM2)), operand3: Some(Direct(YMM2)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 241, 109, 169, 216, 218], OperandSize::Dword) } #[test] fn vpsubusb_14() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(YMM4)), operand2: Some(Direct(YMM3)), operand3: Some(IndirectDisplaced(ECX, 2061308849, Some(OperandSize::Ymmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 241, 101, 175, 216, 161, 177, 19, 221, 122], OperandSize::Dword) } #[test] fn vpsubusb_15() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(YMM3)), operand2: Some(Direct(YMM17)), operand3: Some(Direct(YMM10)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: None }, &[98, 209, 117, 164, 216, 218], OperandSize::Qword) } #[test] fn vpsubusb_16() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(YMM12)), operand2: Some(Direct(YMM1)), operand3: Some(IndirectDisplaced(RSI, 231429742, Some(OperandSize::Ymmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 113, 117, 169, 216, 166, 110, 86, 203, 13], OperandSize::Qword) } #[test] fn vpsubusb_17() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(ZMM6)), operand2: Some(Direct(ZMM6)), operand3: Some(Direct(ZMM7)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None }, &[98, 241, 77, 205, 216, 247], OperandSize::Dword) } #[test] fn vpsubusb_18() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(ZMM1)), operand2: Some(Direct(ZMM6)), operand3: Some(IndirectScaledDisplaced(EDI, Four, 1516100427, Some(OperandSize::Zmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 241, 77, 203, 216, 12, 189, 75, 219, 93, 90], OperandSize::Dword) } #[test] fn vpsubusb_19() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(ZMM26)), operand2: Some(Direct(ZMM30)), operand3: Some(Direct(ZMM6)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 97, 13, 199, 216, 214], OperandSize::Qword) } #[test] fn vpsubusb_20() { run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSB, operand1: Some(Direct(ZMM14)), operand2: Some(Direct(ZMM15)), operand3: Some(IndirectScaledDisplaced(RBX, Four, 2097189521, Some(OperandSize::Zmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: None }, &[98, 113, 5, 204, 216, 52, 157, 145, 146, 0, 125], OperandSize::Qword) }
mit
cfurrow/WatchMeRun
WatchMeRun.Library/Properties/AssemblyInfo.cs
1448
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WatchMeRun.Library")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WatchMeRun.Library")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e71cbd4d-9761-4d1e-b69d-7c907a78676c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
needto/omniauth
oa-enterprise/lib/omniauth/strategies/ldap.rb
3894
require 'omniauth/enterprise' require 'net/ldap' require 'sasl/base' require 'sasl' module OmniAuth module Strategies class LDAP include OmniAuth::Strategy autoload :Adaptor, 'omniauth/strategies/ldap/adaptor' @@config = {'name' => 'cn', 'first_name' => 'givenName', 'last_name' => 'sn', 'email' => ['mail', "email", 'userPrincipalName'], 'phone' => ['telephoneNumber', 'homePhone', 'facsimileTelephoneNumber'], 'mobile_number' => ['mobile', 'mobileTelephoneNumber'], 'nickname' => ['uid', 'userid', 'sAMAccountName'], 'title' => 'title', 'location' => {"%0, %1, %2, %3 %4" => [['address', 'postalAddress', 'homePostalAddress', 'street', 'streetAddress'], ['l'], ['st'],['co'],['postOfficeBox']]}, 'uid' => 'dn', 'url' => ['wwwhomepage'], 'image' => 'jpegPhoto', 'description' => 'description'} # Initialize the LDAP Middleware # # @param [Rack Application] app Standard Rack middleware argument. # @option options [String, 'LDAP Authentication'] :title A title for the authentication form. def initialize(app, options = {}, &block) super(app, options[:name] || :ldap, options.dup, &block) @name_proc = (@options.delete(:name_proc) || Proc.new {|name| name}) @adaptor = OmniAuth::Strategies::LDAP::Adaptor.new(options) end protected def request_phase if env['REQUEST_METHOD'] == 'GET' get_credentials else session['omniauth.ldap'] = {'username' => request['username'], 'password' => request['password']} redirect callback_path end end def get_credentials OmniAuth::Form.build(options[:title] || "LDAP Authentication") do text_field 'Login', 'username' password_field 'Password', 'password' end.to_response end def callback_phase begin creds = session.delete 'omniauth.ldap' @ldap_user_info = {} begin (@adaptor.bind(:allow_anonymous => true) unless @adaptor.bound?) rescue Exception => e puts "failed to bind with the default credentials: " + e.message end @ldap_user_info = @adaptor.search(:filter => Net::LDAP::Filter.eq(@adaptor.uid, @name_proc.call(creds['username'])),:limit => 1) if @adaptor.bound? bind_dn = creds['username'] bind_dn = @ldap_user_info[:dn].to_a.first if @ldap_user_info[:dn] @adaptor.bind(:bind_dn => bind_dn, :password => creds['password']) @ldap_user_info = @adaptor.search(:filter => Net::LDAP::Filter.eq(@adaptor.uid, @name_proc.call(creds['username'])),:limit => 1) if @ldap_user_info.empty? @user_info = self.class.map_user(@@config, @ldap_user_info) @env['omniauth.auth'] = auth_hash rescue Exception => e return fail!(:invalid_credentials, e) end call_app! end def auth_hash OmniAuth::Utils.deep_merge(super, { 'uid' => @user_info["uid"], 'user_info' => @user_info, 'extra' => @ldap_user_info }) end def self.map_user(mapper, object) user = {} mapper.each do |key, value| case value when String user[key] = object[value.downcase.to_sym].to_s if object[value.downcase.to_sym] when Array value.each {|v| (user[key] = object[v.downcase.to_sym].to_s; break;) if object[v.downcase.to_sym]} when Hash value.map do |key1, value1| pattern = key1.dup value1.each_with_index do |v,i| part = ''; v.each {|v1| (part = object[v1.downcase.to_sym].to_s; break;) if object[v1.downcase.to_sym]} pattern.gsub!("%#{i}",part||'') end user[key] = pattern end end end user end end end end
mit
south-coast-science/scs_dev
src/scs_dev/cmd/cmd_sampler.py
3452
""" Created on 13 Jul 2016 @author: Bruno Beloff ([email protected]) """ import logging import optparse # -------------------------------------------------------------------------------------------------------------------- class CmdSampler(object): """unix command line handler""" def __init__(self): """ Constructor """ self.__parser = optparse.OptionParser(usage="%prog [-n NAME] [{ -s SEMAPHORE | -i INTERVAL [-c SAMPLES] }] " "[{ -v | -d }]", version="%prog 1.0") # optional... self.__parser.add_option("--name", "-n", type="string", nargs=1, action="store", dest="name", help="the name of the sampler configuration") self.__parser.add_option("--semaphore", "-s", type="string", nargs=1, action="store", dest="semaphore", help="sampling controlled by SEMAPHORE") self.__parser.add_option("--interval", "-i", type="float", nargs=1, action="store", dest="interval", help="sampling interval in seconds") self.__parser.add_option("--samples", "-c", type="int", nargs=1, action="store", dest="samples", help="sample count (1 if interval not specified)") self.__parser.add_option("--verbose", "-v", action="store_true", dest="verbose", default=False, help="report narrative to stderr") self.__parser.add_option("--debug", "-d", action="store_true", dest="debug", default=False, help="report detailed narrative to stderr") self.__opts, self.__args = self.__parser.parse_args() # ---------------------------------------------------------------------------------------------------------------- def is_valid(self): if self.__opts.semaphore is not None and self.__opts.interval is not None: return False if self.__opts.interval is None and self.__opts.samples is not None: return False if self.verbose and self.debug: return False return True def log_level(self): if self.debug: return logging.DEBUG if self.verbose: return logging.INFO return logging.ERROR # ---------------------------------------------------------------------------------------------------------------- @property def name(self): return self.__opts.name @property def semaphore(self): return self.__opts.semaphore @property def interval(self): return 0 if self.__opts.interval is None else self.__opts.interval @property def samples(self): return 1 if self.__opts.interval is None else self.__opts.samples @property def verbose(self): return self.__opts.verbose @property def debug(self): return self.__opts.debug # ---------------------------------------------------------------------------------------------------------------- def print_help(self, file): self.__parser.print_help(file) def __str__(self, *args, **kwargs): return "CmdSampler:{name:%s, semaphore:%s, interval:%s, samples:%s, verbose:%s, debug:%s}" % \ (self.name, self.semaphore, self.interval, self.samples, self.verbose, self.debug)
mit
daverodal/webwargaming
Mollwitz/Fontenoy1745/playAs.php
3909
<?php /* Copyright 2012-2015 David Rodal This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ ?><head> <meta charset="UTF-8"> <link href='http://fonts.googleapis.com/css?family=Great+Vibes' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Petit+Formal+Script' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Monsieur+La+Doulaise' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Pinyon+Script' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Berkshire+Swash' rel='stylesheet' type='text/css'> <style> body{ background:#000; background:url("<?=base_url("js/The_Battle_of_Fontenoy,_11th_May_1745.png")?>") #333 no-repeat; background-position:center 0; background-size:100%; } h2{ color:#f66; text-shadow: 0 0 3px black,0 0 3px black,0 0 3px black,0 0 3px black,0 0 3px black,0 0 3px black, 0 0 3px black,0 0 3px black; } h1{ text-align:center; font-size:90px; font-family:'Pinyon Scrip'; color:#f66; margin-top:0px; text-shadow: 0 0 5px black,0 0 5px black,0 0 5px black,0 0 5px black,0 0 5px black,0 0 5px black, 0 0 5px black,0 0 5px black,0 0 5px black,0 0 5px black,0 0 5px black,0 0 5px black,0 0 5px black, 0 0 5px black,0 0 5px black,0 0 5px black, 0 0 5px black,0 0 5px black,0 0 5px black,0 0 5px black, 0 0 5px black,0 0 5px black,0 0 5px black; } .link{ font-size:40px; text-decoration: none; color:#f66; text-shadow: 3px 3px 3px black,3px 3px 3px black,3px 3px 3px black,3px 3px 3px black,3px 3px 3px black } legend { text-decoration: none; color:#f66; text-shadow: 3px 3px 3px black,3px 3px 3px black,3px 3px 3px black,3px 3px 3px black,3px 3px 3px black } fieldset{ text-align: center; width:30%; margin:0px; position:absolute; top:300px; left:50%; margin-left:-15%; background-color: rgba(255,255,255,.4); } .attribution{ background: rgba(255,255,255,.6); } .attribution a{ color:red; text-shadow: 1px 1px 1px black; } </style> </head> <body> <div class="backBox"> <h2 style="text-align:center;font-size:30px;font-family:'Monsieur La Doulaise'"> Welcome to</h2> <h1 style=""><span>Fontenoy 1745</span></h1> </div> <div style="clear:both"></div> <fieldset ><Legend>Play As </Legend> <a class="link" href="<?=site_url("wargame/enterHotseat");?>/<?=$wargame?>/">Play Hotseat</a><br> <a class="link" href="<?=site_url("wargame/enterMulti");?>/<?=$wargame?>/">Play Multi</a><br> <a class="link" href="<?=site_url("wargame/leaveGame");?>">Go to Lobby</a><br> <div class="attribution"> Horace Vernet [Public domain], <a target="blank" href="https://commons.wikimedia.org/wiki/File%3AThe_Battle_of_Fontenoy%2C_11th_May_1745.png">via Wikimedia Commons</a> </div> </fieldset>
mit
Freaky/fast_find
lib/fast_find/version.rb
71
# frozen_string_literal: true module FastFind VERSION = '0.2.1' end
mit
ollien/Timpani
timpani/webserver/controllers/user.py
5492
import flask import os.path import datetime from ... import auth from ... import blog from ... import configmanager from ... import settings from ... import themes from .. import webhelpers import random TEMPLATE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../templates")) blueprint = flask.Blueprint("user", __name__, template_folder=TEMPLATE_PATH) @blueprint.route("/") def showPosts(): pageLimit = int(settings.getSettingValue("posts_per_page")) posts = blog.getPosts(limit=pageLimit) templatePath = os.path.join(TEMPLATE_PATH, "posts.html") postParams = webhelpers.getPostsParameters() pageTitle = postParams["blogTitle"] pageCount = blog.getPageCount(blog.getPostCount(), pageLimit) nextPageExists = (blog.nextPageExists(blog.getPostCount(), pageLimit, 1)) return webhelpers.renderPosts(templatePath, pageTitle, 1, pageCount, nextPageExists, posts=posts) @blueprint.route("/page/<int:pageNumber>") def showPostWithPage(pageNumber): if pageNumber < 1: return flask.abort(400) pageLimit = int(settings.getSettingValue("posts_per_page")) posts = blog.getPosts(limit=pageLimit, offset=pageLimit * (pageNumber - 1)) templatePath = os.path.join(TEMPLATE_PATH, "posts.html") postParams = webhelpers.getPostsParameters() pageTitle = "{} - page {}".format(postParams["blogTitle"], pageNumber) pageCount = blog.getPageCount(blog.getPostCount(), pageLimit) nextPageExists = (blog.nextPageExists(blog.getPostCount(), pageLimit, pageNumber)) return webhelpers.renderPosts(templatePath, pageTitle, pageNumber, pageCount, nextPageExists, posts=posts) @blueprint.route("/post/<int:postId>") def showPost(postId): post = blog.getPostById(postId) if post is None: return flask.abort(404) templatePath = os.path.join(TEMPLATE_PATH, "posts.html") postParams = webhelpers.getPostsParameters() pageTitle = "{} - {}".format(postParams["blogTitle"], post["post"].title) return webhelpers.renderPosts(templatePath, pageTitle, 1, 1, False, posts=[post]) @blueprint.route("/tag/<tag>") def showPostsWithTag(tag): pageLimit = int(settings.getSettingValue("posts_per_page")) posts = blog.getPostsWithTag(tag, limit=pageLimit) if len(posts) == 0: return flask.abort(404) templatePath = os.path.join(TEMPLATE_PATH, "posts.html") postParams = webhelpers.getPostsParameters() pageTitle = "{} - #{}".format(postParams["blogTitle"], tag) pageCount = blog.getPageCount(blog.getPostWithTagCount(tag), pageLimit) nextPageExists = (blog.nextPageExists(blog.getPostWithTagCount(tag), pageLimit, 1)) return webhelpers.renderPosts(templatePath, pageTitle, 1, pageCount, nextPageExists, posts=posts, pageBaseString="/tag/{}".format(tag)) @blueprint.route("/tag/<tag>/page/<int:pageNumber>") def showPostWithTagAndPage(tag, pageNumber): if pageNumber < 1: flask.abort(400) pageLimit = int(settings.getSettingValue("posts_per_page")) posts = (blog.getPostsWithTag(tag, limit=pageLimit, offset=pageLimit * (pageNumber - 1))) templatePath = os.path.join(TEMPLATE_PATH, "posts.html") postParams = webhelpers.getPostsParameters() pageTitle = "{} - #{}".format(postParams["blogTitle"], tag) pageCount = blog.getPageCount(blog.getPostWithTagCount(tag), pageLimit) nextPageExists = blog.nextPageExists(blog.getPostWithTagCount(tag), pageLimit, pageNumber) return webhelpers.renderPosts(templatePath, pageTitle, pageNumber, pageCount, nextPageExists, posts=posts, pageBaseString="/tag/{}".format(tag)) @blueprint.route("/login", methods=["GET", "POST"]) def login(): if flask.request.method == "GET": if webhelpers.checkForSession(): return flask.redirect("/manage") else: return flask.render_template("login.html") elif flask.request.method == "POST": if ("username" not in flask.request.form or "password" not in flask.request.form): flask.flash("A username and password must be provided.") return flask.render_template("login.html") elif auth.validateUser(flask.request.form["username"], flask.request.form["password"]): donePage = webhelpers.canRecoverFromRedirect() donePage = donePage if donePage is not None else "/manage" sessionId, expires = auth.createSession(flask.request.form["username"]) flask.session["uid"] = sessionId flask.session.permanent = True flask.session.permanent_session_lifetime = datetime.datetime.now() - expires return flask.redirect(donePage) else: flask.flash("Invalid username or password.") return flask.render_template("login.html") @blueprint.route("/logout", methods=["POST"]) def logout(): if webhelpers.checkForSession(): if "uid" in flask.session: sessionId = flask.session["uid"] auth.invalidateSession(sessionId) flask.session.clear() return flask.redirect("/login") @blueprint.route("/static/theme/<path:filePath>") def themeStatic(filePath): currentTheme = themes.getCurrentTheme() if currentTheme["staticPath"] is None: return "", 404 staticPath = currentTheme["staticPath"] return flask.send_from_directory(staticPath, filePath)
mit
nerab/paradeiser
lib/paradeiser/controllers/paradeiser_controller.rb
1305
require 'fileutils' require 'active_support/core_ext/enumerable' require 'active_model' require 'active_model/serializers/json' module Paradeiser class ParadeiserController < Controller def init FileUtils.mkdir_p(Paradeiser.par_dir) FileUtils.cp_r(File.join(Paradeiser.templates_dir, Paradeiser.os.to_s, 'hooks'), Paradeiser.par_dir) end def report pomodori = Repository.all_pomodori @finished = pomodori.select{|p| p.finished?}.size @canceled = pomodori.select{|p| p.canceled?}.size @external_interrupts = pomodori.map{|p| p.interrupts}.flatten.select{|i| :external == i.type}.size @internal_interrupts = pomodori.map{|p| p.interrupts}.flatten.select{|i| :internal == i.type}.size breaks = Repository.all_breaks @breaks = breaks.size @break_minutes = breaks.sum{|b| b.duration}.to_i.minutes @annotations = pomodori.collect{|p| p.annotations}.flatten self.has_output = true end def status @pom = Repository.active || Repository.all.last self.exitstatus = Status.of(@pom).to_i self.has_output = true render(:text => 'There are no pomodori or breaks.') unless @pom end def export self.has_output = true render(:text => Repository.all.to_json) end end end
mit
Whaka-project/whakamatautau-util
src/main/java/org/whaka/asserts/UberMatchers.java
8228
package org.whaka.asserts; import java.util.Collection; import java.util.Objects; import java.util.function.BiPredicate; import java.util.function.Function; import java.util.regex.Pattern; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.whaka.asserts.matcher.ComparisonMatcher; import org.whaka.asserts.matcher.ConsistencyMatcher; import org.whaka.asserts.matcher.FunctionalMatcher; import org.whaka.asserts.matcher.RegexpMatcher; import org.whaka.asserts.matcher.ThrowableMatcher; import org.whaka.util.UberCollections; import org.whaka.util.reflection.comparison.ComparisonPerformer; import org.whaka.util.reflection.comparison.ComparisonPerformers; import com.google.common.base.Preconditions; /** * Class provides static factory methods for custom Hamcrest matchers provided by the library. * * @see NumberMatchers */ public final class UberMatchers { private UberMatchers() { } /** * Create a matcher that will check that tested item and specified value are equal * according to the specified {@link ComparisonPerformer}. * * @see #deeplyEqualTo(Object) * @see #reflectivelyEqualTo(Object) * @see ComparisonMatcher * @see ComparisonPerformers */ public static <T> Matcher<T> equalTo(T item, ComparisonPerformer<? super T> performer) { return new ComparisonMatcher<>(item, performer); } /** * Create a matcher that will check that tested item and specified value are equal * according to the {@link ComparisonPerformers#DEEP_EQUALS} performer. * * @see #equalTo(Object, ComparisonPerformer) * @see #reflectivelyEqualTo(Object) * @see ComparisonMatcher * @see ComparisonPerformers */ public static <T> Matcher<T> deeplyEqualTo(T item) { return equalTo(item, ComparisonPerformers.DEEP_EQUALS); } /** * Create a matcher that will check that tested item and specified value are equal * according to the {@link ComparisonPerformers#REFLECTIVE_EQUALS} performer. * * @see #equalTo(Object, ComparisonPerformer) * @see #deeplyEqualTo(Object) * @see ComparisonMatcher * @see ComparisonPerformers */ public static <T> Matcher<T> reflectivelyEqualTo(T item) { return equalTo(item, ComparisonPerformers.REFLECTIVE_EQUALS); } /** * Create a matcher that will check that tested item and specified value are either both consistently matched, * or both consistently not matched by the specified matcher. * * @see #nullConsistentWith(Object) * @see ConsistencyMatcher */ public static <T> Matcher<T> consistentWith(T value, Matcher<? super T> matcher) { return new ConsistencyMatcher<T>(value, matcher); } /** * <p>Create a matcher that will check that tested item and specified value are either both consistently <b>nulls</b>, * or both consistently <b>not-nulls</b>. * * <p>Equal to {@link #consistentWith(Object, Matcher)} with {@link Matchers#nullValue()} as delegate. * * @see ConsistencyMatcher */ public static Matcher<Object> nullConsistentWith(Object value) { return consistentWith(value, Matchers.nullValue()); } /** * Create a matcher that will check that string representation of <b>any</b> object * matches specified regexp pattern. * * @throws NullPointerException if specified string is <code>null</code> * * @see #matches(Pattern) * @see RegexpMatcher */ public static Matcher<Object> matches(String pattern) { return RegexpMatcher.create(pattern); } /** * Create a matcher that will check that string representation of <b>any</b> object * matches specified pattern. * * @throws NullPointerException if specified pattern is <code>null</code> * * @see #matches(String) * @see RegexpMatcher */ public static Matcher<Object> matches(Pattern pattern) { return RegexpMatcher.create(pattern); } /** * Create a matcher that will check that an exception is an instance of the specified type. * And will set asserted throwable as cause of the result. * * @see #notExpected() * @see ThrowableMatcher */ public static Matcher<Throwable> throwableOfType(Class<? extends Throwable> type) { return ThrowableMatcher.throwableOfType(type); } /** * Create a matcher that will check that an exception is <code>null</code>. * And will set asserted throwable as cause of the result. * * @see #throwableOfType(Class) * @see ThrowableMatcher */ public static Matcher<Throwable> notExpected() { return ThrowableMatcher.notExpected(); } /** * <p>Create a matcher that will check that a collection contains the specified item. * Specified predicate is used to check elements equality. * * <p><b>Note:</b> matcher will throw an NPE if matched against a <code>null</code> value! * * @throws NullPointerException if specified predicate is <code>null</code> */ public static <T> Matcher<Collection<? extends T>> hasItem(T item, BiPredicate<T, T> matcher) { Objects.requireNonNull(matcher, "Predicate cannot be null!"); return new FunctionalMatcher<Collection<? extends T>>( Collection.class, c -> UberCollections.contains(c, item, matcher), d -> d.appendText("has item ").appendValue(item).appendText(" with a predicate")); } /** * Equal to {@link #hasAnyItem(Collection, BiPredicate)} with {@link Objects#deepEquals(Object, Object)} * used as a predicate. * * <p><b>Note:</b> matcher will throw an NPE if matched against a <code>null</code> value! * * @throws NullPointerException if specified collection is <code>null</code> * @throws IllegalArgumentException if specified collection is <code>empty</code> */ public static <T> Matcher<Collection<? extends T>> hasAnyItem(Collection<T> items) { return hasAnyItem(items, Objects::deepEquals); } /** * <p>Create a matcher that will check that a collection contains any one of the specified item. * Specified predicate is used to check elements equality. * * <p><b>Note:</b> matcher will throw an NPE if matched against a <code>null</code> value! * * @throws NullPointerException if specified collection or specified predicate is <code>null</code> * @throws IllegalArgumentException if specified collection is <code>empty</code> * * @see #hasAnyItem(Collection) */ public static <T> Matcher<Collection<? extends T>> hasAnyItem(Collection<T> items, BiPredicate<T, T> matcher) { Objects.requireNonNull(items, "Items collection cannot be null!"); Objects.requireNonNull(matcher, "Predicate cannot be null!"); Preconditions.checkArgument(!items.isEmpty(), "Items cannot be empty!"); return new FunctionalMatcher<Collection<? extends T>>( Collection.class, c -> UberCollections.containsAny(c, items, matcher), d -> d.appendText("has any one of ").appendValue(items).appendText(" with a predicate")); } /** * Create a matcher that will check that an item is contained in the specified collection. * Specified predicate is used to check elements equality. * * @throws NullPointerException if specified collection or predicate is <code>null</code> */ public static <T> Matcher<T> isIn(Collection<? extends T> col, BiPredicate<T, T> matcher) { Objects.requireNonNull(col, "Collection cannot be null!"); Objects.requireNonNull(matcher, "Predicate cannot be null!"); return new FunctionalMatcher<T>( Object.class, t -> UberCollections.contains(col, t, matcher), d -> d.appendText("one of ").appendValue(col).appendText(" with a predicate")); } /** * Create a matcher that will apply specified function to the received value and then delegate result * to the specified matcher delegate. * * @throws NullPointerException if specified matcher or function is <code>null</code> */ public static <T, V> Matcher<V> convert(Matcher<T> m, Function<V, T> f) { Objects.requireNonNull(m, "Delegate matcher cannot be null!"); Objects.requireNonNull(f, "Converting function cannot be null!"); return new FunctionalMatcher<V>( Object.class, v -> m.matches(f.apply(v)), d -> m.describeTo(d)); } }
mit
Mariusrik/schoolprojects
Ruby on rails eksamen/db/migrate/20170520135456_create_join_table_book_category.rb
223
class CreateJoinTableBookCategory < ActiveRecord::Migration[5.1] def change create_join_table :books, :categories do |t| t.index [:book_id, :category_id] t.index [:category_id, :book_id] end end end
mit
convalise/triple-triad
src/UnityTripleTriad/Assets/Project/Scripts/Utils/ExtensionUtils.cs
3124
public static class ExtensionUtils { #region BYTE_TO_STRING /// <summary> /// Converts a byte array to its hex string counterpart. /// </summary> public static string ToHexString(this byte[] byteArray) { return System.BitConverter.ToString(byteArray).Replace("-", string.Empty); } /// <summary> /// Converts a byte array to its hex string counterpart. /// </summary> public static string ToHexString(this byte[] byteArray, int startIndex, int length) { return System.BitConverter.ToString(byteArray, startIndex, length).Replace("-", string.Empty); } /// <summary> /// Reads a UTF8 formatted string from a byte array. /// </summary> public static string ToUTF8String(this byte[] byteArray) { return System.Text.Encoding.UTF8.GetString(byteArray).Trim('\0'); } /// <summary> /// Reads a UTF8 formatted string from a byte array. /// </summary> public static string ToUTF8String(this byte[] byteArray, int index, int count) { return System.Text.Encoding.UTF8.GetString(byteArray, index, count).Trim('\0'); } #endregion #region DECIMAL_TO_HEXA_STRING /// <summary> /// Converts the decimal number to a hex string. /// </summary> public static string ToHexString(this byte @decimal, bool pad = true) { string hexString = @decimal.ToString("X"); return pad ? ZeroPad(hexString) : hexString; } /// <summary> /// Converts the decimal number to a hex string. /// </summary> public static string ToHexString(this short @decimal, bool pad = true) { string hexString = @decimal.ToString("X"); return pad ? ZeroPad(hexString) : hexString; } /// <summary> /// Converts the decimal number to a hex string. /// </summary> public static string ToHexString(this int @decimal, bool pad = true) { string hexString = @decimal.ToString("X"); return pad ? ZeroPad(hexString) : hexString; } /// <summary> /// Converts the decimal number to a hex string. /// </summary> public static string ToHexString(this long @decimal, bool pad = true) { string hexString = @decimal.ToString("X"); return pad ? ZeroPad(hexString) : hexString; } /// <summary> /// Zero-pad the hex string if it has an odd number of chars. /// </summary> private static string ZeroPad(string hexString) { return ((hexString.Length % 2) != 0) ? ("0" + hexString) : hexString; } #endregion #region HEXA_STRING_TO_DECIMAL /// <summary> /// Converts a hex string to a base 8 decimal. /// </summary> public static byte ToBase8(this string hexString) { return System.Convert.ToByte(hexString, 16); } /// <summary> /// Converts a hex string to a base 16 decimal. /// </summary> public static short ToBase16(this string hexString) { return System.Convert.ToInt16(hexString, 16); } /// <summary> /// Converts a hex string to a base 32 decimal. /// </summary> public static int ToBase32(this string hexString) { return System.Convert.ToInt32(hexString, 16); } /// <summary> /// Converts a hex string to a base 64 decimal. /// </summary> public static long ToBase64(this string hexString) { return System.Convert.ToInt64(hexString, 16); } #endregion }
mit
lordmilko/gemodelsim
php/require/_getJourneyFromMapLocations.php
2677
<?php function getStartEndLocation($index, $row, $previousRow, $journeyIndex, $startEndLocation, $numRows, $postStartLocation, $postEndLocation, $matchIdentifiedCallback) { //If the JourneyID that has been stored for the previous row is different from the JourneyID in the current row, the Journey from the previous row must have ended. In which case the searching algorithm can be finalized for this record and the start and end locations can be compared against the values sent in POST if($journeyIndex != $row["JourneyID"]) { if($index != 0) //If index is 0 there won't be a previous route, so do not attempt to finalize anything { checkAddNewMapLocation($previousRow, $startEndLocation, $postStartLocation, $postEndLocation, $matchIdentifiedCallback); } $startLocation = useNameOrCoordinates($row); $startEndLocation = $startLocation; } //On the last row there won't be any further rows to check against, that would otherwise cause the function to compare the start and end locations of the final row's Journey against those that werent sent in POST. Therefore, if it is the final row, also do a check against the POST locations if($index == $numRows - 1) checkAddNewMapLocation($row, $startEndLocation, $postStartLocation, $postEndLocation, $matchIdentifiedCallback); return $startEndLocation; } //Check whether the start and end locations sent in POST match the start and end locations of a Journey function checkAddNewMapLocation($row, $startLocation, $postStartLocation, $postEndLocation, $matchIdentifiedCallback) { $endLocation = useNameOrCoordinates($row); //If a match is found, raise a flag saying the route designated by the POST start and end locations already exists in the database if(checkJourneyAgainstPOST($startLocation, $endLocation, $postStartLocation, $postEndLocation) == true) { $matchIdentifiedCallback($row); } } //Determine whether to use the Name column or Coordinates column value. Always use the Name column unless the value is null function useNameOrCoordinates($row) { $location; if($row["Name"] == null) $location = $row["Coordinates"]; else $location = $row["Name"]; return $location; } function checkJourneyAgainstPOST($startLocation, $endLocation, $postStartLocation, $postEndLocation) { $locationsMatch = false; if($startLocation == $postStartLocation && $endLocation == $postEndLocation) $locationsMatch = true; return $locationsMatch; } function checkUpdateCurrentJourney($currentJourney, $nextJourney) { if($currentJourney != $nextJourney) $currentJourney = $nextJourney; return $currentJourney; } ?>
mit
ArveH/ACopy
src/Common/ADatabase/Extensions/StringCustomExtensions.cs
6150
using System; using ADatabase.Exceptions; namespace ADatabase.Extensions { public static class StringCustomExtensions { public static TEnumType ConverToEnum<TEnumType>(this string enumValue) { return (TEnumType)Enum.Parse(typeof(TEnumType), enumValue); } public static ColumnTypeName ColumnTypeName(this string str, int length=0) { switch (str) { case "bigint": return ADatabase.ColumnTypeName.Int64; case "binary": return ADatabase.ColumnTypeName.Raw; case "binary_float": case "binaryfloat": return ADatabase.ColumnTypeName.BinaryFloat; case "binary_double": case "binarydouble": return ADatabase.ColumnTypeName.BinaryDouble; case "bit": return ADatabase.ColumnTypeName.Bool; case "blob": return ADatabase.ColumnTypeName.Blob; case "bool": return ADatabase.ColumnTypeName.Bool; case "char": return ADatabase.ColumnTypeName.Char; case "clob": return ADatabase.ColumnTypeName.LongText; case "date": return ADatabase.ColumnTypeName.Date; case "datetime": return ADatabase.ColumnTypeName.DateTime; case "datetime2": return ADatabase.ColumnTypeName.DateTime2; case "dec": return ADatabase.ColumnTypeName.Dec; case "float": return ADatabase.ColumnTypeName.Float; case "guid": return ADatabase.ColumnTypeName.Guid; case "image": return ADatabase.ColumnTypeName.OldBlob; case "int": return ADatabase.ColumnTypeName.Int; case "int16": return ADatabase.ColumnTypeName.Int16; case "int64": return ADatabase.ColumnTypeName.Int64; case "int8": return ADatabase.ColumnTypeName.Int8; case "longtext": return ADatabase.ColumnTypeName.LongText; case "long": return ADatabase.ColumnTypeName.OldText; case "longraw": return ADatabase.ColumnTypeName.OldBlob; case "money": return ADatabase.ColumnTypeName.Money; case "nchar": return ADatabase.ColumnTypeName.NChar; case "noldtext": case "ntext": return ADatabase.ColumnTypeName.NOldText; case "nclob": case "nlongtext": return ADatabase.ColumnTypeName.NLongText; case "number": return ADatabase.ColumnTypeName.Dec; case "nvarchar": case "nvarchar2": return ADatabase.ColumnTypeName.NVarchar; case "oldblob": return ADatabase.ColumnTypeName.OldBlob; case "oldtext": return ADatabase.ColumnTypeName.OldText; case "raw": return ADatabase.ColumnTypeName.Raw; case "real": return ADatabase.ColumnTypeName.BinaryFloat; case "smalldatetime": return ADatabase.ColumnTypeName.SmallDateTime; case "smallint": return ADatabase.ColumnTypeName.Int16; case "smallmoney": return ADatabase.ColumnTypeName.SmallMoney; case "text": return ADatabase.ColumnTypeName.OldText; case "time": return ADatabase.ColumnTypeName.Time; case "timestamp": return ADatabase.ColumnTypeName.Timestamp; case "tinyint": return ADatabase.ColumnTypeName.Int8; case "uniqueidentity": return ADatabase.ColumnTypeName.Guid; case "varbinary": return length <= 0 ? ADatabase.ColumnTypeName.Blob : ADatabase.ColumnTypeName.VarRaw; case "varchar": case "varchar2": return ADatabase.ColumnTypeName.Varchar; case "varraw": return ADatabase.ColumnTypeName.VarRaw; } throw new ADatabaseException($"Copy program doesn't have a representation for ACopy column type {str}"); } public static string AddParameters(this string str) { switch (str) { case "binary": return "binary(@Length)"; case "datetime2": return "datetime2(@Scale)"; case "CHAR": case "char": case "NCHAR": case "nchar": case "NVARCHAR2": case "NVARCHAR": case "nvarchar": case "RAW": case "VARCHAR2": case "VARCHAR": case "varchar": case "varbinary": return str.ToLower() + "(@Length)"; case "FLOAT": case "float": return "float(@Prec)"; case "LONG RAW": return "longraw(@Length)"; case "NUMBER": case "NUMERIC": case "DECIMAL": return "number(@Prec, @Scale)"; case "dec": return "dec(@Prec, @Scale)"; case "decimal": return "decimal(@Prec, @Scale)"; default: return str.ToLower(); } } } }
mit
ragmar/bvmjm
models/faq.php
61
<?php class Faq extends AppModel { var $name = 'Faq'; }
mit
Dratejinn/telegrambot
src/API/API.php
5156
<?php declare(strict_types = 1); namespace Telegram\API; use Psr\Log; final class API { const URL = 'https://api.telegram.org/bot%s/'; /** * @var \Monolog\Logger */ private static $_Logger = NULL; /** * @param string $method * @param \Telegram\API\Bot $bot * @param \Telegram\API\Base\Abstracts\ABaseObject $payload * @return \stdClass */ public static function CallMethod(string $method, Bot $bot, Base\Abstracts\ABaseObject $payload) { $url = self::_GetURL($method, $bot->getToken()); return self::SendRequest($url, $payload); } /** * @param string $url * @param \Telegram\API\Base\Abstracts\ABaseObject $payload * @return \stdClass */ public static function SendRequest(string $url, Base\Abstracts\ABaseObject $payload) { /* Create the headers */ $payloadType = $payload->getPayloadType(); $payload = $payload->getPayload(); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, TRUE); if (ConfigManager::HasConfig('SSL-VerifyPeer')) { $verifyPeer = ConfigManager::GetConfig('SSL-VerifyPeer'); } else { $verifyPeer = TRUE; } curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $verifyPeer); if (ConfigManager::HasConfig('CA-certfile')) { curl_setopt($curl, CURLOPT_CAINFO, ConfigManager::GetConfig('CA-certfile')); } switch ($payloadType) { case 'JSON': $contentLength = strlen($payload); curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'Content-type: application/json', 'Content-Length: ' . $contentLength ]); break; case 'MultiPartFormData': curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'Content-type: multipart/form-data' ]); break; } curl_setopt($curl, CURLOPT_POSTFIELDS, $payload); // output the response curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); $content = curl_exec($curl); $error = curl_error($curl); curl_close($curl); if (!empty($error)) { if (self::HasLogger()) { self::$_Logger->error('Curl error: ' . $error); } return NULL; } if (!is_string($content)) { if (self::HasLogger()) { self::$_Logger->error('Return value of curl handle is not of type string!'); } return NULL; } /* Decode json string */ $res = Base\Abstracts\ABaseObject::DecodeJSON($content, FALSE); if ($res === NULL) { $res = new \stdClass; $res->ok = FALSE; if (self::HasLogger()) { $err = json_last_error(); switch ($err) { case JSON_ERROR_NONE: break; case JSON_ERROR_DEPTH: self::$_Logger->alert('JSON decode error: Maximum stack depth exceeded'); break; case JSON_ERROR_STATE_MISMATCH: self::$_Logger->alert('JSON decode error: Underflow or the modes mismatch'); break; case JSON_ERROR_CTRL_CHAR: self::$_Logger->alert('JSON decode error: Unexpected control character found'); break; case JSON_ERROR_SYNTAX: self::$_Logger->alert('JSON decode error: Syntax error, malformed JSON'); break; case JSON_ERROR_UTF8: self::$_Logger->alert('JSON decode error: Malformed UTF-8 characters, possibly incorrectly encoded'); break; default: self::$_Logger->alert('JSON decode error: Unknown error (' . $err . ')'); break; } } } return $res; } /** * @param string $method * @param string $token * @return string */ private static function _GetURL(string $method, string $token) : string { $botUrl = sprintf(self::URL, $token); return $botUrl . $method; } /** * @param \Psr\Log\LoggerInterface $logger */ public static function SetLogger(Log\LoggerInterface $logger) { self::$_Logger = $logger; } /** * @return bool */ public static function HasLogger() : bool { return self::$_Logger !== NULL; } /** * Generates a V3 UUID * * @return string */ public static function GenerateUUID() : string { $data = openssl_random_pseudo_bytes(16); $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100 $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10 return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); } }
mit
InfinityRaider/InfinityLib
src/main/java/com/infinityraider/infinitylib/utility/inventory/ItemHandlerInventory.java
2544
package com.infinityraider.infinitylib.utility.inventory; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import javax.annotation.Nonnull; /** * Simple class to wrap an IInventory as an IItemHandler while maintaining IInventory functionality */ @SuppressWarnings("unused") public class ItemHandlerInventory implements IInventoryItemHandler { private final IInventory inventory; public ItemHandlerInventory(IInventory inventory) { this.inventory = inventory; } public IInventory getInventory() { return inventory; } @Override public int getSizeInventory() { return this.getInventory().getSizeInventory(); } @Override @Nonnull public ItemStack getStackInInvSlot(int index) { return this.getInventory().getStackInSlot(index); } @Override public int getSlotLimit(int slot) { return this.getInventory().getInventoryStackLimit(); } @Override public boolean isItemValid(int slot, @Nonnull ItemStack stack) { return this.getInventory().isItemValidForSlot(slot, stack); } @Override @Nonnull public ItemStack decrStackSize(int index, int count) { return this.getInventory().decrStackSize(index, count); } @Override @Nonnull public ItemStack removeStackFromSlot(int index) { return this.getInventory().removeStackFromSlot(index); } @Override public void setInventorySlotContents(int index, @Nonnull ItemStack stack) { this.getInventory().setInventorySlotContents(index, stack); } @Override public int getInventoryStackLimit() { return this.getInventory().getInventoryStackLimit(); } @Override public void markDirty() { this.getInventory().markDirty(); } @Override public boolean isUsableByPlayer(@Nonnull PlayerEntity player) { return this.getInventory().isUsableByPlayer(player); } @Override public void openInventory(@Nonnull PlayerEntity player) { this.getInventory().openInventory(player); } @Override public void closeInventory(@Nonnull PlayerEntity player) { this.getInventory().closeInventory(player); } @Override public boolean isItemValidForSlot(int index, @Nonnull ItemStack stack) { return this.getInventory().isItemValidForSlot(index, stack); } @Override public void clear() { this.getInventory().clear(); } }
mit
bvilhjal/mixmogam
snpsdata.py
125648
""" This python library aims to do two things. 1. Offer general wrapper classes around SNPs datasets. 2. Offer basic functions which can aid analysis of the SNPs. Author: Bjarni J. Vilhjalmsson Email: [email protected] """ import sys, warnings from itertools import * import bisect import h5py import os import random import kinship try: import scipy as sp sp.seterr(divide='raise') except Exception, err_str: print 'scipy is missing:', err_str IUPAC_alphabet = ['A', 'C', 'G', 'T', '-', 'Y', 'R', 'W', 'S', 'K', 'M', 'D', 'H', 'V', 'B', 'X', 'N'] """ Marker type suggestions: 'Unknown' 'SNP' 'Indel' 'Other' ... etc. """ def get_haplotypes(snps, num_accessions, count_haplotypes=False): curr_haplotypes = map(tuple, sp.transpose(sp.array(snps).tolist())) hap_set = list(set(curr_haplotypes)) hap_hash = {} for j, h in enumerate(hap_set): hap_hash[h] = j new_haplotypes = sp.zeros(num_accessions, dtype='int8') for j, h in enumerate(curr_haplotypes): new_haplotypes[j] = hap_hash[h] if count_haplotypes: hap_counts = [curr_haplotypes.count(hap) for hap in hap_set] return hap_set, hap_counts, new_haplotypes else: return new_haplotypes class _SnpsData_(object): """ An abstract superclass. """ def __init__(self, snps, positions, baseScale=None, accessions=None, arrayIds=None, chromosome=None, alignment_positions=None, id=None, marker_types=None, alphabet=None, associated_positions=None): self.snps = snps # list[position_index][accession_index] self.positions = positions # list[position_index] if accessions: self.accessions = accessions # list[accession_index] # self._convert_to_tg_ecotypes_() if arrayIds: self.arrayIds = arrayIds # list[accession_index] self.chromosome = chromosome self.alignment_positions = alignment_positions self.id = id self.marker_types = marker_types # Where do these markers come frome, what type are they? Useful for later analysis. self.alphabet = None self.missingVal = None self.associated_positions = associated_positions def merge_data(self, sd, union_accessions=True, allow_multiple_markers=True, error_threshold=0.2): """ Merges data, allowing multiple markers at a position. (E.g. deletions and SNPs.) However it merges markers which overlap to a significant degree. """ if union_accessions: new_accessions = list(set(self.accessions).union(set(sd.accessions))) else: new_accessions = self.accessions acc_map = [] for acc in new_accessions: try: ai1 = self.accessions.index(acc) except: ai1 = -1 try: ai2 = sd.accessions.index(acc) except: ai2 = -1 acc_map.append((ai1, ai2)) # print acc_map # pdb.set_trace() index_dict = {} j = 0 last_pos = sd.positions[j] for i, pos in enumerate(self.positions): curr_pos = last_pos while j < len(sd.positions) and curr_pos < pos: j += 1 if j < len(sd.positions): curr_pos = sd.positions[j] last_pos = curr_pos index_list = [] while j < len(sd.positions) and curr_pos == pos: index_list.append(j) j += 1 if j < len(sd.positions): curr_pos = sd.positions[j] if index_list: index_dict[i] = index_list indices_to_skip = set() new_snps = [] merge_count = 0 for i, snp1 in enumerate(self.snps): new_snp = [] if i in index_dict: index_list = index_dict[i] for j in index_list: error_count = 0 t_count = 0 snp2 = sd.snps[j] for (ai1, ai2) in acc_map: if ai1 != -1 and ai2 != -1: if snp1[ai1] != snp2[ai2] and snp1[ai1] != self.missingVal\ and snp2[ai2] != self.missingVal: error_count += 1 t_count += 1 if t_count > 0 and error_count / float(t_count) < error_threshold: # print "Merge error is %f"%(error_count/float(t_count)) for (ai1, ai2) in acc_map: if ai1 != -1 and ai2 != -1: if snp1[ai1] != self.missingVal: new_snp.append(snp1[ai1]) else: new_snp.append(snp2[ai2]) elif ai1 == -1: new_snp.append(snp2[ai2]) else: new_snp.append(snp1[ai1]) merge_count += 1 indices_to_skip.add(j) elif t_count > 0: print "Not merging since error is %f." % (error_count / float(t_count)) for (ai1, ai2) in acc_map: if ai1 != -1: new_snp.append(snp1[ai1]) else: new_snp.append(self.missingVal) else: for (ai1, ai2) in acc_map: if ai1 != -1: new_snp.append(snp1[ai1]) else: new_snp.append(self.missingVal) # print snp1,new_snp if new_snp == []: raise Exception new_snps.append(new_snp) new_positions = self.positions for j in range(len(sd.snps)): if not j in indices_to_skip: snp2 = sd.snps[j] new_snp = [] for (ai1, ai2) in acc_map: if ai2 != -1: new_snp.append(snp2[ai2]) else: new_snp.append(self.missingVal) if new_snp == []: raise Exception new_snps.append(new_snp) new_positions.append(sd.positions[j]) pos_snp_list = zip(new_positions, new_snps) pos_snp_list.sort() r = map(list, zip(*pos_snp_list)) self.positions = r[0] self.snps = r[1] self.accessions = new_accessions if len(self.snps) != len(self.positions): raise Exception print "Merged %d SNPs!" % (merge_count) print "Resulting in %d SNPs in total" % len(self.snps) def extend(self, snpsd, union_accessions=True): """ Extends the marker data with another snpsd, but assumes they are non overlapping and spatially ordered. """ if union_accessions: new_accessions = list(set(self.accessions).union(set(snpsd.accessions))) else: raise NotImplementedError acc_map = [] for acc in new_accessions: try: ai1 = self.accessions.index(acc) except: ai1 = -1 try: ai2 = snpsd.accessions.index(acc) except: ai2 = -1 acc_map.append((ai1, ai2)) new_snps = [] new_positions = [] for i, snp in enumerate(self.snps): new_snp = [] for (ai1, ai2) in acc_map: if ai1 == -1: new_snp.append(self.missingVal) else: new_snp.append(snp[ai1]) new_positions.append(self.positions[i]) for i, snp in enumerate(snpsd.snps): new_snp = [] for (ai1, ai2) in acc_map: if ai2 == -1: new_snp.append(self.missingVal) else: new_snp.append(snp[ai2]) new_positions.append(snpsd.positions[i]) self.snps = new_snps self.positions = new_positions self.accessions = new_accessions def sample_snps(self, random_fraction, seed=None): """ Discards SNPs, leaving a random fraction of them untouched. """ if seed: sp.random.seed(seed) rs = sp.random.random(len(self.snps)) new_positions = [] new_snps = [] for i in range(len(self.snps)): if rs[i] < random_fraction: new_positions.append(self.positions[i]) new_snps.append(self.snps[i]) self.positions, self.snps = new_positions, new_snps def scalePositions(self, baseScale): for i in range(0, len(self.positions)): self.positions[i] = int(self.positions[i] * baseScale) self.baseScale = baseScale def addSnp(self, snp): self.snps.append(snp) def addPos(self, position): self.positions.append(position) def removeAccessions(self, accessions, arrayIds=None): """ Removes accessions from the data. """ accPair = set() for i in range(0, len(accessions)): if arrayIds: key = (accessions[i], arrayIds[i]) else: key = accessions[i] accPair.add(key) newAccessions = [] newArrayIds = [] for i in range(0, len(self.snps)): snp = self.snps[i] newSnp = [] for j in range(0, len(self.accessions)): if arrayIds: key = (self.accessions[j], self.arrayIds[j]) else: key = self.accessions[j] if not key in accPair: newSnp.append(snp[j]) if i == 0: newAccessions.append(self.accessions[j]) if arrayIds: newArrayIds.append(self.arrayIds[j]) self.snps[i] = newSnp self.accessions = newAccessions if arrayIds: self.arrayIds = newArrayIds def removeAccessionIndices(self, indicesToKeep): """ Removes accessions from the data. """ newAccessions = [] newArrayIds = [] for i in indicesToKeep: newAccessions.append(self.accessions[i]) if self.arrayIds: newArrayIds.append(self.arrayIds[i]) for i in range(len(self.snps)): snp = self.snps[i] newSnp = [] for j in indicesToKeep: newSnp.append(snp[j]) self.snps[i] = newSnp self.accessions = newAccessions if self.arrayIds: # print "removeAccessionIndices: has array IDs: self.arrayIds =",self.arrayIds self.arrayIds = newArrayIds # print "len(self.arrayIds):",len(self.arrayIds) # pdb.set_trace() # print "len(self.accessions):",len(self.accessions) def filterMonoMorphicSnps(self): """ 05/12/08 yh. add no_of_monomorphic_snps_removed Removes SNPs from the data which are monomorphic. """ newPositions = [] newSnps = [] for i in range(0, len(self.positions)): count = 0 for nt in self.alphabet: if nt in self.snps[i]: count += 1 if count > 1: newSnps.append(self.snps[i]) newPositions.append(self.positions[i]) numRemoved = len(self.positions) - len(newPositions) self.no_of_monomorphic_snps_removed = numRemoved self.snps = newSnps self.positions = newPositions return numRemoved def onlyBinarySnps(self): """ Removes all but binary SNPs. (I.e. monomorphic, tertiary and quaternary alleles SNPs are removed.) """ newPositions = [] newSnps = [] for i in range(0, len(self.positions)): count = 0 for nt in self.alphabet: if nt in self.snps[i]: count += 1 if count == 2: newSnps.append(self.snps[i]) newPositions.append(self.positions[i]) numRemoved = len(self.positions) - len(newPositions) self.no_of_nonbinary_snps_removed = numRemoved self.snps = newSnps self.positions = newPositions print "Removed %d non-binary SNPs, leaving %d SNPs in total." % (numRemoved, len(self.snps)) return numRemoved def orderAccessions(self, accessionMapping): newAccessions = [None for i in range(0, len(accessionMapping))] for (i, j) in accessionMapping: newAccessions[j] = self.accessions[i] newSnps = [] for pos in self.positions: newSnps.append([self.missingVal for i in range(0, len(accessionMapping))]) for (i, j) in accessionMapping: for posIndex in range(0, len(self.positions)): newSnps[posIndex][j] = self.snps[posIndex][i] self.accessions = newAccessions self.snps = newSnps if self.arrayIds: newArrayIds = [None for i in range(0, len(self.arrayIds))] for (i, j) in accessionMapping: newArrayIds[j] = self.arrayIds[i] self.arrayIds = newArrayIds def filterRegion(self, startPos, endPos): """ Filter all SNPs but those in region. """ i = 0 while i < len(self.snps) and self.positions[i] < startPos: i += 1 newSnps = [] newPositions = [] while i < len(self.snps) and self.positions[i] < endPos: newSnps.append(self.snps[i]) newPositions.append(self.positions[i]) i += 1 self.snps = newSnps self.positions = newPositions def get_region_snpsd(self, start_pos, end_pos): """ Constructs and returns a new object based on the prev. using SNPs only in the given region. """ import copy snpsd = copy.deepcopy(self) # Clone i = 0 while i < len(self.snps) and self.positions[i] < start_pos: i += 1 new_snps = [] new_positions = [] while i < len(self.snps) and self.positions[i] < end_pos: new_snps.append(self.snps[i]) new_positions.append(self.positions[i]) i += 1 snpsd.positions = new_positions snpsd.snps = new_snps return snpsd def get_snp_phen_pair(self, snp_index, phen_data, phen_index=None, missingVal=None): """ returns a pair of snp and phenotype values, removing NA's """ if not missingVal: missingVal = self.missingVal snp = self.snps[snp_index] phen_vals = phen_data.getPhenVals(phen_index, noNAs=False) # print phen_data.accessions # print self.accessions # print len(phen_vals),len(phen_data.accessions) acc_set = list(set(self.accessions).intersection(set(phen_data.accessions))) acc_set.sort() # Not really necessary... new_snp = [] new_phen_vals = [] for acc in acc_set: si = self.accessions.index(acc) pi = phen_data.accessions.index(acc) if snp[si] != missingVal and phen_vals[pi] != missingVal: new_snp.append(snp[si]) new_phen_vals.append(phen_vals[pi]) return (new_snp, new_phen_vals) def get_mafs(self): """ Returns MAFs and MARFs Assumes that this is a binary allele. """ mafs = [] marfs = [] for snp in self.snps: missing_count = list(snp).count(self.missingVal) num_nts = len(snp) - missing_count nts = set(snp) if missing_count: nts.remove(self.missingVal) c = list(snp).count(nts.pop()) / float(num_nts) if c > 0.5: c = 1.0 - c marfs.append(c) mafs.append(int(c * num_nts)) return {"mafs":mafs, "marfs":marfs} def remove_snps(self, remove_indices): """ Filters all SNPs in the indices list. """ remove_indices.sort(reverse=True) for i in remove_indices: del self.snps[i] del self.positions[i] if self.alignment_positions: del self.alignment_positions[i] def filter_snp_indices(self, indices): """ Filters all SNPs but those in the indices list. """ new_snps = [] new_positions = [] new_alignm_positions = [] for i in indices: new_snps.append(self.snps[i]) new_positions.append(self.positions[i]) self.snps = new_snps self.positions = new_positions if self.alignment_positions: new_alignm_positions = [] for i in indices: new_alignm_positions.append(self.alignment_positions[i]) self.alignment_positions = new_alignm_positions def filter_accessions_by_NAs(self, maxMissing): """ Removes the accessions in the snpsd if it has NA-rates greater than maxMissing. """ sys.stderr.write("Calculating NA rate ...") missingCounts = self.accessionsMissingCounts() indices_to_keep = [] num_snps = float(len(self.snps)) for i, mc in enumerate(missingCounts): if (mc / num_snps) <= maxMissing: indices_to_keep.append(i) self.removeAccessionIndices(indices_to_keep) def filter_na_snps(self, max_na_rate=0.0): new_snps = [] new_positions = [] num_snps = len(self.snps) e_num = float(len(self.accessions)) for i, snp in enumerate(self.snps): if snp.count(self.missingVal) / e_num <= max_na_rate: new_snps.append(snp) new_positions.append(self.positions[i]) self.snps = new_snps self.positions = new_positions print "Removed %d SNPs, leaving %d in total." % (num_snps - len(self.snps), len(self.snps)) def accessionsMissingCounts(self): """ Returns a list of accessions and their missing value rates. """ missingCounts = [0] * len(self.accessions) for i in range(0, len(self.positions)): for j in range(0, len(self.accessions)): if self.snps[i][j] == self.missingVal: missingCounts[j] += 1 return missingCounts def __str__(self): st = "Number of accessions: " + str(len(self.accessions)) + "\n" st += "Number of SNPs: " + str(len(self.snps)) + "\n" uniqueAccessions = list(set(self.accessions)) if len(uniqueAccessions) < len(self.accessions): st += "Not all accessions are unique. \n" + "Number of unique accessions: " + str(len(uniqueAccessions)) + "\n" for acc in uniqueAccessions: count = self.accessions.count(acc) if count > 1: st += acc + " has " + str(count) + " occurrences.\n\n" return st def countMissingSnps(self): """ Returns a list of accessions and their missing value rates. """ missingCounts = [0.0 for acc in self.accessions] totalCounts = [0.0 for acc in self.accessions] for i in range(0, len(self.positions)): for j in range(0, len(self.accessions)): totalCounts[j] += 1 if self.snps[i][j] == self.missingVal: missingCounts[j] += 1 return [missingCounts[i] / totalCounts[i] for i in range(len(self.accessions))], missingCounts def print_ecotype_info_to_file(self, filename): """ Prints info on the accessions/ecotype IDs to a file. """ import phenotypeData as pd eid = pd.get_ecotype_id_info_dict() f = open(filename, 'w') f.write((", ".join(["Ecotype_id", "Native_name", "Stock_parent", "latitude", "longitude", "country"])) + "\n") for e in self.accessions: l = [e] + list(eid[int(e)]) l = map(str, l) f.write((", ".join(l)) + "\n") f.close() class RawDecoder(dict): def __missing__(self, key): return 'NA' def __init__(self, initdict={}): for letter in ['A', 'C', 'G', 'T']: self[letter] = letter for letter in initdict: self[letter] = initdict[letter] class RawSnpsData(_SnpsData_): """ 05/11/2008 yh. give default values to all initial arguments so that it could be called without any arguments. Similar to the SnpsData class, except it deals with bases (A,C,G,T), instead of allele numbers (0s and 1s). Alphabet: A,C,G,T, and NA """ # alphabet = ['A','C','G','T'] # alphabet = ['A','C','G','T','-'] def __init__(self, snps=None, positions=None, baseScale=None, accessions=None, arrayIds=None, chromosome=None, callProbabilities=None, alignment_positions=None, id=None, marker_types=None, missing_val='NA'): self.snps = snps self.positions = positions self.accessions = accessions # if accessions: # self._convert_to_tg_ecotypes_() self.arrayIds = arrayIds self.callProbabilities = [] # list[position_index][accession_index] if callProbabilities: self.callProbabilities = callProbabilities self.alignment_positions = alignment_positions self.missingVal = missing_val self.alphabet = IUPAC_alphabet self.marker_types = marker_types # Where do these markers come frome, what type are they? Useful for later analysis. self.id = id self.chromosome = chromosome def writeToFile(self, filename, chromosome): """ Writes data to a file. 1 file for each chromosome. WARNING OLD, outdated! """ outStr = "" fieldStrings = ["Chromosome", "Positions"] for acc in self.accessions: fieldStrings.append(str(acc)) outStr += ", ".join(fieldStrings) + "\n" for i in range(0, len(self.positions)): outStr += str(chromosome) + ", " + str(self.positions[i]) + ", " + ", ".join(self.snps[i]) + "\n" f = open(filename, "w") f.write(outStr) f.close() # def impute_data_region(self, reference_snpsd, window_count=100, window_size=None, verbose=False, **kwargs): # """ # Impute any NA SNPs. # """ # import ImputeSNPs as imp # import tempfile, copy # if window_size: # start_pos = max(0, self.positions[0] - window_size) # end_pos = self.positions[-1] + window_size # snpsd = reference_snpsd.get_region_snpsd(start_pos, end_pos) # else: # snpsd = copy.deepcopy(reference_snpsd) # if (not window_count) and window_size: # i = 0 # while i < len(snpsd.positions) and snpsd.positions[i] < self.positions[0]: # i += 1 # suffix_count = i # i = 1 # while i >= len(snpsd.positions) and snpsd.positions[len(snpsd.positions) - i] > self.positions[-1]: # i += 1 # window_count = max(suffix_count + 1, i) # # snpsd.mergeDataUnion(self, priority=2, unionType=3, verbose=verbose) # snpsd.na_ambigious_calls() # snpsd.onlyBinarySnps() # print snpsd.snps # print snpsd.accessions # print len(snpsd.accessions), len(set(snpsd.accessions)) # tmpFile1 = tempfile.mkstemp() # os.close(tmpFile1[0]) # tmpFile2 = tempfile.mkstemp() # os.close(tmpFile2[0]) # # if verbose: # print "Preparing data in", tmpFile1[1] # imp.writeAsNputeFile(snpsd, tmpFile1[1]) # imp.checkNputeFile(tmpFile1[1]) # nputeCmd = "python " + imp.path_NPUTE + "NPUTE.py -m 0 -w " + str(window_count) + " -i " + str(tmpFile1[1]) + " -o " + str(tmpFile2[1]) # if verbose: # print "Imputing data..." # print nputeCmd # os.system(nputeCmd) # if verbose: # print "Imputation done!" # # snpsd = imp.readNputeFile(tmpFile2[1], snpsd.accessions, snpsd.positions) # self.mergeDataUnion(snpsd, priority=2) # os.remove(tmpFile1[1]) # os.remove(tmpFile2[1]) # # # def impute_data(self, verbose=True): # """ # Impute any NAs in the data. # """ # import ImputeSNPs as imp # import tempfile # tmpFile1 = tempfile.mkstemp() # os.close(tmpFile1[0]) # tmpFile2 = tempfile.mkstemp() # os.close(tmpFile2[0]) # # if verbose: # print "Preparing data in", tmpFile1[1] # imp.writeAsNputeFile(self, tmpFile1[1]) # imp.checkNputeFile(tmpFile1[1]) # nputeCmd = "python " + imp.path_NPUTE + "NPUTE.py -m 0 -w 30 -i " + str(tmpFile1[1]) + " -o " + str(tmpFile2[1]) # if verbose: # print "Imputing data..." # print nputeCmd # os.system(nputeCmd) # if verbose: # print "Imputation done!" # # pdb.set_trace() # snpsd = imp.readNputeFile(tmpFile2[1], self.accessions, self.positions) # self.snps = snpsd.snps # os.remove(tmpFile1[1]) # os.remove(tmpFile2[1]) def compareWith(self, snpsd, withArrayIds=0, verbose=True, heterozygous2NA=False): """ 05/10/2008 len(commonSnpsPos) could be zero This function performs QC on two datasets. Requires accessions to be defined. withArrayIds = 0 (no array IDs), =1 the object called from has array IDs, =2 both objects have array IDs """ basicAlphabet = ['-', 'A', 'C', 'G', 'T'] if verbose: print "Comparing datas" print "Number of snps:", len(self.snps), "and", len(snpsd.snps) # Find common accession indices accessionsIndices = [] accessionErrorRate = [] accessionCallRates = [[], []] accessionCounts = [] commonAccessions = [] arrayIds = [] for i in range(0, len(self.accessions)): acc = self.accessions[i] if snpsd.accessions.count(acc): j = snpsd.accessions.index(acc) accessionsIndices.append([i, j]) accessionErrorRate.append(0) accessionCounts.append(0) accessionCallRates[0].append(0) accessionCallRates[1].append(0) commonAccessions.append(acc) if withArrayIds > 0: if withArrayIds == 1: aId = self.arrayIds[i] elif withArrayIds == 2: aId = (self.arrayIds[i], snpsd.arrayIds[j]) arrayIds.append(aId) commonSnpsPos = [] snpErrorRate = [] snpCallRate = [[], []] goodSnpsCounts = [] totalCounts = 0 totalFails = 0 i = 0 j = 0 while i <= len(self.positions) and j <= len(snpsd.positions): if i < len(self.positions): pos1 = self.positions[i] if j < len(snpsd.positions): pos2 = snpsd.positions[j] if i < len(self.positions) and pos1 < pos2: i = i + 1 elif j < len(snpsd.positions) and pos2 < pos1: j = j + 1 elif i < len(self.positions) and j < len(snpsd.positions) and pos1 == pos2: commonSnpsPos.append(pos1) fails = 0 counts = 0 missing1 = 0 missing2 = 0 for k in range(0, len(accessionsIndices)): accIndices = accessionsIndices[k] snp1 = self.snps[i][accIndices[0]] snp2 = snpsd.snps[j][accIndices[1]] if heterozygous2NA: if snp1 in basicAlphabet and snp2 in basicAlphabet: accessionCounts[k] += 1 counts += 1 if snp1 != snp2: fails = fails + 1 accessionErrorRate[k] += 1 else: if snp1 == self.missingVal: accessionCallRates[0][k] += 1 missing1 += 1 if snp2 == self.missingVal: accessionCallRates[1][k] += 1 missing2 += 1 else: if snp1 != self.missingVal and snp2 != self.missingVal: accessionCounts[k] += 1 counts += 1 if snp1 != snp2: fails = fails + 1 accessionErrorRate[k] += 1 else: if snp1 == self.missingVal: accessionCallRates[0][k] += 1 missing1 += 1 if snp2 == self.missingVal: accessionCallRates[1][k] += 1 missing2 += 1 goodSnpsCounts.append(counts) error = 0 totalCounts += counts totalFails += fails if counts > 0: error = float(fails) / float(counts) snpErrorRate.append(error) snpCallRate[0].append(missing1 / float(len(accessionsIndices))) snpCallRate[1].append(missing2 / float(len(accessionsIndices))) i = i + 1 j = j + 1 else: # One pointer has reached and the end and the other surpassed it. break for i in range(0, len(accessionErrorRate)): if accessionCounts[i] > 0: accessionErrorRate[i] = accessionErrorRate[i] / float(accessionCounts[i]) no_of_common_snps_pos = len(commonSnpsPos) if no_of_common_snps_pos > 0: # 05/08/10 yh accessionCallRates[0][i] = accessionCallRates[0][i] / float(no_of_common_snps_pos) accessionCallRates[1][i] = accessionCallRates[1][i] / float(no_of_common_snps_pos) else: accessionCallRates[0][i] = 0 accessionCallRates[1][i] = 1 print "In all", len(snpErrorRate), "common snps found" print "In all", len(commonAccessions), "common accessions found" print "Common accessions IDs :", commonAccessions print "Common SNPs positions :", commonSnpsPos print "Accessions error rates", accessionErrorRate print "Average Accession SNP Error:", sum(accessionErrorRate) / float(len(accessionErrorRate)) print "SNP error rates", snpErrorRate print "Average Snp Error:", sum(snpErrorRate) / float(len(snpErrorRate)) naCounts1 = [0] * len(accessionsIndices) for i in range(0, len(self.positions)): for k in range(0, len(accessionsIndices)): accIndices = accessionsIndices[k] snp = self.snps[i][accIndices[0]] if snp == self.missingVal: naCounts1[k] += 1 naCounts2 = [0] * len(accessionsIndices) for i in range(0, len(snpsd.positions)): for k in range(0, len(accessionsIndices)): accIndices = accessionsIndices[k] snp = snpsd.snps[i][accIndices[1]] if snp == self.missingVal: naCounts2[k] += 1 return [commonSnpsPos, snpErrorRate, commonAccessions, accessionErrorRate, accessionCallRates, arrayIds, accessionCounts, snpCallRate, [naCounts1, naCounts2], [totalCounts, totalFails]] def convert_to_binary(self): """ An updated and version of the getSnpsData.. uses scipy. """ raise NotImplementedError def getSnpsData(self, missingVal= -1, reference_ecotype='6909', only_binary=True, verbose=True): """ Returns a SnpsData object correspoding to this RawSnpsData object. Note that some of the SnpsData attributes are a shallow copy of the RawSnpsData obj. Reference ecotype is set to be the 0 allele. """ decoder = {self.missingVal:missingVal} #Might cause errors somewhere???!!! coding_fun = sp.vectorize(lambda x: decoder[x], otypes=['int8']) if reference_ecotype in self.accessions: ref_i = self.accessions.index(reference_ecotype) else: ref_i = 0 import warnings warnings.warn("Given reference ecotype %s wasn't found, using %s as 0-reference." % \ (reference_ecotype, self.accessions[ref_i])) snps = [] positions = [] num_lines = len(self.accessions) for snp_i, (snp, pos) in enumerate(izip(self.snps, self.positions)): if verbose and snp_i % 100000 == 0: print 'Converted %d SNPs.' % snp_i unique_nts = sp.unique(snp).tolist() if self.missingVal in unique_nts: if len(unique_nts) != 3: continue # Skipping non-binary SNP else: unique_nts.remove(self.missingVal) else: if len(unique_nts) != 2: continue # Skipping non-binary SNP if snp[ref_i] != self.missingVal: col0_nt = snp[ref_i] decoder[col0_nt] = 0 unique_nts.remove(col0_nt) decoder[unique_nts[0]] = 1 else: decoder[unique_nts[0]] = 0 decoder[unique_nts[1]] = 1 snps.append(coding_fun(snp)) positions.append(pos) print 'Removed %d non-binary SNPs out of %d, when converting to binary SNPs.'\ % (len(self.positions) - len(positions), len(self.positions)) assert len(snps) == len(positions), 'Somthing odd with the lengths.' return SNPsData(snps, positions, accessions=self.accessions, marker_types=self.marker_types, missing_val=missingVal) def filterBadSnps(self, snpsd, maxNumError=0): """ 05/12/08 add no_of_snps_filtered_by_mismatch Filters snps with high rate mismatches, when compared against another snpsd. """ newSnps = [] newPositions = [] sys.stderr.write("Comparing datas. Number of snps: %s vs %s. \n" % (len(self.snps), len(snpsd.snps))) # Find common accession indices accessionsIndices = [] commonAccessions = [] for i in range(0, len(self.accessions)): acc = self.accessions[i] if snpsd.accessions.count(acc): j = snpsd.accessions.index(acc) accessionsIndices.append([i, j]) commonAccessions.append(acc) commonSnpsPos = [] i = 0 j = 0 while i <= len(self.positions) and j <= len(snpsd.positions): if i < len(self.positions): pos1 = self.positions[i] if j < len(snpsd.positions): pos2 = snpsd.positions[j] if i < len(self.positions) and pos1 < pos2: newSnps.append(self.snps[i]) newPositions.append(self.positions[i]) i = i + 1 elif j < len(snpsd.positions) and pos2 < pos1: j = j + 1 elif i < len(self.positions) and j < len(snpsd.positions) and pos1 == pos2: commonSnpsPos.append(pos1) fails = 0 counts = 0 for k in range(0, len(accessionsIndices)): accIndices = accessionsIndices[k] snp1 = self.snps[i][accIndices[0]] snp2 = snpsd.snps[j][accIndices[1]] if snp1 != self.missingVal and snp2 != self.missingVal: counts += 1 if snp1 != snp2: fails = fails + 1 error = 0 if counts > 0: error = float(fails) / float(counts) if error <= maxNumError: newSnps.append(self.snps[i]) newPositions.append(self.positions[i]) i = i + 1 j = j + 1 else: # One pointer has reached and the end and the other surpassed it. break self.no_of_snps_filtered_by_mismatch = len(self.snps) - len(newSnps) sys.stderr.write('%s SNPs were filtered\n' % (self.no_of_snps_filtered_by_mismatch)) self.snps = newSnps self.positions = newPositions def convertBadCallsToNA(self, minCallProb=0): """ Converts all base calls with call prob. lower than the given one to NAs. """ totalCount = len(self.positions) * len(self.snps[0]) count = 0 for i in range(0, len(self.positions)): for j in range(0, len(self.snps[i])): if self.callProbabilities[i][j] < minCallProb: self.snps[i][j] = self.missingVal count += 1 fractionConverted = count / float(totalCount) return fractionConverted def getSnpsNArates(self): """ Returns a list of accessions and their missing value rates. """ naRates = [] for i in range(0, len(self.positions)): missingCounts = 0 totalCounts = 0 for j in range(0, len(self.accessions)): totalCounts += 1 if self.snps[i][j] == self.missingVal: missingCounts += 1 naRates.append(missingCounts / float(totalCounts)) return naRates def filterMissingSnps(self, maxNumMissing=0): """ 05/12/2008 add no_of_snps_filtered_by_na Removes SNPs from the data which have more than maxNumMissing missing values. """ warnings.warn("This function is deprecated!!") newPositions = [] newSnps = [] for i in range(0, len(self.positions)): missingCount = 0 for nt in self.snps[i]: if nt == self.missingVal: missingCount += 1 if missingCount <= maxNumMissing: newSnps.append(self.snps[i]) newPositions.append(self.positions[i]) numRemoved = len(self.positions) - len(newPositions) self.no_of_snps_filtered_by_na = numRemoved self.snps = newSnps self.positions = newPositions return numRemoved def na_ambigious_calls(self, maxNumMissing=0): """ NAs any ambiguous calls, i.e. anything but A,C,G,T,- """ for snp in self.snps: for i, nt in enumerate(snp): if not nt in ['A', 'C', 'G', 'T', '-', self.missingVal]: snp[i] = self.missingVal def filterMinMAF(self, minMAF=0): """ Removes SNPs from the data which have a minor allele count less than the given one. """ warnings.warn("This function is old, and should be replaced.. please don't use it!!") newPositions = [] newSnps = [] ntCounts = [0.0] * len(self.alphabet) ntl = self.alphabet for i in range(0, len(self.positions)): snp = self.snps[i] totalCount = 0 for j in range(0, len(self.alphabet)): nt = ntl[j] c = snp.count(nt) ntCounts[j] = c totalCount += c if totalCount == 0 : print "snp:", snp print "self.alphabet:", self.alphabet maxAF = max(ntCounts) maf = 0 if ntCounts.count(maxAF) < 2: for j in range(0, len(self.alphabet)): if ntCounts[j] < maxAF and ntCounts[j] > 0: if ntCounts[j] > maf: maf = ntCounts[j] else: maf = maxAF if minMAF <= maf: newSnps.append(self.snps[i]) newPositions.append(self.positions[i]) numRemoved = len(self.positions) - len(newPositions) self.snps = newSnps self.positions = newPositions return numRemoved def filterMinMARF(self, minMARF=0): """ Removes SNPs from the data which have a Relative MAF less than the given one. """ warnings.warn("This function is old, and should be replaced.. please don't use it!!") newPositions = [] newSnps = [] ntCounts = [0.0] * len(self.alphabet) ntl = self.alphabet for i in range(0, len(self.positions)): snp = self.snps[i] totalCount = 0 for j in range(0, len(self.alphabet)): nt = ntl[j] c = snp.count(nt) ntCounts[j] = c totalCount += c if totalCount == 0 : print "snp:", snp print "self.alphabet:", self.alphabet for j in range(0, len(self.alphabet)): ntCounts[j] = ntCounts[j] / float(totalCount) maxAF = max(ntCounts) maf = 0 if ntCounts.count(maxAF) < 2: for j in range(0, len(self.alphabet)): if ntCounts[j] < maxAF and ntCounts[j] > 0.0: if ntCounts[j] > maf: maf = ntCounts[j] else: maf = maxAF if minMARF <= maf: newSnps.append(self.snps[i]) newPositions.append(self.positions[i]) numRemoved = len(self.positions) - len(newPositions) self.snps = newSnps self.positions = newPositions return numRemoved def snpsFilterMAF(self, maf_thresholds): self.filterMinMARF(maf_thresholds[0]) if maf_thresholds[1] < 0.5: raise Exception def mergeIdenticalAccessions(self, accessionIndexList, priority): """ The priority argument gives particular accessions in the list priority if priority is set to 0, then majority (if any) rules. """ pass class SNPsData(_SnpsData_): """ An alternative to the old SnpsData class, where this uses scipy to speed things up when possible. """ alphabet = [-1, 0, 1, 2, 3] # Here -1 is thought to be missing data value. def __init__(self, snps, positions, accessions=None, arrayIds=None, chromosome=None, alignment_positions=None, id=None, marker_types=None, missing_val= -1): self.snps = snps self.positions = positions self.accessions = accessions self.arrayIds = arrayIds self.chromosome = chromosome self.alignment_positions = alignment_positions self.marker_types = marker_types # Where do these markers come frome, what type are they? Useful for later analysis. self.id = id self.missingVal = missing_val def removeAccessionIndices(self, indicesToKeep): """ Removes accessions from the data. """ newAccessions = [] newArrayIds = [] for i in indicesToKeep: newAccessions.append(self.accessions[i]) if self.arrayIds: newArrayIds.append(self.arrayIds[i]) num_accessions = len(indicesToKeep) for i in range(len(self.snps)): self.snps[i] = self.snps[i][indicesToKeep] # snp = self.snps[i] # newSnp = sp.empty(num_accessions,dtype='int8') # for j,k in enumerate(indicesToKeep): # newSnp[j] = snp[k] # self.snps[i] = newSnp self.accessions = newAccessions if self.arrayIds: # print "removeAccessionIndices: has array IDs: self.arrayIds =",self.arrayIds self.arrayIds = newArrayIds # print "len(self.arrayIds):",len(self.arrayIds) # pdb.set_trace() # print "len(self.accessions):",len(self.accessions) def onlyBinarySnps(self): """ Removes all but binary SNPs. (I.e. monomorphic, tertiary and quaternary alleles SNPs are removed.) """ new_positions = [] new_snps = [] for i, (snp, pos) in enumerate(izip(self.snps, self.positions)): if len(sp.unique(snp)) == 2: new_snps.append(snp) new_positions.append(pos) num_removed = len(self.positions) - len(new_positions) self.no_of_nonbinary_snps_removed = num_removed self.snps = new_snps self.positions = new_positions # print "Removed %d non-binary SNPs, leaving %d SNPs in total." % (num_removed, len(self.snps)) return num_removed def remove_monomorphic_snps(self): """ Removes all fixed SNPs. (I.e. monomorphic.) """ new_positions = [] new_snps = [] for i, (snp, pos) in enumerate(izip(self.snps, self.positions)): if len(sp.unique(snp)) > 1: new_snps.append(snp) new_positions.append(pos) num_removed = len(self.positions) - len(new_positions) self.snps = new_snps self.positions = new_positions # print "Removed %d non-binary SNPs, leaving %d SNPs in total." % (num_removed, len(self.snps)) return num_removed def haplotize(self, snp_window=None, base_window=None): if snp_window: haplotypes_list = [] i = 0 num_accessions = len(self.accessions) while i < snp_window: cur_snps = self.snps[:i + snp_window + 1] haplotypes_list.append(get_haplotypes(cur_snps, num_accessions)) i += 1 while i < len(self.snps) - snp_window: cur_snps = self.snps[i - snp_window:i + snp_window + 1] haplotypes_list.append(get_haplotypes(cur_snps, num_accessions)) i += 1 if i % 100 == 0: print i while i < len(self.snps): cur_snps = self.snps[i - snp_window:] haplotypes_list.append(get_haplotypes(cur_snps, num_accessions)) i += 1 self.snps = haplotypes_list elif base_window: raise NotImplementedError else: raise Exception('Window size missing') def get_mafs(self, w_missing=False, type='binary'): """ Returns MAFs and MARFs (Uses numpy.bincount) types supported: classes (e.g. binary data), diploid_ints, .. """ def _get_maf_(snp): # For missing data coded as -1s l = sp.bincount(snp) maf = max(l) for m in l[1:]: if m != 0 and m < maf: maf = m return maf mafs = [] marfs = [] num_nts = len(self.snps[0]) if w_missing: for snp in self.snps: if self.missingVal in snp: missing_count = list(snp).count(self.missingVal) num_nts = len(snp) - missing_count nts = set(snp) nts.remove(self.missingVal) c = list(snp).count(nts.pop()) / float(num_nts) if c > 0.5: c = 1.0 - c marfs.append(c) mafs.append(int(c * num_nts)) else: l = sp.bincount(snp) maf = min(l) mafs.append(maf) marfs.append(maf / float(num_nts)) else: if type in ['binary', 'int']: for snp in self.snps: l = sp.bincount(snp) maf = min(l) mafs.append(maf) marfs.append(maf / float(num_nts)) elif type == 'diploid_int': for snp in self.snps: bin_counts = sp.bincount(snp) bin_counts = sp.bincount(snp, minlength=3) l = sp.array([bin_counts[0], bin_counts[2]]) + bin_counts[1] / 2.0 maf = l.min() mafs.append(maf) marfs.append(maf / float(num_nts)) else: raise NotImplementedError return {"mafs":mafs, "marfs":marfs} def filter_mac(self, min_mac=15, w_missing=False, data_format='binary'): """ Filter minor allele count SNPs. """ print 'Filtering SNPs with MAC<%d, assuming %s data format' % (min_mac, data_format) new_snps = [] new_positions = [] if w_missing: raise NotImplementedError if data_format in ['binary', 'int']: for snp, pos in izip(self.snps, self.positions): bc = sp.bincount(snp) if len(bc) > 1 and bc.min() >= min_mac: new_snps.append(snp) new_positions.append(pos) elif data_format == 'diploid_int': for snp, pos in izip(self.snps, self.positions): bin_counts = sp.bincount(snp, minlength=3) l = sp.array([bin_counts[0], bin_counts[2]]) + bin_counts[1] / 2.0 if l.min() >= min_mac: new_snps.append(snp) new_positions.append(pos) print 'Removed %d SNPs out of %d, leaving %d SNPs.' % (len(self.positions) - len(new_positions), len(self.positions), len(new_positions)) self.positions = new_positions self.snps = new_snps def merge_data(self, sd, acc_merge_type='intersection', error_threshold=0.1, discard_error_threshold=0.1): """ Merges data, possibly allowing multiple markers at a position. (E.g. deletions and SNPs.) However it merges markers which overlap to a significant degree (error_threshold). (Uses scipy SNPs) """ perc_overlap = len(set(self.accessions).intersection(set(sd.accessions))) \ / float(len(set(self.accessions).union(set(sd.accessions)))) print "Percentage of overlapping accessions %s" % perc_overlap if acc_merge_type == 'union': new_accessions = list(set(self.accessions).union(set(sd.accessions))) elif acc_merge_type == 'intersection': new_accessions = list(set(self.accessions).intersection(set(sd.accessions))) else: new_accessions = self.accessions acc_map = [] for acc in new_accessions: try: ai1 = self.accessions.index(acc) except: ai1 = -1 try: ai2 = sd.accessions.index(acc) except: ai2 = -1 acc_map.append((ai1, ai2)) num_accessions = len(new_accessions) missing_val_snp = sp.array(sp.repeat(self.missingVal, num_accessions), dtype='int8') # To handle multiple markers at the same position index_dict = {} j = 0 last_pos = sd.positions[j] for i, pos in enumerate(self.positions): curr_pos = last_pos while j < len(sd.positions) and curr_pos < pos: j += 1 if j < len(sd.positions): curr_pos = sd.positions[j] last_pos = curr_pos index_list = [] while j < len(sd.positions) and curr_pos == pos: index_list.append(j) j += 1 if j < len(sd.positions): curr_pos = sd.positions[j] if index_list: index_dict[i] = index_list indices_to_skip = set() # Markers which are merged in the second SNPsData new_snps = [] new_positions = [] merge_count = 0 for i, snp1 in enumerate(self.snps): new_snp = sp.array(sp.repeat(self.missingVal, num_accessions), dtype='int8') if i in index_dict: # If there are markers at the same position. index_list = index_dict[i] for j in index_list: error_count = 0 t_count = 0 # total count snp2 = sd.snps[j] for (ai1, ai2) in acc_map: if ai1 != -1 and ai2 != -1: if snp1[ai1] != snp2[ai2] and snp1[ai1] != self.missingVal\ and snp2[ai2] != self.missingVal: error_count += 1 t_count += 1 merge_error = error_count / float(t_count) if t_count > 0 else 1 if merge_error <= error_threshold or merge_error > discard_error_threshold: indices_to_skip.add(j) if merge_error <= error_threshold: print "Merge error is %f" % merge_error for ni, (ai1, ai2) in enumerate(acc_map): if ai1 != -1 and ai2 != -1: if snp1[ai1] != self.missingVal: new_snp[ni] = snp1[ai1] else: new_snp[ni] = snp2[ai2] elif ai1 == -1: new_snp[ni] = snp2[ai2] else: new_snp[ni] = snp1[ai1] merge_count += 1 else: print 'Removing SNP at position %d since they have an error of %f'\ % (self.positions[i], merge_error) elif t_count > 0: print "Not merging since error is %f" % merge_error for ni, (ai1, ai2) in enumerate(acc_map): if ai1 != -1: new_snp[ni] = snp1[ai1] else: # There were no markers at this position in the other snps data. for ni, (ai1, ai2) in enumerate(acc_map): if ai1 != -1: new_snp[ni] = snp1[ai1] if sp.any(new_snp != missing_val_snp): # Some are not are missing new_snps.append(new_snp) new_positions.append(self.positions[i]) print 'Inserting %d non-overlapping SNPs into the self snps data.' % len(sd.snps) for j in range(len(sd.snps)): if not j in indices_to_skip: # There were no markers at this position in the other snps data. snp2 = sd.snps[j] new_snp = sp.array(sp.repeat(self.missingVal, num_accessions), dtype='int8') for ni, (ai1, ai2) in enumerate(acc_map): if ai2 != -1: new_snp[ni] = snp2[ai2] if new_snp == []: raise Exception new_snps.append(new_snp) new_positions.append(sd.positions[j]) print 'Sorting SNPs by positions..' pos_snp_list = zip(new_positions, range(len(new_positions))) pos_snp_list.sort() r = map(list, zip(*pos_snp_list)) self.positions = r[0] self.snps = [new_snps[i] for i in r[1]] self.accessions = new_accessions if len(self.snps) != len(self.positions): raise Exception print "Merged %d SNPs!" % (merge_count) print "Resulting in %d SNPs in total" % len(self.snps) class SnpsData(_SnpsData_): """ A class for SNPs data. It uses 0, 1 (and 2, 3 if there are more than 2 alleles) to represent SNPs. -1 is used if the allele data is missing. This class should really be named marker data, as it is used for more than just SNP markers. Contains various functions that aid the analysis of the data. """ # freqs = [] #list[position_index1][position_index2-position_index1+1] Linkage frequencies. # baseScale = 1 #Scaling for positions alphabet = [0, 1, 2, 3] def __init__(self, snps, positions, baseScale=None, accessions=None, arrayIds=None, chromosome=None, alignment_positions=None, id=None, marker_types=None, missing_val= -1): self.snps = snps self.positions = positions if baseScale: self.scalePositions(baseScale) self.accessions = accessions self.arrayIds = arrayIds self.chromosome = chromosome self.alignment_positions = alignment_positions self.marker_types = marker_types # Where do these markers come frome, what type are they? Useful for later analysis. self.id = id self.missingVal = missing_val def clone(self): """ Filter all SNPs but those in region. """ newSNPs = [] newPositions = [] newAccessions = [] for acc in self.accessions: newAccessions.append(acc) for i in range(0, len(self.positions)): new_snp = [] for j in range(0, len(self.accessions)): new_snp.append(self.snps[i][j]) newSNPs.append(new_snp) newPositions.append(self.positions[i]) return SnpsData(newSNPs, newPositions, accessions=newAccessions, arrayIds=self.arrayIds, chromosome=self.chromosome) def remove_redundant_snps(self, r2_threshold=0.8, w_missing=False): """ Removes any redundant SNPs as measured by correlation. Returns information on what SNPs are correlated. """ r2s = self.calc_r2_matrix(w_missing=w_missing) snps_indices = range(len(self.snps)) new_snps_indices = [] redundant_snps_indices_list = [] redundant_pos_list = [] while snps_indices: si1 = snps_indices.pop() new_snps_indices.append(si1) redundant_snps_indices = [] redundant_positions = [] for si2 in snps_indices[:]: if r2s[si1, si2] >= r2_threshold: redundant_snps_indices.append(si2) redundant_positions.append(self.positions[si2]) snps_indices.remove(si2) redundant_pos_list.append(redundant_positions) redundant_snps_indices_list.append(redundant_snps_indices) print "In total", len(self.snps), ", thereof", len(self.snps) - len(new_snps_indices), "are redundant." self.filter_snp_indices(new_snps_indices) self.redundant_positions = redundant_pos_list return redundant_pos_list def calcFreqs(self, windowSize, innerWindowSize=0): """ Returns a list of two loci comparison frequencies with in a window. """ freqs = [] delta = 0 if len(self.snps) > 0: delta = 1.0 / float(len(self.snps[0])) for i in xrange(0, len(self.snps) - 1): l = [] j = i + 1 while j < len(self.snps) and (self.positions[j] - self.positions[i]) < innerWindowSize : j = j + 1 while j < len(self.snps) and (self.positions[j] - self.positions[i]) <= windowSize: jfreqs = [0.0] * 4 # The frequencies, of a pair of alleles. snp1 = self.snps[i] snp2 = self.snps[j] count = 0 for k in xrange(0, len(snp1)): val = snp1[k] * 2 + snp2[k] jfreqs[val] = jfreqs[val] + delta l.append(jfreqs) j = j + 1 freqs.append(l) self.freqs = freqs return self.freqs def calc_all_freqs(self, w_missing=False): """ Returns a matrix of two loci comparison frequencies. """ if w_missing: freqs = [] for i, snp1 in enumerate(self.snps): l = [] for j in range(i): jfreqs = [0.0] * 4 # The frequencies, of a pair of alleles. snp2 = self.snps[j] count = 0.0 for nt1, nt2 in zip(snp1, snp2): if nt1 != self.missingVal and nt2 != self.missingVal: count += 1.0 val = nt1 * 2 + nt2 jfreqs[val] += 1.0 jfreqs = [f / count for f in jfreqs] l.append(jfreqs) freqs.append(l) return freqs else: freqs = [] delta = 0 if len(self.snps) > 0: delta = 1.0 / float(len(self.snps[0])) for i, snp1 in enumerate(self.snps): l = [] for j in range(i): jfreqs = [0.0] * 4 # The frequencies, of a pair of alleles. snp2 = self.snps[j] for k in range(len(snp1)): val = snp1[k] * 2 + snp2[k] jfreqs[val] = jfreqs[val] + delta l.append(jfreqs) freqs.append(l) return freqs def calcFreqsUnbiased(self, windowSize, innerWindowSize=0): # Returns a list of two loci comparison frequencies with in a window. """ Uses a distribution of frequencies that is not dependent on the lenght of the sequence. (Alot of data is disregarded.) """ numPairs = 0 # Counts the number of pairs freqs = [] delta = 0 if len(self.snps) > 0: delta = 1.0 / float(len(self.snps[0])) for i in xrange(0, len(self.snps) - 1): if (self.positions[len(self.snps) - 1] - self.positions[i]) >= windowSize: j = i + 1 l = [] while j < len(self.snps) and (self.positions[j] - self.positions[i]) < innerWindowSize : j = j + 1 while j < len(self.snps) and (self.positions[j] - self.positions[i]) <= windowSize: jfreqs = [0.0] * 4 snp1 = self.snps[i] snp2 = self.snps[j] count = 0 for k in xrange(0, len(snp1)): val = snp1[k] * 2 + snp2[k] jfreqs[val] = jfreqs[val] + delta l.append(jfreqs) j = j + 1 numPairs = numPairs + 1 freqs.append(l) else: break self.freqs = freqs return self.freqs # return numPairs def calcFreqsSimple(self): freqs = [] delta = 0 if len(self.snps) > 0: delta = 1.0 / float(len(self.snps[0])) for i in xrange(0, len(self.snps) - 1): l = [] for j in xrange(i + 1, len(self.snps)): jfreqs = [0.0] * 4 snp1 = self.snps[i] snp2 = self.snps[j] count = 0 for k in xrange(0, len(snp1)): val = snp1[k] * 2 + snp2[k] jfreqs[val] = jfreqs[val] + delta l.append(jfreqs) freqs.append(l) self.freqs = freqs return self.freqs def snpsFilter(self): """ Splits the SNPs up after their allele frequency .. """ snpsDatas = [SnpsData([], []), SnpsData([], []), SnpsData([], []), SnpsData([], []), SnpsData([], []), SnpsData([], []), SnpsData([], []), SnpsData([], []), SnpsData([], []), SnpsData([], [])] l = len(self.snps[0]) for j in xrange(0, len(self.snps)): snp = self.snps[j] c = snp.count(0) / float(l) """ if c>0.5: c = 1-c if c == 0.5: c =0.499 """ if c == 1: c = 0.99999 i = int(c * 10) snpsDatas[i].addSnp(snp) snpsDatas[i].addPos(self.positions[j]) return snpsDatas def snpsFilterMAF(self, mafs, type='classes'): """ Filters all snps with MAF not in the interval out of dataset. """ newsnps = [] newpos = [] # print self.snps l = len(self.snps[0]) if l == 0: print self.snps for j in xrange(0, len(self.snps)): snp = self.snps[j] c = snp.count(0) / float(l) if c > 0.5: c = 1 - c if c > mafs[0] and c <= mafs[1]: newsnps.append(snp) newpos.append(self.positions[j]) if len(newsnps) == 0: print "Filtered out all snps from", len(self.snps), " what to do what to do?" del self.snps self.snps = newsnps del self.positions self.positions = newpos def snpsFilterRare(self, threshold=0.1): """Filters all snps with MAF of less than threshold out of dataset.""" newsnps = [] newpos = [] # print self.snps l = len(self.snps[0]) if l == 0: print self.snps for j in xrange(0, len(self.snps)): snp = self.snps[j] c = snp.count(0) / float(l) if c > 0.5: c = 1 - c if c > threshold: newsnps.append(snp) newpos.append(self.positions[j]) # if len(newsnps)==0: # print "Filtered out all snps from",len(self.snps)," what to do what to do?" del self.snps self.snps = newsnps del self.positions self.positions = newpos def _genRecombFile(self, filename, windowSize, maxNumPairs): n = len(self.snps[0]) # number of individuals/accessions numPairs = self.calcFreqsUnbiased(windowSize) if numPairs != 0: filterProb = float(maxNumPairs) / numPairs else: return numPairs f = open(filename, 'w') numPairs = 0 for i in range(0, len(self.freqs)): for j in range(0, len(self.freqs[i])): if random.random() <= filterProb: numPairs = numPairs + 1 st = str(i + 1) + " " + str(j + i + 2) + " " + str(self.positions[j + i + 1] - self.positions[i]) + " u " # u denotes unknown as opposed to ad ancestral derived st = st + str(int(self.freqs[i][j][0] * n + 0.5)) + " " + str(int(self.freqs[i][j][1] * n + 0.5)) + " " st = st + str(int(self.freqs[i][j][2] * n + 0.5)) + " " + str(int(self.freqs[i][j][3] * n + 0.5)) + " 0 0 0 0 " + str(100 - n) + "\n" f.write(st) f.close() return numPairs # def estimateRecomb(self, windowSize, maxNumPairs=10000, tempfile1="tmp1", tempfile2="tmp2", meanTract=200, numPoints=50): # num = self._genRecombFile(tempfile1, windowSize, maxNumPairs) # if num < 1: # return [0, 0, 0] # os.system(homedir + "Projects/programs/Maxhap/maxhap 1 " + homedir + "Projects/programs/Maxhap/h100rho .0008 10 .1 0.01 500 " + str(numPoints) + " " + str(meanTract) + " < " + tempfile1 + " > " + tempfile2) # f = open(tempfile2, 'r') # lines = f.readlines() # npairs = float(lines[1].split()[2]) # i = 2 # while(lines[i].split()[0] == "Warning:"): # i = i + 1 # rho = float(lines[i].split()[1]) # ratio = float(lines[i].split()[2]) # f.close() # return [rho, ratio, npairs] def meanAF(self): """ Mean allele frequency. """ if len(self.snps): l = float(len(self.snps[0])) c = 0 for j in xrange(0, len(self.snps)): snp = self.snps[j] snpsc = snp.count(0) if snpsc < (l / 2.0): c = c + snpsc / l else: c = c + abs((l / 2.0) - snpsc) / l return c / len(self.snps) else: return 0 def EHH(self, snp1, snp2): """ Calculates the EHH between two SNPs""" # data = self.snps[snp1:snp2] haplotypes = [] haplotypecount = [] for i in range(0, len(self.snps[0])): haplotype = [] for j in range(snp1, snp2 + 1): haplotype.append(self.snps[j][i]) if not haplotype in haplotypes: haplotypes.append(haplotype) haplotypecount.append(1.0) else: k = haplotypes.index(haplotype) haplotypecount[k] = haplotypecount[k] + 1.0 s = 0.0 for i in range(0, len(haplotypes)): if haplotypecount[i] > 1: s = s + haplotypecount[i] * (haplotypecount[i] - 1) s = s / (len(self.snps[0]) * (len(self.snps[0]) - 1)) return s def totalEHH(self, windowSize, innerWindowSize): """ Lenght indep mean EHH statistics.. (Note: no data filtering!) """ ehhcount = 0 ehh = 0.0 for i in xrange(0, len(self.snps) - 1): if (self.positions[len(self.snps) - 1] - self.positions[i]) >= windowSize: j = i + 1 l = [] while j < len(self.snps) and (self.positions[j] - self.positions[i]) < innerWindowSize : j = j + 1 while j < len(self.snps) and (self.positions[j] - self.positions[i]) <= windowSize: ehh = ehh + self.EHH(i, j) ehhcount = ehhcount + 1 j = j + 1 else: break return [ehh, ehhcount] class SNPsDataSet: """ A class that encompasses multiple _SnpsData_ chromosomes objects (chromosomes), and can deal with them as a whole. This object should eventually replace the snpsdata lists.. """ snpsDataList = None chromosomes = None accessions = None def __init__(self, snpsds, chromosomes, id=None, call_method=None, data_format=None): self.snpsDataList = snpsds self.chromosomes = chromosomes self.accessions = self.snpsDataList[0].accessions self.array_ids = self.snpsDataList[0].arrayIds self.id = id self.missing_val = snpsds[0].missingVal self.call_method = call_method self.data_format = data_format # binary, diploid_ints, floats, int if not id and snpsds[0].id: self.id = id for i in range(1, len(self.chromosomes)): if self.accessions != self.snpsDataList[i].accessions: raise Exception("Accessions (or order) are different between SNPs datas") self.is_binary = list(snpsds[0].snps[0]).count(0) or list(snpsds[0].snps[0]).count(1) # def add_to_db(self, short_name, method_description='', data_description='', comment='', **kwargs): # """ # Other possible keyword args are parent_id, accession_set_id ,imputed ,unique_ecotype # """ # conn = dbutils.connect_to_papaya() # cursor = conn.cursor() # # # #Checking whether data is already inserted... # sql_statement = "SELECT id FROM stock_250k.call_method WHERE short_name='%s';" % (short_name) # print sql_statement # cursor.execute(sql_statement) # row = cursor.fetchone() # print row # if row: # print "Data is already inserted in DB. File will however be updated." # call_method_id = int(row[0]) # filename = '/Network/Data/250k/db/dataset/call_method_%d.tsv' % call_method_id # else: # # #Inserting data # sql_statement = "INSERT INTO stock_250k.call_method (short_name,method_description,data_description,comment" # for k in kwargs: # sql_statement += ',%s' % k # sql_statement += ") VALUES ('%s','%s','%s','%s'" % (short_name, method_description, data_description, comment) # for k in kwargs: # sql_statement += ',%s' % str(kwargs[k]) # sql_statement += ');' # print sql_statement # cursor.execute(sql_statement) # # #Getting method_id # sql_statement = "SELECT id FROM stock_250k.call_method WHERE short_name='%s';" % (short_name) # print sql_statement # cursor.execute(sql_statement) # row = cursor.fetchone() # call_method_id = int(row[0]) # filename = '/Network/Data/250k/db/dataset/call_method_%d.tsv' % call_method_id # # #Updating the filename # sql_statement = "UPDATE stock_250k.call_method SET filename='%s' WHERE id=%d" % (filename, call_method_id) # print sql_statement # cursor.execute(sql_statement) # # print "Committing transaction (making changes permanent)." # conn.commit() # # print "Call method id is %d" % call_method_id # #Generating Yu's file... # self.write_to_file_yu_format(filename) # # # # #Generate DB call files... # self._generate_db_call_files_(call_method=call_method_id, cursor=cursor, conn=conn) # # #Add SNPs to DB? # # # cursor.close() # conn.close() # # return call_method_id # # # # # def _generate_db_call_files_(self, call_method=None, array_ids=None, file_dir='/Network/Data/250k/db/calls/', cursor=None, conn=None): # import os # import warnings # # if not array_ids: # if not self.array_ids: # raise Exception('Array IDs are missing.') # else: # array_ids = self.array_ids # if not call_method: # raise Exception("Call method is missing!!") # chr_pos_snp_list = self.getChrPosSNPList() # # #Create the call method directory # file_dir = file_dir + 'method_' + str(call_method) + '/' # if not os.path.lexists(file_dir): # os.mkdir(file_dir) # else: # warnings.warn('Directory already exists: %s' % file_dir) # # #Connect to DB, if needed # if not cursor: # import dbutils # conn = dbutils.connect_to_papaya() # cursor = conn.cursor() # # for i, aid in enumerate(array_ids): # print "Inserting genotype files into DB." # #Checking if it is already in the DB. # sql_statement = "SELECT id FROM stock_250k.call_info WHERE array_id=%s AND method_id=%d;"\ # % (aid, call_method) # print sql_statement # cursor.execute(sql_statement) # row = cursor.fetchone() # if row: # 'Already in DB. File will be updated.' # call_info_id = int(row[0]) # else: # #Insert info # sql_statement = "INSERT INTO stock_250k.call_info (array_id, method_id) VALUES (%s,%d);"\ # % (aid, call_method) # print sql_statement # cursor.execute(sql_statement) # # sql_statement = "SELECT id FROM stock_250k.call_info WHERE array_id=%s AND method_id=%d;"\ # % (aid, call_method) # print sql_statement # cursor.execute(sql_statement) # row = cursor.fetchone() # if row: # call_info_id = int(row[0]) # print "Committing transaction (making changes permanent)." # conn.commit() # # try: # #Write to a designated place. # file_name = file_dir + str(call_info_id) + "_call.tsv" # sql_statement = "UPDATE stock_250k.call_info \ # SET filename='%s'\ # WHERE id=%d" % (file_name, call_info_id) # print sql_statement # cursor.execute(sql_statement) # # #Generate file in the right place # f = open(file_name, 'w') # f.write('SNP_ID\t%s\n' % aid) # for (c, p, s) in chr_pos_snp_list: # f.write('%d_%d\t%s\n' % (c, p, s[i])) # f.close() # except Exception, err_str: # print "Couldn't generate call info file, error message:%s" % err_str # print "Closing connection." # #Close connection # if not cursor: # cursor.close() # conn.close() # print "Remember to copy files to papaya, i.e. everything in directory: %s" % file_dir def writeToFile(self, filename, delimiter=",", missingVal="NA", accDecoder=None, withArrayIds=False, decoder=None, callProbFile=None, binary_format=False): """ Writes data to a file. Note that there is no decoder dictionary option here.. """ print "Writing data to file:", filename numSnps = 0 for i in range(0, len(self.chromosomes)): numSnps += len(self.snpsDataList[i].positions) # outStr = "NumSnps: "+str(numSnps)+", NumAcc: "+str(len(accessions))+"\n" if withArrayIds: outStr = ", ".join(["-", "-"] + self.snpsDataList[0].arrayIds) + "\n" else: outStr = "" fieldStrings = ["Chromosome", "Positions"] if accDecoder: for acc in self.snpsDataList[i].accessions: fieldStrings.append(str(accDecoder[acc])) else: for acc in self.snpsDataList[i].accessions: fieldStrings.append(str(acc)) outStr += delimiter.join(fieldStrings) + "\n" if binary_format: f = open(filename, "wb") else: f = open(filename, "w") f.write(outStr) if decoder: for chromosome, snpsd in izip(self.chromosomes, self.snpsDataList): sys.stdout.write(".") sys.stdout.flush() for pos, snp in izip(snpsd.positions, snpsd.snps): outStr = str(chromosome) + delimiter + str(pos) for nt in snp: outStr += delimiter + str(decoder[snp]) outStr += "\n" f.write(outStr) # for j in range(0,len(self.snpsDataList[i].positions)): # outStr ="" # outStr += str(self.chromosomes[i])+delimiter+str(self.snpsDataList[i].positions[j]) # for k in range(0, len(self.snpsDataList[0].accessions)): # outStr += delimiter+str(decoder[self.snpsDataList[i].snps[j][k]]) # outStr +="\n" # f.write(outStr) else: for chromosome, snpsd in izip(self.chromosomes, self.snpsDataList): sys.stdout.write(".") sys.stdout.flush() for pos, snp in izip(snpsd.positions, snpsd.snps): outStr = '%d%s%d%s%s\n' % (chromosome, delimiter, pos, delimiter, delimiter.join(map(str, snp.tolist()))) f.write(outStr) # for i in range(0,len(self.chromosomes)): # sys.stdout.write(".") # sys.stdout.flush() # for j in range(0,len(self.snpsDataList[i].positions)): # outStr ="" # outStr += str(self.chromosomes[i])+delimiter+str(self.snpsDataList[i].positions[j]) # snp = self.snpsDataList[i].snps[j] # if len(snp) != len(self.snpsDataList[0].accessions): # print "len(snp):",len(snp),", vs. len(self.snpsDataList[0].accessions):",len(self.snpsDataList[0].accessions) # raise Exception("The length didn't match") # for nt in snp: # outStr += delimiter+str(nt) # outStr +="\n" # f.write(outStr) f.close() print "" if callProbFile: if withArrayIds: outStr = "-, -, " + ", ".join(self.snpsDataList[0].arrayIds) + "\n" else: outStr = "" f = open(callProbFile, "w") outStr += delimiter.join(fieldStrings) + "\n" f.write(outStr) f.flush() for i in range(0, len(self.chromosomes)): outStr = "" snpsd = self.snpsDataList[i] self.snpsDataList[i] = [] for j in range(0, len(snpsd.positions)): outStr += str(self.chromosomes[i]) + delimiter + str(snpsd.positions[j]) for k in range(0, len(snpsd.accessions)): outStr += delimiter + str(snpsd.callProbabilities[j][k]) outStr += "\n" del snpsd f.write(outStr) f.flush() f.close() # # def write_to_file_yu_format(self, filename): # """ # Writes data to a file in Yu's format. (Requires array IDs) # # Only works with raw sequence data.. (IUPAC nucleotides) # """ # import yu_snp_key as yk # print "transposing chr_pos_snp_list" # chr_pos_snp_list = map(list, zip(*self.getChrPosSNPList())) # chrs = chr_pos_snp_list[0] # positions = chr_pos_snp_list[1] # snps = chr_pos_snp_list[2] # assert len(snps) == len(chrs) == len(positions), "SNPs, chromosomes, and positions not with same lenght" # # print "transposing SNPs" # snps = map(list, zip(*snps)) # # array_ids = self.array_ids # ecotypes = self.accessions # assert len(snps) == len(array_ids) == len(ecotypes), "SNP, array IDs, and ecotype IDs not with same lenght" # # print "len(array_ids) len(ecotypes):", len(array_ids), len(ecotypes) # # print "Writing data to file:", filename # f = open(filename, "w") # str_list = ['ecotype_id', 'array_id'] # str_list.extend([str(c) + "_" + str(p) for (c, p) in zip(chrs, positions)]) # f.write('\t'.join(str_list) + '\n') # for ei, ai, nts in zip(ecotypes, array_ids, snps): # str_list = [str(ei), str(ai)] # str_list.extend([str(yk.nt_2_number[nt]) for nt in nts]) # f.write('\t'.join(str_list) + '\n') # f.close() def coordinate_w_phenotype_data(self, phend, pid, coord_phen=True, verbose=False): """ Deletes accessions which are not common, and sorts the accessions, removes monomorphic SNPs, etc. """ print "Coordinating SNP and Phenotype data." ets = phend.phen_dict[pid]['ecotypes'] # Checking which accessions to keep and which to remove. # common_ets = list(set(self.accessions + ets)) # common_ets.sort() sd_indices_to_keep = set() # [] pd_indices_to_keep = [] for i, acc in enumerate(self.accessions): for j, et in enumerate(ets): if et == acc: sd_indices_to_keep.add(i) pd_indices_to_keep.append(j) if verbose: initial_indices = set(range(len(ets))) missing_indices = list(initial_indices.difference(set(pd_indices_to_keep))) missing_indices.sort() if len(missing_indices) > 0: print "You phenotyped accessions that were not identified in the SNP-file." print [ets[i] for i in missing_indices ] # # for i, acc in enumerate(self.accessions): # if common_ets[bisect.bisect(common_ets, acc) - 1] == acc: # sd_indices_to_keep.add(i) # for j, et in enumerate(ets): # if common_ets[bisect.bisect(common_ets, et) - 1] == et: # pd_indices_to_keep.append(j) sd_indices_to_keep = list(sd_indices_to_keep) sd_indices_to_keep.sort() # Filter accessions that do not have phenotype values (from the genotype data). print "Filtering genotype data" # if len(sd_indices_to_keep) != len(self.accessions): self.filter_accessions_indices(sd_indices_to_keep) if coord_phen: num_values = len(phend.phen_dict[pid]['ecotypes']) print "Filtering phenotype data." phend.filter_ecotypes(pd_indices_to_keep, pids=[pid]) # Removing accessions that don't have genotypes or phenotype values ets = phend.phen_dict[pid]['ecotypes'] print "Out of %d, leaving %d values." % (num_values, len(ets)) # Ordering accessions according to the order of accessions in the genotype file # if ets != self.accessions: # l = zip(ets, range(len(ets))) # l.sort() # l = map(list, zip(*l)) # ets_map = l[1] # phend.order_ecotypes(ets_map, pids=[pid]) if self.data_format == 'binary': print 'Filtering non-binary SNPs' total_num = 0 removed_num = 0 for snpsd in self.snpsDataList: total_num += len(snpsd.snps) removed_num += snpsd.onlyBinarySnps() print 'Removed %d non-binary SNPs out of %d SNPs' % (removed_num, total_num) elif self.data_format in ['int', 'diploid_int']: print 'Filtering monomorhpic SNPs' total_num = 0 removed_num = 0 for snpsd in self.snpsDataList: total_num += len(snpsd.snps) removed_num += snpsd.remove_monomorphic_snps() print 'Removed %d monomorphic SNPs out of %d SNPs' % (removed_num, total_num) return {'pd_indices_to_keep':pd_indices_to_keep, 'n_filtered_snps':removed_num} def get_ibs_kinship_matrix(self, debug_filter=1, snp_dtype='int8', dtype='single'): """ Calculate the IBS kinship matrix. (un-scaled) Currently it works only for binary kinship matrices. """ import kinship print 'Starting kinship calculation' snps = self.getSnps(debug_filter) return kinship.calc_ibs_kinship(snps, snps_data_format=self.data_format, snp_dtype=snp_dtype, dtype=dtype) def get_local_n_global_kinships(self, focal_chrom_pos=None, window_size=25000, chrom=None, start_pos=None, stop_pos=None, kinship_method='ibd', global_kinship=None, verbose=False): """ Returns local and global kinship matrices. """ if focal_chrom_pos != None: chrom, pos = focal_chrom_pos start_pos = pos - window_size stop_pos = pos + window_size local_snps, global_snps = self.get_region_split_snps(chrom, start_pos, stop_pos) if verbose: print 'Found %d local SNPs' % len(local_snps) print 'and %d global SNPs' % len(global_snps) if kinship_method == 'ibd': local_k = kinship.calc_ibd_kinship(local_snps) if len(local_snps) else None if global_kinship == None: global_k = kinship.calc_ibd_kinship(global_snps) if len(global_snps) else None elif kinship_method == 'ibs': local_k = kinship.calc_ibs_kinship(local_snps) if len(local_snps) else None if global_kinship == None: global_k = kinship.calc_ibs_kinship(global_snps) if len(global_snps) else None else: raise NotImplementedError if global_kinship != None: if len(local_snps): global_k = (global_kinship * self.num_snps() - local_k * len(local_snps)) / len(global_snps) else: local_k = None global_k = global_kinship return {'local_k':local_k, 'global_k':global_k, 'num_local_snps':len(local_snps), 'num_global_snps':len(global_snps)} def get_chrom_vs_rest_kinships(self, chrom=None, kinship_method='ibd', global_kinship=None, verbose=False): """ Returns local and global kinship matrices. """ local_snps, global_snps = self.get_chrom_split_snps(chrom) if verbose: print 'Found %d SNPs on chromosome %d' % (len(local_snps), chrom) print 'and %d SNPs on other chromosomes' % len(global_snps) if kinship_method == 'ibd': local_k = self._calc_ibd_kinship_(local_snps, num_dots=0) if len(local_snps) else None if global_kinship == None: global_k = self._calc_ibd_kinship_(global_snps, num_dots=0) if len(global_snps) else None elif kinship_method == 'ibs': local_k = self._calc_ibs_kinship_(local_snps, num_dots=0) if len(local_snps) else None if global_kinship == None: global_k = self._calc_ibs_kinship_(global_snps, num_dots=0) if len(global_snps) else None else: raise NotImplementedError if global_kinship != None: if len(local_snps): global_k = (global_kinship * self.num_snps() - local_k * len(local_snps)) / len(global_snps) else: local_k = None global_k = global_kinship return {'local_k':local_k, 'global_k':global_k, 'num_local_snps':len(local_snps), 'num_global_snps':len(global_snps)} def get_region_split_snps(self, chrom, start_pos, end_pos): """ Returns two SNP sets, one with the SNPs within the given region, and the other with the remaining SNPs. """ global_snps = [] local_snps = [] chr_pos_l = self.get_chr_pos_list(cache_list=True) start_i = bisect.bisect(chr_pos_l, (chrom, start_pos)) stop_i = bisect.bisect(chr_pos_l, (chrom, end_pos)) snps = self.get_snps(cache=True) local_snps = snps[start_i:stop_i] global_snps = snps[:start_i] + snps[stop_i:] return local_snps, global_snps def get_chrom_split_snps(self, chrom): c_ends = self.get_chromosome_ends() ci = self.chromosomes.index(chrom) return self.get_region_split_snps(chrom, 0, c_ends[ci] + 1) def get_region_split_kinships(self, chrom_pos_list, kinship_method='ibd', global_kinship=None, verbose=False): """ Returns local and global kinship matrices. """ region_snps = self.get_regions_split_snps(chrom_pos_list) num_snps_found = len(region_snps) if verbose: print 'Found %d SNPs in the regions' % num_snps_found if kinship_method == 'ibd': regional_k = self._calc_ibd_kinship_(region_snps, num_dots=0) if num_snps_found else None elif kinship_method == 'ibs': regional_k = self._calc_ibs_kinship_(region_snps, num_dots=0) if num_snps_found else None else: raise NotImplementedError if global_kinship != None and regional_k != None: global_k = (global_kinship * self.num_snps() - regional_k * num_snps_found) \ / (self.num_snps() - num_snps_found) else: global_k = None return {'regional_k':regional_k, 'global_k':global_k, 'num_snps_found':num_snps_found} def get_regions_split_snps(self, chrom_pos_list): """ Returns the SNP sets, wherethe SNPs are in multiple regions, and the other is the remaining set. """ chr_pos_l = self.get_chr_pos_list() snps = self.get_snps() region_snps = [] for chrom, start_pos, end_pos in chrom_pos_list: start_i = bisect.bisect(chr_pos_l, (chrom, start_pos)) stop_i = bisect.bisect(chr_pos_l, (chrom, end_pos)) region_snps.extend(snps[start_i:stop_i]) return region_snps # def get_ibd_kinship_matrix_old(self, debug_filter=1, num_dots=10000, with_correction=True, # snp_dtype='int8', dtype='single'): # """ # Calculate the IBD kinship matrix, as described in (Yang et al., Nat. Genetics, 2010) # (un-scaled) # """ # if self.data_format != 'binary': # raise NotImplementedError # print 'Starting IBD kinship calculation, it prints %d dots.' % num_dots # snps = self.getSnps(debug_filter) # num_snps = len(snps) # num_lines = len(self.accessions) # print 'Allocating K matrix' # k_mat = sp.zeros((num_lines, num_lines), dtype=dtype) # # print 'Calculating IBD kinship... one SNP at a time' # #Do one SNP at a time to save memory... # for snp_i, snp in enumerate(snps): # p = sp.mean(snp) # norm_snp = sp.mat((snp - p) / sp.std(snp)) # M = norm_snp.T * norm_snp # if with_correction: # c = p * (1 - p * (4 - 6 * p + 3 * p * p)) # cor_norm_snp = (snp - p) / sp.sqrt(c) # for i in range(0, num_lines): # M[i, i] = cor_norm_snp[i] ** 2 # k_mat += M#norm_snp.T * norm_snp # if num_snps >= num_dots and (snp_i + 1) % (num_snps / num_dots) == 0: #Print dots # sys.stdout.write('.') # sys.stdout.flush() # k_mat = k_mat / len(snps) # return k_mat def get_ibd_kinship_matrix(self, debug_filter=1, dtype='single'): import kinship print 'Starting IBD calculation' snps = self.getSnps(debug_filter) cov_mat = kinship.calc_ibd_kinship(snps, len(self.accessions), dtype=dtype) print 'Finished calculating IBD kinship matrix' return cov_mat def get_snp_cov_matrix(self, debug_filter=1, num_dots=10, dtype='single'): print 'Initializing' num_lines = len(self.accessions) chunk_size = num_lines num_snps = self.num_snps() num_splits = num_snps / chunk_size cov_mat = sp.zeros((num_lines, num_lines)) snps = self.getSnps(debug_filter) print 'Estimating the accession means' accession_sums = sp.zeros(num_lines) for chunk_i, i in enumerate(range(0, self.num_snps(), chunk_size)): snps_array = sp.array(snps[i:i + chunk_size]) snps_array = snps_array.T norm_snps_array = (snps_array - sp.mean(snps_array, 0)) / sp.std(snps_array, 0) accession_sums += sp.sum(norm_snps_array, 1) accession_means = accession_sums / num_snps print accession_means print 'Starting covariance calculation' for chunk_i, i in enumerate(range(0, self.num_snps(), chunk_size)): snps_array = sp.array(snps[i:i + chunk_size]) snps_array = snps_array.T norm_snps_array = (snps_array - sp.mean(snps_array, 0)) / sp.std(snps_array, 0) x = sp.mat(norm_snps_array.T - accession_means) # The only difference from the IBD matrix is that we subtract the accession means. cov_mat += x.T * x if num_splits >= num_dots and (chunk_i + 1) % int(num_splits / num_dots) == 0: # Print dots sys.stdout.write('.') sys.stdout.flush() cov_mat = cov_mat / self.num_snps() print 'Finished calculating covariance matrix' return cov_mat def get_macs(self): r = self.get_mafs() return r['mafs'] def get_normalized_snps(self, debug_filter=1, dtype='single'): print 'Normalizing SNPs' snps = self.getSnps(debug_filter) snps_array = sp.array(snps) snps_array = snps_array.T # Normalizing (subtracting by) norm_snps_array = (snps_array - sp.mean(snps_array, 0)) / sp.std(snps_array, 0) print 'Finished normalizing them' return norm_snps_array def convert_data_format(self, target_data_format='binary'): """ Converts the underlying raw data format to a binary one, i.e. A,C,G,T,NA,etc. are converted to 0,1,-1 """ if self.data_format == target_data_format: import warnings warnings.warn("Data appears to be already in %s format!" % target_data_format) else: if self.data_format == 'nucleotides' and target_data_format == 'binary': snpsd_list = [] for snpsd in self.snpsDataList: snpsd_list.append(snpsd.getSnpsData()) self.snpsDataList = snpsd_list self.data_format = 'binary' self.missing_val = self.snpsDataList[0].missingVal else: raise NotImplementedError def haplotize(self, snp_window=None, base_window=None): """ Converts the data-format to a haplotype numbering format """ print 'Haplotizing!' assert (snp_window or base_window), 'snp_window or base_window arguments are missing.' for i, sd in enumerate(self.snpsDataList): sd.haplotize(snp_window=snp_window, base_window=base_window) print i def impute_missing(self, reference_data): if not len(self.snpsDataList) == len(reference_data.snpsDataList): raise Exception("Reference data for imputation doesn't have equal chromosome number.") for i, snpsd in enumerate(self.snpsDataList): snpsd.inpute_data_region(reference_data.snpsDataList[i]) def get_snps(self, random_fraction=None, cache=False): if cache: try: return self.snps except Exception: pass snplist = [] if random_fraction: import random for snpsd in self.snpsDataList: for snp in snpsd.snps: if random.random() < random_fraction: snplist.append(snp) else: for snpsd in self.snpsDataList: snplist.extend(snpsd.snps) if cache: self.snps = snplist return snplist def getSnps(self, random_fraction=None): return self.get_snps(random_fraction=None) def num_snps(self): num_snps = 0 for snpsd in self.snpsDataList: num_snps += len(snpsd.snps) return num_snps def plot_tree(self, tree_file, verbose=True, kinship_method='ibs'): if verbose: print "Calculating kinship matrix" if kinship_method == 'ibs': K = self.get_ibs_kinship_matrix() if kinship_method == 'ibd': K = self.get_ibd_kinship_matrix() plot_tree(K, tree_file, self.accessions, verbose=verbose) def plot_snp_map(self, chromosome, position, pdf_file=None, png_file=None, map_type='global', color_by=None, cmap=None, title='', eid=None): """ Plot accessions on a map. 'color_by' is by default set to be the phenotype values. """ import phenotypeData as pd import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt # matplotlib.rcParams['backend'] = 'GTKAgg' if eid == None: eid = pd.get_ecotype_id_info_dict() lats = [] lons = [] acc_names = [] for e in self.accessions: r = eid[int(e)] acc_names.append(r[0]) try: latitude = float(r[2]) longitude = float(r[3]) # r = eid[str(e)] # latitude = float(r[5]) # longitude = float(r[6]) except Exception, err_str: print "Latitude and Longitude, not found?:", err_str print 'Placing them in the Atlantic.' latitude = 40 longitude = -20 lats.append(latitude) lons.append(longitude) from mpl_toolkits.basemap import Basemap import numpy as np from pylab import cm if map_type == "global2": plt.figure(figsize=(14, 12)) m = Basemap(width=21.e6, height=21.e6, projection='gnom', lat_0=76, lon_0=15) m.drawparallels(np.arange(20, 90, 20)) m.drawmeridians(np.arange(-180, 180, 30)) elif map_type == 'global': plt.figure(figsize=(16, 4)) plt.axes([0.02, 0.02, 0.96, 0.96]) m = Basemap(projection='cyl', llcrnrlat=10, urcrnrlat=80, llcrnrlon= -130, urcrnrlon=150, lat_ts=20, resolution='c') m.drawparallels(np.arange(20, 90, 20)) m.drawmeridians(np.arange(-180, 180, 30)) elif map_type == 'europe': plt.figure(figsize=(8, 6)) plt.axes([0.02, 0.02, 0.96, 0.96]) m = Basemap(projection='cyl', llcrnrlat=35, urcrnrlat=70, llcrnrlon= -15, urcrnrlon=40, lat_ts=20, resolution='h') m.drawparallels(np.arange(30, 80, 10)) m.drawmeridians(np.arange(-20, 100, 10)) # m.bluemarble() elif map_type == 'sweden': plt.figure(figsize=(2.4, 4)) plt.axes([0.02, 0.02, 0.96, 0.96]) m = Basemap(projection='merc', llcrnrlat=55, urcrnrlat=67, llcrnrlon=10, urcrnrlon=25, lat_ts=10, resolution='i') m.drawparallels(np.arange(45, 75, 5)) m.drawmeridians(np.arange(5, 30, 5)) # m.bluemarble() else: raise Exception("map_type is invalid") # m.drawmapboundary(fill_color='aqua') m.drawcoastlines() m.fillcontinents() m.drawcountries() # m.fillcontinents(color='green', lake_color='blue') xs = [] ys = [] for lon, lat in zip(lons, lats): x, y = m(*np.meshgrid([lon], [lat])) xs.append(float(x)) ys.append(float(y)) if not color_by: color_vals = self.get_snp_at(chromosome, position) else: color_vals = color_by assert len(color_vals) == len(self.accessions), "accessions and color_by_vals values don't match ! " if not cmap: num_colors = len(set(color_vals)) if num_colors <= 10: cmap = cm.get_cmap('jet', num_colors) else: cmap = cm.get_cmap('jet') lws = [0] * len(xs) plt.scatter(xs, ys, s=10, linewidths=lws, c=color_vals, cmap=cmap, alpha=0.7, zorder=2) # plt.plot(xs, ys, 'o', color='r', alpha=0.5, zorder=2,) if title: plt.title(title) if pdf_file: plt.savefig(pdf_file, format="pdf", dpi=400) if png_file: plt.savefig(png_file, format="png", dpi=400) if not pdf_file and not png_file: plt.show() return self.accessions, lats, lons # def get_snps(self, random_fraction=None, region=None): # snplist = [] # if random_fraction: # import random # for snpsd in self.snpsDataList: # for snp in snpsd.snps: # if random.random() < random_fraction: # snplist.append(snp) # elif region: # chrom, start_pos, end_pos = region # snpsd = self.snpsDataList[chrom - 1] # ps_gen = izip(snpsd.positions, snpsd.snps) # p, s = ps_ge.next() # while p < start_pos: # p, s = ps_ge.next() # #Now found # while p < end_pos: # snplist.append(s) # pos_list = [] # p, s = ps_ge.next() # # else: # for snpsd in self.snpsDataList: # snplist += snpsd.snps # return snplist def get_snp_at(self, chromosome, position): """ Returns the SNP at the given position, if it exits. """ c_i = self.chromosomes.index(chromosome) sd = self.snpsDataList[c_i] i = 0 while sd.positions[i] < position: i += 1 if sd.positions[i] == position: print 'Found the SNP.' return sd.snps[i] else: print "Didn't find the SNP on chromosome %d, at position %d" % (chromosome, position) return None def get_positions(self): poslist = [] for snpsd in self.snpsDataList: for pos in snpsd.positions: poslist.append(pos) return poslist def getPositions(self): return self.get_positions() def get_top_correlated_snp(self, snp, r2_threshold=0.5): sample_snp_chr_pos_marf = [] sample_r2s = [] print_r2s = [] print_snp_chr_pos_marf = [] for snpsd, chromosome in zip(self.snpsDataList, self.chromosomes): marfs = snpsd.get_mafs()['marfs'] r2s = snpsd.calc_r2_with_snp(snp) for r2, sample_snp, sample_snp_pos, marf in zip(r2s, snpsd.snps, snpsd.positions, marfs): if r2 > r2_threshold: sample_r2s.append(r2) sample_snp_chr_pos_marf.append((sample_snp, chromosome, sample_snp_pos, marf)) if r2 > 0.1: print_r2s.append(r2) print_snp_chr_pos_marf.append((sample_snp, chromosome, sample_snp_pos, marf)) l = zip(print_r2s, print_snp_chr_pos_marf) l.sort() print l[-10:] return sample_snp_chr_pos_marf def get_all_snp_w_info(self): """ Returns the SNPs along with some info.. """ sample_snp_chr_pos_marf = [] for snpsd, chromosome in zip(self.snpsDataList, self.chromosomes): marfs = snpsd.get_mafs()['marfs'] sample_snp_chr_pos_marf += zip(snpsd.snps, [chromosome] * len(snpsd.snps), snpsd.positions, marfs) return sample_snp_chr_pos_marf def get_chr_pos_list(self, cache_list=False): if cache_list: try: chr_pos_list = self.chr_pos_list if len(chr_pos_list) > 0: return chr_pos_list else: raise Exception except Exception: pass chr_pos_list = [] for chrom, snpsd in izip(self.chromosomes, self.snpsDataList): chr_pos_list += zip([chrom] * len(snpsd.positions), snpsd.positions) if cache_list: self.chr_pos_list = chr_pos_list return chr_pos_list def getChrPosList(self): return self.get_chr_pos_list() def get_chr_list(self): chr_list = [] for c, snpsd in izip(self.chromosomes, self.snpsDataList): chr_list.extend([c] * len(snpsd.positions)) return chr_list def get_chromosome_ends(self): chr_ends = [] for snpsd in self.snpsDataList: chr_ends.append(snpsd.positions[-1]) return chr_ends def get_genome_length(self): return sum(self.get_chromosome_ends()) def get_mafs(self): """ Returns the mafs and marfs as a dictionary. types: classes, diploid_ints """ maf_list = [] marf_list = [] for snpsd in self.snpsDataList: r = snpsd.get_mafs(type=self.data_format) maf_list.extend(r["mafs"]) marf_list.extend(r["marfs"]) print "Finished calculating MAFs." return {"mafs":maf_list, "marfs":marf_list} def get_chr_pos_snp_list(self): chr_pos_snp_list = [] for i in range(0, len(self.snpsDataList)): snpsd = self.snpsDataList[i] chr = i + 1 for j in range(0, len(snpsd.positions)): pos = snpsd.positions[j] snp = snpsd.snps[j] chr_pos_snp_list.append((chr, pos, snp)) return chr_pos_snp_list def getChrPosSNPList(self): return self.get_chr_pos_snp_list() def get_region_pos_snp_dict(self, chromosome, start_pos=None, end_pos=None): """ Returns a dict containing a list of positions and snps. """ positions = [] snps = [] for snpsd in self.snpsDataList: if snpsd.chromosome == chromosome: break assert snpsd.chromosome == chromosome, "SNPs data with appropriate chromosomes wasn't found" i = 0 while i < len(snpsd.positions) and snpsd.positions[i] < start_pos: i += 1 if end_pos: while i < len(snpsd.positions) and snpsd.positions[i] < end_pos: positions.append(snpsd.positions[i]) snps.append(snpsd.snps[i]) i += 1 else: positions = snpsd.positions[i:] snps = snpsd.snps[i:] return {'positions':positions, 'snps':snps} def get_cand_genes_snp_priors(self, cand_genes, radius=10000, num_exp_causal=1.0, cg_prior_fold_incr=50.0, method_type='sum_all_priors'): """ Returns SNP priors """ chr_pos_list = self.getChrPosList() num_snps = float(len(chr_pos_list)) i = 0 gene_chr_pos_list = sorted([(int(gene.chromosome), gene.startPos, gene.endPos) for gene in cand_genes]) num_cgs = len(gene_chr_pos_list) cg_snp_indices = [] for gene_chr, gene_start_pos, gene_end_pos in gene_chr_pos_list: start_i = bisect.bisect(chr_pos_list, (gene_chr, gene_start_pos - radius - 1)) stop_i = bisect.bisect(chr_pos_list, (gene_chr, gene_end_pos + radius + 1)) cg_snp_indices.extend(range(start_i, stop_i)) cg_snp_indices = sorted(list(set(cg_snp_indices))) if method_type == 'sum_all_priors': pi_0 = num_exp_causal / num_snps # Basis prior pi_1 = pi_0 * cg_prior_fold_incr # Cand. gene prior elif method_type == 'sum_base_priors': pi_0 = num_exp_causal / (num_snps - num_cgs + cg_prior_fold_incr * num_cgs) # Basis prior pi_1 = pi_0 * cg_prior_fold_incr # Cand. gene prior else: raise NotImplementedError snp_priors = sp.repeat(pi_0, num_snps) for i in cg_snp_indices: snp_priors[i] = pi_1 print max(snp_priors), min(snp_priors) return snp_priors.tolist() def get_snp_priors(self, cpp_list=None, cand_genes=None, radius=25000, num_exp_causal=10.0, cg_prior_fold_incr=10): """ Takes a list of SNPs/markers with some priors, and extrapolates that to the SNPs in the data. """ cpp_list.sort() l = map(list, zip(*cpp_list)) priors = l[2] cp_list = self.getChrPosList() snp_priors = [] snp_i = 0 p_i = 0 if cpp_list != None: # Do chromosome by chromosome.. for chrom in [1, 2, 3, 4, 5]: p_i = bisect.bisect(cpp_list, (chrom, 0, 0)) snp_i = 0 positions = self.snpsDataList[chrom - 1].positions num_snps = len(positions) pos = positions[snp_i] chrom_1, pos_1, prior_1 = cpp_list[p_i] chrom_2, pos_2, prior_2 = cpp_list[p_i + 1] while snp_i < num_snps and p_i < len(cpp_list) - 2 and chrom_2 == chrom: chrom_1, pos_1, prior_1 = cpp_list[p_i] chrom_2, pos_2, prior_2 = cpp_list[p_i + 1] if chrom_2 == chrom: while snp_i < num_snps - 1 and pos <= pos_1: snp_priors.append(prior_1) snp_i += 1 pos = positions[snp_i] while snp_i < num_snps - 1 and pos_1 < pos <= pos_2: d = pos_2 - pos_1 s = (pos - pos_1) / float(d) snp_priors.append(prior_1 * (1 - s) + prior_2 * s) snp_i += 1 pos = positions[snp_i] p_i += 1 chrom_1, pos_1, prior_1 = cpp_list[p_i] chrom_2, pos_2, prior_2 = cpp_list[p_i + 1] if chrom_2 != chrom: # The chromosome is ending while snp_i < num_snps: snp_priors.append(prior_1) snp_i += 1 elif p_i >= len(cpp_list) - 2: # It's finishing while snp_i < num_snps: snp_priors.append(prior_2) snp_i += 1 snp_priors = sp.array(snp_priors) snp_priors = 1000 * (snp_priors - snp_priors.min()) / (snp_priors.max() - snp_priors.min()) + 1 else: snp_priors = sp.repeat(1.0, self.num_snps()) if cand_genes != None: print 'Now for candidate genes' chr_pos_list = self.getChrPosList() num_snps = len(chr_pos_list) i = 0 gene_chr_pos_list = sorted([(int(gene.chromosome), gene.startPos, gene.endPos) for gene in cand_genes]) print gene_chr_pos_list num_cgs = len(gene_chr_pos_list) cg_snp_indices = [] for gene_chr, gene_start_pos, gene_end_pos in gene_chr_pos_list: start_i = bisect.bisect(chr_pos_list, (gene_chr, gene_start_pos - radius - 1)) stop_i = bisect.bisect(chr_pos_list, (gene_chr, gene_end_pos + radius + 1)) cg_snp_indices.extend(range(start_i, stop_i)) cg_snp_indices = sorted(list(set(cg_snp_indices))) snp_priors[cg_snp_indices] = snp_priors[cg_snp_indices] * cg_prior_fold_incr snp_priors = (num_exp_causal * snp_priors / sum(snp_priors)).tolist() print max(snp_priors), min(snp_priors) return snp_priors # def get_pc(self, pc_num=1, random_fraction=0.1): # """ # Returns the pc_num'th principal components of the genotype # """ # import random # import rpy, util # # if not self.is_binary: # print "Converting the snps data to binary format." # self.convert_2_binary() # # snps = [] # for sd in self.snpsDataList: # snps.extend(random.sample(sd.snps, int(random_fraction * len(sd.snps)))) # genotypes = map(list, zip(*snps)) # # # for genotype in genotypes: # sd = util.calcSD(genotype) # for j in range(len(genotype)): # genotype[j] = genotype[j] / sd # # genotypes = sp.transpose(sp.array(genotypes)) # #print genotypes # pc = rpy.r.princomp(genotypes) # pc_sorted = zip(list(pc["scores"][pc_num - 1]), self.accessions) # pc_sorted.sort() # print pc_sorted # pc = list(pc["scores"][pc_num - 1]) # self.pc = pc # return pc def updateRegions(self, regionList): """ Deprecated 11/11/08 - Bjarni """ c_i = 0 i = 0 rl_i = 0 # region list index while c_i < len(self.chromosomes) and rl_i < len(regionList): region = regionList[rl_i] snpsd = self.snpsDataList[c_i] cp1 = (c_i + 1, snpsd.positions[i]) cp_start = (region.chromosome, region.startPos) while cp1 < cp_start: if i < len(snpsd.positions): i += 1 else: c_i += 1 snpsd = self.snpsDataList[c_i] i = 0 cp1 = (c_i + 1, snpsd.positions[i]) cp_end = (region.chromosome, region.endPos) while cp1 <= cp_end: """Update current region!""" region.snps.append(snpsd.snps[i]) region.snps_indices.append((c_i, i)) i += 1 if i < len(snpsd.positions): cp1 = (c_i + 1, snpsd.positions[i]) else: c_i += 1 i = 0 break rl_i += 1 def filter_na_snps(self, max_na_rate=0.0): for snpsd in self.snpsDataList: snpsd.filter_na_snps(max_na_rate=max_na_rate) def remove_snps_indices(self, indices_to_remove): remove_indices = [[] for i in range(len(self.snpsDataList))] indices_to_remove.sort() offset = 0 i = 0 for snpsd_i, snpsd in enumerate(self.snpsDataList): max_i = offset + len(snpsd.snps) i2r = indices_to_remove[i] while i < len(indices_to_remove) and i2r < max_i: remove_indices[snpsd_i].append(i2r - offset) i += 1 i2r = indices_to_remove[i] offset = max_i for i, snpsd in enumerate(self.snpsDataList): snpsd.remove_snps(remove_indices[i]) def filter_na_accessions(self, max_na_rate=0.2, verbose=False): accessions_na_counts = [0.0 for acc in self.accessions] total_snps = 0 for snpsd in self.snpsDataList: for i, c in enumerate(snpsd.countMissingSnps()[1]): accessions_na_counts[i] += c total_snps += float(len(snpsd.snps)) accessions_na_counts = [accessions_na_counts[i] / total_snps for i in range(len(accessions_na_counts))] # print accessions_na_counts acc_to_keep = [] for i, na_rate in enumerate(accessions_na_counts): if na_rate <= max_na_rate: acc_to_keep.append(self.accessions[i]) # print len(acc_to_keep) self.filter_accessions(acc_to_keep) def filter_maf_snps(self, maf, maf_ub=1): for snpsd in self.snpsDataList: snpsd.snpsFilterMAF([maf, maf_ub], type=self.data_format) def filter_mac_snps(self, mac_threshold=15): for snpsd in self.snpsDataList: snpsd.filter_mac(mac_threshold, data_format=self.data_format) def filter_monomorphic_snps(self): n_filtered_snps = 0 for snpsd in self.snpsDataList: n_filtered_snps += snpsd.filterMonoMorphicSnps() return n_filtered_snps def filter_snps(self, snps_to_keep): """ Filter snps, leaving the snps in the given order. """ assert len(snps_to_keep) != 0, "Can't remove all snps." for i, snps in enumerate(snps_to_keep): snps_indices_to_keep = [] for snp in snps: snps_indices_to_keep.append(bisect.bisect(self.snpsDataList[i].positions, snp) - 1) self.snpsDataList[i].filter_snp_indices(snps_indices_to_keep) def filter_accessions(self, accessions_to_keep): """ Filter accessions, leaving the remaining accession in the given order. """ assert len(accessions_to_keep) != 0, "Can't remove all ecotypes." ecotypes = accessions_to_keep acc_indices_to_keep = [] for et in ecotypes: try: i = self.accessions.index(et) acc_indices_to_keep.append(i) except: continue # pdb.set_trace() # acc_indices_to_keep.sort() self.filter_accessions_indices(acc_indices_to_keep) def filter_accessions_indices(self, acc_indices_to_keep): num_accessions = len(self.accessions) for i, snpsd in enumerate(self.snpsDataList): # print i, len(snpsd.accessions) snpsd.removeAccessionIndices(acc_indices_to_keep) self.accessions = self.snpsDataList[0].accessions self.array_ids = self.snpsDataList[0].arrayIds print "Removed %d accessions, leaving %d in total." % (num_accessions - len(acc_indices_to_keep), len(acc_indices_to_keep)) def filter_for_countries(self, country_codes, complement=False): import phenotypeData as pd ei_dict = pd.get_ecotype_id_info_dict() acc_indices_to_keep = [] if complement: for i, ei in enumerate(self.accessions): if ei_dict[int(ei)][4] not in country_codes: acc_indices_to_keep.append(i) else: for i, ei in enumerate(self.accessions): if ei_dict[int(ei)][4] in country_codes: acc_indices_to_keep.append(i) self.filter_accessions_indices(acc_indices_to_keep) for ei in self.accessions: print ei, ei_dict[int(ei)] def sample_snps(self, random_fraction, seed=None): """ Samples a random fraction of the SNPs. """ for snpsd in self.snpsDataList: snpsd.sample_snps(random_fraction, seed=seed) def get_region_snpsd(self, chr, start_pos=None, end_pos=None): """ Modifies original object, beware! """ c_i = self.chromosomes.index(chr) print chr, start_pos, end_pos snpsd = self.snpsDataList[c_i] if start_pos != None: new_snps = [] new_positions = [] i = 0 while i < len(snpsd.positions) - 1 and snpsd.positions[i] < start_pos: i += 1 while i < len(snpsd.positions) - 1 and snpsd.positions[i] < end_pos: new_snps.append(snpsd.snps[i]) new_positions.append(snpsd.positions[i]) i += 1 snpsd.positions = new_positions snpsd.snps = new_snps return snpsd def merge_snps_data(self, sd, acc_merge_type='intersection', error_threshold=0.1, discard_error_threshold=0.1): """ Merges data using _SnpsData_.merge_data """ if self.chromosomes != sd.chromosomes: raise Exception else: self.new_snps_data_list = [] for sd1, sd2, chromosome in zip(self.snpsDataList, sd.snpsDataList, self.chromosomes): print "Merging data on chromosome %s." % (str(chromosome)) sd1.merge_data(sd2, acc_merge_type=acc_merge_type, error_threshold=error_threshold, discard_error_threshold=discard_error_threshold) self.new_snps_data_list.append(sd1) self.accessions = self.new_snps_data_list[0].accessions self.snpsDataList = self.new_snps_data_list def plot_tree(K, tree_file, ets, verbose=True, label_values=None): import scipy.cluster.hierarchy as hc import pylab import phenotypeData e_dict = phenotypeData.get_ecotype_id_info_dict() # print e_dict labels = [] for et_i, et in enumerate(ets): try: s1 = unicode(e_dict[int(et)][0], 'iso-8859-1') if label_values != None: s2 = unicode(' %s' % str(label_values[et_i])) else: s2 = unicode('(%0.1f,%0.1f)' % (e_dict[int(et)][2], e_dict[int(et)][3])) s = s1 + s2 except Exception, err_s: print err_s s = str(et) labels.append(s) if verbose: print "Plotting tree for SNPs:" Z = hc.average(K) pylab.figure(figsize=(24, 15)) pylab.axes([0.03, 0.08, 0.96, 0.91]) dend_dict = hc.dendrogram(Z, leaf_font_size=7, labels=labels) xmin, xmax = pylab.xlim() xrange = xmax - xmin ymin, ymax = pylab.ylim() yrange = ymax - ymin pylab.axis([xmin - 0.01 * xrange, xmax + 0.01 * xrange, ymin - 0.02 * yrange, ymax + 0.02 * yrange]) pylab.savefig(tree_file, format='pdf') pylab.clf() if verbose: print "Done plotting tree, saved in file:", tree_file, "\n" def construct_snps_data_set(snps, positions, chromosomes, indiv_ids, data_format='binary'): """ Assumes the SNPs are sorted by chromosome and position. """ last_i = 0 snpsds = [] chrom_list = list(set(chromosomes)) chrom_list.sort() for chrom in chrom_list[:-1]: i = bisect.bisect(chromosomes, chrom) snpsds.append(SNPsData(snps=snps[last_i:i], positions=positions[last_i:i], chromosome=chrom, accessions=indiv_ids)) last_i = i assert snps.dtype == sp.dtype('int8'), "Type doesn't match the data format." snpsds.append(SNPsData(snps=snps[last_i:], positions=positions[last_i:], chromosome=chrom_list[-1], accessions=indiv_ids)) return SNPsDataSet(snpsds, chrom_list, data_format=data_format) if __name__ == "__main__": pass
mit
digitaluzu/nimble-bookmarks
neat.js
57479
/* jshint unused: true, undef: true */ /* global window, document, localStorage, $, $each, setTimeout, screen, clearInterval */ window.addEventListener('load', init, false); function init() { if (localStorage.popupHeight) document.body.style.height = localStorage.popupHeight + 'px'; if (localStorage.popupWidth) document.body.style.width = localStorage.popupWidth + 'px'; } (function(window) { var document = window.document; var chrome = window.chrome; var localStorage = window.localStorage; var navigator = window.navigator; var body = document.body; var _m = chrome.i18n.getMessage; // Error alert var AlertDialog = { open: function(dialog) { if (!dialog) return; $('alert-dialog-text').innerHTML = dialog; body.addClass('needAlert'); }, close: function() { body.removeClass('needAlert'); } }; // popdown toast when an error occurs window.addEventListener('error', function() { AlertDialog.open('<strong>' + _m('errorOccured') + '</strong><br>' + _m('reportedToDeveloper')); }, false); // Platform detection var os = (navigator.platform.toLowerCase().match(/mac|win|linux/i) || ['other'])[0]; body.addClass(os); // Some i18n $('edit-dialog-name').placeholder = _m('name'); $('edit-dialog-url').placeholder = _m('url'); $('hotkey-dialog-hotkey').placeholder = _m('hotkey'); $each({ 'bookmark-new-tab': 'openNewTab', 'bookmark-new-window': 'openNewWindow', 'bookmark-new-incognito-window': 'openIncognitoWindow', 'bookmark-edit': 'edit', 'bookmark-update': 'updateEllipsis', 'bookmark-delete': 'deleteEllipsis', 'bookmark-set-hotkey': 'setHotkeyEllipsis', 'bookmark-unset-hotkey': 'unsetHotkey', 'folder-window': 'openBookmarks', 'folder-new-window': 'openBookmarksNewWindow', 'folder-new-incognito-window': 'openBookmarksIncognitoWindow', 'folder-edit': 'edit', 'folder-delete': 'deleteEllipsis', 'edit-dialog-button': 'save', 'hotkey-dialog-button': 'save' }, function(msg, id) { var el = $(id), m = _m(msg); if (el.tagName == 'COMMAND') el.label = m; el.textContent = m; }); // RTL indicator var rtl = (body.getComputedStyle('direction') == 'rtl'); if (rtl) body.addClass('rtl'); // Init some variables var opens = localStorage.opens ? JSON.parse(localStorage.opens) : []; var rememberState = !localStorage.dontRememberState; var httpsPattern = /^https?:\/\//i; // Hotkey-related functions. var hotkeys = localStorage.hotkeys ? JSON.parse(localStorage.hotkeys) : {}; function setHotkey(id, hotkey) { hotkeys[id] = hotkey; localStorage.hotkeys = JSON.stringify(hotkeys); } function unsetHotkey(id) { if (id in hotkeys) { delete hotkeys[id]; localStorage.hotkeys = JSON.stringify(hotkeys); } } function getHotkey(id) { if (hotkeys.hasOwnProperty(id)) { return hotkeys[id]; } else { return ''; } } function getHotkeyId(hotkey) { for (var id in hotkeys) { if (hotkeys.hasOwnProperty(id)) { if (hotkeys[id] === hotkey) { return id; } } } return null; } function setHotkeyText(id, hotkey) { var li = $('neat-tree-item-' + id); var a = li.querySelector('a'); var em = a.querySelector('em'); // Create element if it doesn't exist. if (!em) { em = document.createElement('em'); em.addClass('hotkey'); a.insertBefore(em, a.firstChild); } em.textContent = '[' + hotkey + ']'; } function unsetHotkeyText(id) { var li = $('neat-tree-item-' + id); var a = li.querySelector('a'); var em = a.querySelector('em'); if (em) { a.removeChild(em); } } function refreshHotkeyText() { for (var id in hotkeys) { if (hotkeys.hasOwnProperty(id)) { setHotkeyText(id, hotkeys[id]); } } } // Adaptive bookmark tooltips var adaptBookmarkTooltips = function() { var bookmarks = document.querySelectorAll('li.child a'); for (var i = 0, l = bookmarks.length; i < l; i++) { var bookmark = bookmarks[i]; if (bookmark.hasClass('titled')) { if (bookmark.scrollWidth <= bookmark.offsetWidth) { bookmark.title = bookmark.href; bookmark.removeClass('titled'); } } else if (bookmark.scrollWidth > bookmark.offsetWidth) { var text = bookmark.querySelector('i').textContent; var title = bookmark.title; if (text != title) { bookmark.title = text + '\n' + title; bookmark.addClass('titled'); } } } }; var generateBookmarkHTML = function(title, url, extras) { if (!extras) extras = ''; var u = url.htmlspecialchars(); var favicon = 'chrome://favicon/' + u; var tooltipURL = url; if (/^javascript:/i.test(url)) { if (url.length > 140) tooltipURL = url.slice(0, 140) + '...'; favicon = 'images/document-code.png'; } tooltipURL = tooltipURL.htmlspecialchars(); var name = title.htmlspecialchars() || (httpsPattern.test(url) ? url.replace(httpsPattern, '') : _m('noTitle')); return '<a href="' + u + '"' + ' title="' + tooltipURL + '" tabindex="0" ' + extras + '>' + '<img src="' + favicon + '" width="16" height="16" alt=""><i>' + name + '</i>' + '</a>'; }; var generateHTML = function(data, level) { if (!level) level = 0; var paddingStart = 14 * level; var group = (level === 0) ? 'tree' : 'group'; var html = '<ul role="' + group + '" data-level="' + level + '">'; var getBookmarks = function(_id) { chrome.bookmarks.getChildren(_id, function(children) { var html = generateHTML(children, level + 1); var div = document.createElement('div'); div.innerHTML = html; var ul = div.querySelector('ul'); ul.inject($('neat-tree-item-' + _id)); div.destroy(); }); }; for (var i = 0, l = data.length; i < l; i++) { var d = data[i]; var children = d.children; var title = d.title.htmlspecialchars(); var url = d.url; var id = d.id; var parentID = d.parentId; var idHTML = id ? ' id="neat-tree-item-' + id + '"' : ''; var isFolder = d.dateGroupModified || children || typeof url == 'undefined'; if (isFolder) { var isOpen = false; var open = ''; if (rememberState) { isOpen = opens.contains(id); if (isOpen) open = ' open'; } html += '<li class="parent' + open + '"' + idHTML + ' role="treeitem" aria-expanded="' + isOpen + '" data-parentid="' + parentID + '">' + '<span tabindex="0" style="-webkit-padding-start: ' + paddingStart + 'px"><b class="twisty"></b>' + '<img src="images/folder.png" width="16" height="16" alt=""><i>' + (title || _m('noTitle')) + '</i>' + '</span>'; if (isOpen) { if (children) { html += generateHTML(children, level + 1); } else { getBookmarks(id); } } } else { html += '<li class="child"' + idHTML + ' role="treeitem" data-parentid="' + parentID + '">' + generateBookmarkHTML(title, url, 'style="-webkit-padding-start: ' + paddingStart + 'px"'); } html += '</li>'; } html += '</ul>'; return html; }; var $tree = $('tree'); chrome.bookmarks.getTree(function(tree) { var html = generateHTML(tree[0].children); $tree.innerHTML = html; refreshHotkeyText(); // Automatically give focus to the first folder. var firstChild = $tree.querySelector('li:first-child>span'); if (firstChild) { firstChild.focus(); } setTimeout(adaptBookmarkTooltips, 100); tree = null; }); // Events for the tree $tree.addEventListener('scroll', function() { localStorage.scrollTop = $tree.scrollTop; // store scroll position at each scroll event }); var closeUnusedFolders = localStorage.closeUnusedFolders; $tree.addEventListener('click', function(e) { if (e.button !== 0) return; var el = e.target; var tagName = el.tagName; if (tagName != 'SPAN') return; if (e.shiftKey || e.ctrlKey) return; var parent = el.parentNode; parent.toggleClass('open'); var expanded = parent.hasClass('open'); parent.setAttribute('aria-expanded', expanded); var children = parent.querySelector('ul'); if (!children) { var id = parent.id.replace('neat-tree-item-', ''); chrome.bookmarks.getChildren(id, function(children) { var html = generateHTML(children, parseInt(parent.parentNode.dataset.level) + 1); var div = document.createElement('div'); div.innerHTML = html; var ul = div.querySelector('ul'); ul.inject(parent); div.destroy(); refreshHotkeyText(); setTimeout(adaptBookmarkTooltips, 100); }); } if (closeUnusedFolders && expanded) { var siblings = parent.getSiblings('li'); for (var i = 0, l = siblings.length; i < l; i++) { var li = siblings[i]; if (li.hasClass('parent')) { li.removeClass('open').setAttribute('aria-expanded', false); } } } var opens = $tree.querySelectorAll('li.open'); opens = Array.map(function(li) { return li.id.replace('neat-tree-item-', ''); }, opens); localStorage.opens = JSON.stringify(opens); }); // Force middle clicks to trigger the focus event $tree.addEventListener('mouseup', function(e) { if (e.button != 1) return; var el = e.target; var tagName = el.tagName; if (tagName != 'A' && tagName != 'SPAN') return; el.focus(); }); // Popup auto-height var resetHeight = function() { setTimeout(function() { var neatTree = $tree.firstElementChild; if (neatTree) { var fullHeight = neatTree.offsetHeight + $tree.offsetTop + 6; // Slide up faster than down body.style.webkitTransitionDuration = (fullHeight < window.innerHeight) ? '.3s' : '.1s'; var maxHeight = screen.height - window.screenY - 50; var height = Math.max(0, Math.min(fullHeight, maxHeight)); body.style.height = height + 'px'; localStorage.popupHeight = height; } }, 100); }; resetHeight(); $tree.addEventListener('click', resetHeight); $tree.addEventListener('keyup', resetHeight); // Confirm dialog event listeners $('confirm-dialog-button-1').addEventListener('click', function() { ConfirmDialog.fn1(); ConfirmDialog.close(); }, false); $('confirm-dialog-button-2').addEventListener('click', function() { ConfirmDialog.fn2(); ConfirmDialog.close(); }, false); // Confirm dialog var ConfirmDialog = { open: function(opts) { if (!opts) return; $('confirm-dialog-text').innerHTML = opts.dialog.widont(); $('confirm-dialog-button-1').innerHTML = opts.button1; $('confirm-dialog-button-2').innerHTML = opts.button2; if (opts.fn1) ConfirmDialog.fn1 = opts.fn1; if (opts.fn2) ConfirmDialog.fn2 = opts.fn2; $('confirm-dialog-button-' + (opts.focusButton || 1)).focus(); document.body.addClass('needConfirm'); }, close: function() { document.body.removeClass('needConfirm'); }, fn1: function() {}, fn2: function() {} }; // Edit dialog event listener $('edit-dialog').addEventListener('submit', function(e) { EditDialog.close(); e.preventDefault(); }, false); // Edit dialog var EditDialog = window.EditDialog = { open: function(opts) { if (!opts) return; $('edit-dialog-text').innerHTML = opts.dialog.widont(); if (opts.fn) EditDialog.fn = opts.fn; var type = opts.type || 'bookmark'; var name = $('edit-dialog-name'); name.value = opts.name; name.focus(); name.select(); name.scrollLeft = 0; // very delicate, show first few words instead of last var url = $('edit-dialog-url'); if (type == 'bookmark') { url.style.display = ''; url.disabled = false; url.value = opts.url; } else { url.style.display = 'none'; url.disabled = true; url.value = ''; } body.addClass('needEdit'); }, close: function() { var urlInput = $('edit-dialog-url'); var url = urlInput.value; if (!urlInput.validity.valid) { urlInput.value = 'http://' + url; if (!urlInput.validity.valid) url = ''; // if still invalid, forget it. url = 'http://' + url; } EditDialog.fn($('edit-dialog-name').value, url); EditDialog.closeNoSave(); }, closeNoSave: function() { body.removeClass('needEdit'); }, fn: function() {} }; // Hotkey dialog event listener $('hotkey-dialog').addEventListener('submit', function(e) { HotkeyDialog.close(); e.preventDefault(); }, false); // Hotkey input validation. $('hotkey-dialog-hotkey').onkeypress = function(e) { var key; if (e.keyCode) key = e.keyCode; else if (e.which) key = e.which; // Allow enter, backspace... if (key === 13 || key === 8) { return true; } if (/[^A-Za-z0-9]/.test(String.fromCharCode(key))) { return false; } return true; }; // Hotkey dialog var HotkeyDialog = window.HotkeyDialog = { open: function(opts) { if (!opts) return; $('hotkey-dialog-text').innerHTML = opts.dialog.widont(); if (opts.fn) HotkeyDialog.fn = opts.fn; var name = $('hotkey-dialog-name'); name.value = opts.name; name.disabled = true; name.scrollLeft = 0; // very delicate, show first few words instead of last var hotkey = $('hotkey-dialog-hotkey'); hotkey.disabled = false; hotkey.value = opts.hotkey; hotkey.focus(); hotkey.select(); body.addClass('needSetHotkey'); }, close: function() { var hotkeyInput = $('hotkey-dialog-hotkey'); var hotkey = hotkeyInput.value.toLowerCase(); HotkeyDialog.fn(hotkey); HotkeyDialog.closeNoSave(); }, closeNoSave: function() { body.removeClass('needSetHotkey'); }, fn: function() {} }; // Bookmark handling var dontConfirmOpenFolder = !!localStorage.dontConfirmOpenFolder; var openBookmarksLimit = 5; var actions = { openBookmark: function(url) { chrome.tabs.getSelected(null, function(tab) { var decodedURL; try { decodedURL = decodeURIComponent(url); } catch (e) { return; } chrome.tabs.update(tab.id, { url: decodedURL }); setTimeout(window.close, 200); }); }, openBookmarkNewTab: function(url, selected, blankTabCheck) { var open = function() { chrome.tabs.create({ url: url, selected: selected }); }; if (blankTabCheck) { chrome.tabs.getSelected(null, function(tab) { if (/^chrome:\/\/newtab/i.test(tab.url)) { chrome.tabs.update(tab.id, { url: url }); setTimeout(window.close, 200); } else { open(); } }); } else { open(); } }, openBookmarkNewWindow: function(url, incognito) { chrome.windows.create({ url: url, incognito: incognito }); }, openBookmarks: function(li, urls, selected) { var urlsLen = urls.length; var open = function() { chrome.tabs.create({ url: urls.shift(), selected: selected // first tab will be selected }); for (var i = 0, l = urls.length; i < l; i++) { chrome.tabs.create({ url: urls[i], selected: false }); } }; if (!dontConfirmOpenFolder && urlsLen > openBookmarksLimit) { ConfirmDialog.open({ dialog: _m('confirmOpenBookmarks', '' + urlsLen), button1: '<strong>' + _m('open') + '</strong>', button2: _m('nope'), fn1: open, fn2: function() { li.querySelector('a, span').focus(); } }); } else { open(); } }, openBookmarksNewWindow: function(li, urls, incognito) { var urlsLen = urls.length; var open = function() { chrome.windows.create({ url: urls, incognito: incognito }); }; if (!dontConfirmOpenFolder && urlsLen > openBookmarksLimit) { var dialog = incognito ? _m('confirmOpenBookmarksNewIncognitoWindow', '' + urlsLen) : _m('confirmOpenBookmarksNewWindow', '' + urlsLen); ConfirmDialog.open({ dialog: dialog, button1: '<strong>' + _m('open') + '</strong>', button2: _m('nope'), fn1: open, fn2: function() { li.querySelector('a, span').focus(); } }); } else { open(); } }, editBookmarkFolder: function(id) { chrome.bookmarks.get(id, function(nodeList) { if (!nodeList.length) return; var node = nodeList[0]; var url = node.url; var isBookmark = !!url; var type = isBookmark ? 'bookmark' : 'folder'; var dialog = isBookmark ? _m('editBookmark') : _m('editFolder'); EditDialog.open({ dialog: dialog, type: type, name: node.title, url: decodeURIComponent(url), fn: function(name, url) { chrome.bookmarks.update(id, { title: name, url: isBookmark ? url : '' }, function(n) { var title = n.title; var url = n.url; var li = $('neat-tree-item-' + id); if (li) { if (isBookmark) { var css = li.querySelector('a').style.cssText; li.innerHTML = generateBookmarkHTML(title, url, 'style="' + css + '"'); } else { var i = li.querySelector('i'); var name = title || (httpsPattern.test(url) ? url.replace(httpsPattern, '') : _m('noTitle')); i.textContent = name; } } li.firstElementChild.focus(); }); } }); }); }, updateBookmark: function(id) { chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) { var new_url = tabs[0].url; var li = $('neat-tree-item-' + id); var bookmarkName = '<cite>' + li.textContent.trim() + '</cite>'; var dialog = _m('confirmUpdateBookmark', [bookmarkName, new_url]); ConfirmDialog.open({ dialog: dialog, button1: '<strong>' + _m('update') + '</strong>', button2: _m('nope'), fn1: function() { chrome.bookmarks.update(id, { url: new_url }, function(n) { var title = n.title; var url = n.url; var css = li.querySelector('a').style.cssText; li.innerHTML = generateBookmarkHTML(title, url, 'style="' + css + '"'); li.firstElementChild.focus(); }); }, fn2: function() { li.querySelector('a, span').focus(); } }); }); }, deleteBookmark: function(id) { var li = $('neat-tree-item-' + id); var bookmarkName = '<cite>' + li.textContent.trim() + '</cite>'; var dialog = _m('confirmDeleteBookmark', [bookmarkName]); ConfirmDialog.open({ dialog: dialog, button1: '<strong>' + _m('delete') + '</strong>', button2: _m('nope'), fn1: function() { chrome.bookmarks.remove(id, function() { if (li) { var nearLi1 = li.nextElementSibling || li.previousElementSibling; li.destroy(); if (nearLi1) nearLi1.querySelector('a, span').focus(); } }); }, fn2: function() { li.querySelector('a, span').focus(); } }); }, deleteBookmarks: function(id, bookmarkCount, folderCount) { var li = $('neat-tree-item-' + id); var item = li.querySelector('span'); var dialog = ''; var folderName = '<cite>' + item.textContent.trim() + '</cite>'; if (bookmarkCount && folderCount) { dialog = _m('confirmDeleteFolderSubfoldersBookmarks', [folderName, folderCount, bookmarkCount]); } else if (bookmarkCount) { dialog = _m('confirmDeleteFolderBookmarks', [folderName, bookmarkCount]); } else if (folderCount) { dialog = _m('confirmDeleteFolderSubfolders', [folderName, folderCount]); } else { dialog = _m('confirmDeleteFolder', [folderName]); } ConfirmDialog.open({ dialog: dialog, button1: '<strong>' + _m('delete') + '</strong>', button2: _m('nope'), fn1: function() { chrome.bookmarks.removeTree(id, function() { li.destroy(); }); var nearLi = li.nextElementSibling || li.previousElementSibling; if (nearLi) nearLi.querySelector('a, span').focus(); }, fn2: function() { li.querySelector('a, span').focus(); } }); }, setHotkey: function(id, name) { HotkeyDialog.open({ dialog: _m('setHotkey'), name: name, hotkey: getHotkey(id), fn: function(hotkey) { // If not alphanumeric or is empty string... if (/[^a-z0-9]|(^$)/.test(hotkey)) { unsetHotkey(id); unsetHotkeyText(id); } else { setHotkey(id, hotkey); setHotkeyText(id, hotkey); } } }); }, unsetHotkey: function(id) { unsetHotkey(id); unsetHotkeyText(id); } }; // For performing bookmark actions via keyboard commands. var leftClickNewTab = !!localStorage.leftClickNewTab; var noOpenBookmark = false; var bookmarkHandler = function(e) { e.preventDefault(); if (e.button !== 0) return; // force left-click if (noOpenBookmark) { // flag that disables opening bookmark noOpenBookmark = false; return; } var el = e.target; var ctrlMeta = (e.ctrlKey || e.metaKey); var shift = e.shiftKey; if (el.tagName == 'A') { var url = el.href; if (ctrlMeta) { // ctrl/meta click actions.openBookmarkNewTab(url, !shift); } else { // click if (shift) { actions.openBookmarkNewWindow(url); } else { if (leftClickNewTab) { actions.openBookmarkNewTab(url, true, true); } else { actions.openBookmark(url); } } } } else if (el.tagName == 'SPAN') { var li = el.parentNode; var id = li.id.replace('neat-tree-item-', ''); chrome.bookmarks.getChildren(id, function(children) { var urls = Array.map(function(c) { return c.url; }, children).clean(); var urlsLen = urls.length; if (!urlsLen) return; if (ctrlMeta) { // ctrl/meta click actions.openBookmarks(li, urls, !shift); } else if (shift) { // shift click actions.openBookmarksNewWindow(li, urls); } }); } }; $tree.addEventListener('click', bookmarkHandler); var bookmarkHandlerMiddle = function(e) { if (e.button != 1) return; // force middle-click var event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, true, false, e.shiftKey, true, 0, null); e.target.dispatchEvent(event); }; $tree.addEventListener('mouseup', bookmarkHandlerMiddle); // Disable Chrome auto-scroll feature window.addEventListener('mousedown', function(e) { if (e.button == 1) e.preventDefault(); }); // Context menu var $bookmarkContextMenu = $('bookmark-context-menu'); var $folderContextMenu = $('folder-context-menu'); var clearMenu = function(e) { currentContext = null; var active = body.querySelector('.active'); if (active) { active.removeClass('active'); // This is kinda hacky. Oh well. if (e) { var el = e.target; if (el == $tree) active.focus(); } } $bookmarkContextMenu.style.left = '-999px'; $bookmarkContextMenu.style.opacity = 0; $folderContextMenu.style.left = '-999px'; $folderContextMenu.style.opacity = 0; }; body.addEventListener('click', clearMenu); $tree.addEventListener('scroll', clearMenu); $tree.addEventListener('focus', clearMenu, true); var currentContext = null; var macCloseContextMenu = false; body.addEventListener('contextmenu', function(e) { e.preventDefault(); clearMenu(); if (os == 'mac') { macCloseContextMenu = false; setTimeout(function() { macCloseContextMenu = true; }, 500); } var el = e.target; var active, pageX, pageY, boundY; if (el.tagName == 'A') { currentContext = el; active = body.querySelector('.active'); if (active) active.removeClass('active'); el.addClass('active'); var bookmarkMenuWidth = $bookmarkContextMenu.offsetWidth; var bookmarkMenuHeight = $bookmarkContextMenu.offsetHeight; pageX = rtl ? Math.max(0, e.pageX - bookmarkMenuWidth) : Math.min(e.pageX, body.offsetWidth - bookmarkMenuWidth); pageY = e.pageY; boundY = window.innerHeight - bookmarkMenuHeight; if (pageY > boundY) pageY -= bookmarkMenuHeight; if (pageY < 0) pageY = boundY; pageY = Math.max(0, pageY); $bookmarkContextMenu.style.left = pageX + 'px'; $bookmarkContextMenu.style.top = pageY + 'px'; $bookmarkContextMenu.style.opacity = 1; $bookmarkContextMenu.focus(); } else if (el.tagName == 'SPAN') { currentContext = el; active = body.querySelector('.active'); if (active) active.removeClass('active'); el.addClass('active'); if (el.parentNode.dataset.parentid == '0') { $folderContextMenu.addClass('hide-editables'); } else { $folderContextMenu.removeClass('hide-editables'); } var folderMenuWidth = $folderContextMenu.offsetWidth; var folderMenuHeight = $folderContextMenu.offsetHeight; pageX = rtl ? Math.max(0, e.pageX - folderMenuWidth) : Math.min(e.pageX, body.offsetWidth - folderMenuWidth); pageY = e.pageY; boundY = window.innerHeight - folderMenuHeight; if (pageY > boundY) pageY -= folderMenuHeight; if (pageY < 0) pageY = boundY; $folderContextMenu.style.left = pageX + 'px'; $folderContextMenu.style.top = pageY + 'px'; $folderContextMenu.style.opacity = 1; $folderContextMenu.focus(); } }); // on Mac, holding down right-click for a period of time closes the context menu // Not a complete implementation, but it works :) if (os == 'mac') body.addEventListener('mouseup', function(e) { if (e.button == 2 && macCloseContextMenu) { macCloseContextMenu = false; clearMenu(); } }); var bookmarkContextHandler = function(e) { e.stopPropagation(); if (!currentContext) return; var el = e.target; if (el.tagName != 'COMMAND') return; var url = currentContext.href; switch (el.id) { case 'bookmark-new-tab': actions.openBookmarkNewTab(url); break; case 'bookmark-new-window': actions.openBookmarkNewWindow(url); break; case 'bookmark-new-incognito-window': actions.openBookmarkNewWindow(url, true); break; case 'bookmark-edit': var li = currentContext.parentNode; var id = li.id.replace(/(neat\-tree)\-item\-/, ''); actions.editBookmarkFolder(id); break; case 'bookmark-update': var li = currentContext.parentNode; var id = li.id.replace(/(neat\-tree)\-item\-/, ''); actions.updateBookmark(id); break; case 'bookmark-delete': var li = currentContext.parentNode; var id = li.id.replace(/(neat\-tree)\-item\-/, ''); actions.deleteBookmark(id); break; case 'bookmark-set-hotkey': var li = currentContext.parentNode; var id = li.id.replace(/(neat\-tree)\-item\-/, ''); var name = li.querySelector('i'); actions.setHotkey(id, name.textContent); break; case 'bookmark-unset-hotkey': var li = currentContext.parentNode; var id = li.id.replace(/(neat\-tree)\-item\-/, ''); actions.unsetHotkey(id); break; } clearMenu(); }; // On Mac, all three mouse clicks work; on Windows, middle-click doesn't work $bookmarkContextMenu.addEventListener('mouseup', function(e) { e.stopPropagation(); if (e.button === 0 || (os == 'mac' && e.button == 1)) bookmarkContextHandler(e); }); $bookmarkContextMenu.addEventListener('contextmenu', bookmarkContextHandler); $bookmarkContextMenu.addEventListener('click', function(e) { e.stopPropagation(); }); var folderContextHandler = function(e) { if (!currentContext) return; var el = e.target; if (el.tagName != 'COMMAND') return; var li = currentContext.parentNode; var id = li.id.replace('neat-tree-item-', ''); chrome.bookmarks.getChildren(id, function(children) { var urls = Array.map(function(c) { return c.url; }, children).clean(); var urlsLen = urls.length; var noURLS = !urlsLen; switch (el.id) { case 'folder-window': if (noURLS) return; actions.openBookmarks(li, urls); break; case 'folder-new-window': if (noURLS) return; actions.openBookmarksNewWindow(li, urls); break; case 'folder-new-incognito-window': if (noURLS) return; actions.openBookmarksNewWindow(li, urls, true); break; case 'folder-edit': actions.editBookmarkFolder(id); break; case 'folder-delete': actions.deleteBookmarks(id, urlsLen, children.length - urlsLen); break; } }); clearMenu(); }; $folderContextMenu.addEventListener('mouseup', function(e) { e.stopPropagation(); if (e.button === 0 || (os == 'mac' && e.button == 1)) folderContextHandler(e); }); $folderContextMenu.addEventListener('contextmenu', folderContextHandler); $folderContextMenu.addEventListener('click', function(e) { e.stopPropagation(); }); // Keyboard navigation var treeKeyDown = function(e) { var item = document.activeElement; if (!/^(a|span)$/i.test(item.tagName)) item = $tree.querySelector('li:first-child>span'); var li = item.parentNode; var keyCode = e.keyCode; var metaKey = e.metaKey; if (keyCode == 40 && metaKey) keyCode = 35; // cmd + down (Mac) if (keyCode == 38 && metaKey) keyCode = 36; // cmd + up (Mac) var event; var lis; var parentID; switch (keyCode) { case 40: // down e.preventDefault(); var liChild = li.querySelector('ul>li:first-child'); if (li.hasClass('open') && liChild) { liChild.querySelector('a, span').focus(); } else { var nextLi = li.nextElementSibling; if (nextLi) { nextLi.querySelector('a, span').focus(); } else { do { // Go up in hierarchy li = li.parentNode.parentNode; // Go to next if (li.tagName === 'LI') nextLi = li.nextElementSibling; if (nextLi) nextLi.querySelector('a, span').focus(); } while (li.tagName === 'LI' && !nextLi); } } break; case 38: // up e.preventDefault(); var prevLi = li.previousElementSibling; if (prevLi) { while (prevLi.hasClass('open') && prevLi.querySelector('ul>li:last-child')) { lis = prevLi.querySelectorAll('ul>li:last-child'); prevLi = Array.filter(function(li) { return !!li.parentNode.offsetHeight; }, lis).getLast(); } prevLi.querySelector('a, span').focus(); } else { var parentPrevLi = li.parentNode.parentNode; if (parentPrevLi && parentPrevLi.tagName == 'LI') { parentPrevLi.querySelector('a, span').focus(); } } break; case 39: // right (left for RTL) e.preventDefault(); if (li.hasClass('parent') && ((!rtl && !li.hasClass('open')) || (rtl && li.hasClass('open')))) { event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); li.firstElementChild.dispatchEvent(event); } else if (rtl) { parentID = li.dataset.parentid; if (parentID == '0') return; $('neat-tree-item-' + parentID).querySelector('span').focus(); } break; case 37: // left (right for RTL) e.preventDefault(); if (li.hasClass('parent') && ((!rtl && li.hasClass('open')) || (rtl && !li.hasClass('open')))) { event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); li.firstElementChild.dispatchEvent(event); } else if (!rtl) { parentID = li.dataset.parentid; if (parentID == '0') return; $('neat-tree-item-' + parentID).querySelector('span').focus(); } break; case 32: // space case 13: // enter e.preventDefault(); event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, e.ctrlKey, false, e.shiftKey, e.metaKey, 0, null); li.firstElementChild.dispatchEvent(event); break; case 35: // end lis = this.querySelectorAll('ul>li:last-child'); Array.filter(function(li) { return !!li.parentNode.offsetHeight; }, lis).getLast().querySelector('span, a').focus(); break; case 36: // home this.querySelector('ul>li:first-child').querySelector('span, a').focus(); break; case 113: // F2, not for Mac if (os == 'mac') break; var id = li.id.replace(/(neat\-tree)\-item\-/, ''); actions.editBookmarkFolder(id); break; case 46: // delete break; // don't run 'default' default: var key = String.fromCharCode(keyCode).trim(); if (!key) return; // Trigger the hotkey if it exists. key = key.toLowerCase(); var id = getHotkeyId(key); if (id) { var li = $('neat-tree-item-' + id); // Due to Chrome bookmark sync bug, it's possible that the element // for this bookmark id doesn't actually exist anymore. if (li === null) { // Delete hotkey for this id to prevent invalid ids from remaining. unsetHotkey(id); } else { event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, e.ctrlKey, false, e.shiftKey, e.metaKey, 0, null); li.firstElementChild.dispatchEvent(event); } } } }; $tree.addEventListener('keydown', treeKeyDown); var treeKeyUp = function(e) { var item = document.activeElement; if (!/^(a|span)$/i.test(item.tagName)) item = $tree.querySelector('li:first-child>span'); var li = item.parentNode; switch (e.keyCode) { case 8: // backspace if (os != 'mac') break; // somehow delete button on mac gives backspace /* falls through */ case 46: // delete e.preventDefault(); var id = li.id.replace(/(neat\-tree)\-item\-/, ''); if (li.hasClass('parent')) { chrome.bookmarks.getChildren(id, function(children) { var urlsLen = Array.map(function(c) { return c.url; }, children).clean().length; actions.deleteBookmarks(id, urlsLen, children.length - urlsLen); }); } else { actions.deleteBookmark(id); } break; } }; $tree.addEventListener('keyup', treeKeyUp); var contextKeyDown = function(e) { var menu = this; var item = document.activeElement; var metaKey = e.metaKey; switch (e.keyCode) { case 40: // down e.preventDefault(); if (metaKey) { // cmd + down (Mac) menu.lastElementChild.focus(); } else { if (item.tagName == 'COMMAND') { var nextItem = item.nextElementSibling; if (nextItem && nextItem.tagName == 'HR') nextItem = nextItem.nextElementSibling; if (nextItem) { nextItem.focus(); } else if (os != 'mac') { menu.firstElementChild.focus(); } } else { item.firstElementChild.focus(); } } break; case 38: // up e.preventDefault(); if (metaKey) { // cmd + up (Mac) menu.firstElementChild.focus(); } else { if (item.tagName == 'COMMAND') { var prevItem = item.previousElementSibling; if (prevItem && prevItem.tagName == 'HR') prevItem = prevItem.previousElementSibling; if (prevItem) { prevItem.focus(); } else if (os != 'mac') { menu.lastElementChild.focus(); } } else { item.lastElementChild.focus(); } } break; case 32: // space if (os != 'mac') break; /* falls through */ case 13: // enter e.preventDefault(); var event = document.createEvent('MouseEvents'); event.initMouseEvent('mouseup', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); item.dispatchEvent(event); /* falls through */ case 27: // esc e.preventDefault(); var active = body.querySelector('.active'); if (active) active.removeClass('active').focus(); clearMenu(); } }; $bookmarkContextMenu.addEventListener('keydown', contextKeyDown); $folderContextMenu.addEventListener('keydown', contextKeyDown); var contextMouseMove = function(e) { e.target.focus(); }; $bookmarkContextMenu.addEventListener('mousemove', contextMouseMove); $folderContextMenu.addEventListener('mousemove', contextMouseMove); var contextMouseOut = function() { if (this.style.opacity.toInt()) this.focus(); }; $bookmarkContextMenu.addEventListener('mouseout', contextMouseOut); $folderContextMenu.addEventListener('mouseout', contextMouseOut); // Drag and drop var draggedBookmark = null; var draggedOut = false; var canDrop = false; var bookmarkClone = $('bookmark-clone'); var dropOverlay = $('drop-overlay'); $tree.addEventListener('mousedown', function(e) { if (e.button !== 0) return; var el = e.target; var elParent = el.parentNode; // can move any bookmarks/folders except the default root folders if ((el.tagName == 'A' && elParent.hasClass('child')) || (el.tagName == 'SPAN' && elParent.hasClass('parent') && elParent.dataset.parentid != '0')) { e.preventDefault(); draggedOut = false; draggedBookmark = el; bookmarkClone.innerHTML = el.innerHTML; el.focus(); } }); var scrollTree, scrollTreeInterval = 100, scrollTreeSpot = 10; var scrollTreeSpeed = 20; var stopScrollTree = function() { clearInterval(scrollTree); scrollTree = null; }; document.addEventListener('mousemove', function(e) { if (e.button !== 0) return; if (!draggedBookmark) return; e.preventDefault(); var el = e.target; var clientX = e.clientX; var clientY = e.clientY + document.body.scrollTop; if (el == draggedBookmark) { bookmarkClone.style.left = '-999px'; dropOverlay.style.left = '-999px'; canDrop = false; return; } draggedOut = true; // if hovering over the dragged element itself or cursor move outside the tree var treeTop = $tree.offsetTop, treeBottom = window.innerHeight; if (clientX < 0 || clientY < treeTop || clientX > $tree.offsetWidth || clientY > treeBottom) { bookmarkClone.style.left = '-999px'; dropOverlay.style.left = '-999px'; canDrop = false; } // if hovering over the top or bottom edges of the tree, scroll the tree var treeScrollHeight = $tree.scrollHeight, treeOffsetHeight = $tree.offsetHeight; if (treeScrollHeight > treeOffsetHeight) { // only scroll when it's scrollable var treeScrollTop = $tree.scrollTop; if (clientY <= treeTop + scrollTreeSpot) { if (treeScrollTop === 0) { stopScrollTree(); } else if (!scrollTree) { scrollTree = setInterval(function() { $tree.scrollTop -= scrollTreeSpeed; dropOverlay.style.left = '-999px'; }, scrollTreeInterval); } } else if (clientY >= treeBottom - scrollTreeSpot) { if (treeScrollTop == (treeScrollHeight - treeOffsetHeight)) { stopScrollTree(); } else if (!scrollTree) { scrollTree = setInterval(function() { $tree.scrollTop += scrollTreeSpeed; dropOverlay.style.left = '-999px'; }, scrollTreeInterval); } } else { stopScrollTree(); } } // collapse the folder before moving it var draggedBookmarkParent = draggedBookmark.parentNode; if (draggedBookmark.tagName == 'SPAN' && draggedBookmarkParent.hasClass('open')) { draggedBookmarkParent.removeClass('open').setAttribute('aria-expanded', false); } if (el.tagName == 'A') { canDrop = true; bookmarkClone.style.top = clientY + 'px'; bookmarkClone.style.left = (rtl ? (clientX - bookmarkClone.offsetWidth) : clientX) + 'px'; var elRect = el.getBoundingClientRect(); var elRectTop = elRect.top + document.body.scrollTop; var elRectBottom = elRect.bottom + document.body.scrollTop; var top = (clientY >= elRectTop + elRect.height / 2) ? elRectBottom : elRectTop; dropOverlay.className = 'bookmark'; dropOverlay.style.top = top + 'px'; dropOverlay.style.left = rtl ? '0px' : el.style.webkitPaddingStart.toInt() + 16 + 'px'; dropOverlay.style.width = (el.getComputedStyle('width').toInt() - 12) + 'px'; dropOverlay.style.height = null; } else if (el.tagName == 'SPAN') { canDrop = true; bookmarkClone.style.top = clientY + 'px'; bookmarkClone.style.left = clientX + 'px'; var elRect = el.getBoundingClientRect(); var top = null; var elRectTop = elRect.top + document.body.scrollTop; var elRectHeight = elRect.height; var elRectBottom = elRect.bottom + document.body.scrollTop; var elParent = el.parentNode; if (elParent.dataset.parentid != '0') { if (clientY < elRectTop + elRectHeight * 0.3) { top = elRectTop; } else if (clientY > (elRectTop + elRectHeight * 0.7) && !elParent.hasClass('open')) { top = elRectBottom; } } if (top === null) { dropOverlay.className = 'folder'; dropOverlay.style.top = elRectTop + 'px'; dropOverlay.style.left = '0px'; dropOverlay.style.width = elRect.width + 'px'; dropOverlay.style.height = elRect.height + 'px'; } else { dropOverlay.className = 'bookmark'; dropOverlay.style.top = top + 'px'; dropOverlay.style.left = el.style.webkitPaddingStart.toInt() + 16 + 'px'; dropOverlay.style.width = (el.getComputedStyle('width').toInt() - 12) + 'px'; dropOverlay.style.height = null; } } }); var onDrop = function() { draggedBookmark = null; bookmarkClone.style.left = '-999px'; dropOverlay.style.left = '-999px'; canDrop = false; }; document.addEventListener('mouseup', function(e) { if (e.button !== 0) return; if (!draggedBookmark) return; stopScrollTree(); if (!canDrop) { if (draggedOut) noOpenBookmark = true; draggedOut = false; onDrop(); return; } var el = e.target; var elParent = el.parentNode; var id = elParent.id.replace('neat-tree-item-', ''); if (!id) { onDrop(); return; } var draggedBookmarkParent = draggedBookmark.parentNode; var draggedID = draggedBookmarkParent.id.replace('neat-tree-item-', ''); var clientY = e.clientY + document.body.scrollTop; if (el.tagName == 'A') { var elRect = el.getBoundingClientRect(); var elRectTop = elRect.top + document.body.scrollTop; var moveBottom = (clientY >= elRectTop + elRect.height / 2); chrome.bookmarks.get(id, function(node) { if (!node || !node.length) return; node = node[0]; var index = node.index; var parentId = node.parentId; if (draggedID) { chrome.bookmarks.move(draggedID, { parentId: parentId, index: moveBottom ? ++index : index }, function() { draggedBookmarkParent.inject(elParent, moveBottom ? 'after' : 'before'); draggedBookmark.style.webkitPaddingStart = el.style.webkitPaddingStart; draggedBookmark.focus(); onDrop(); }); } }); } else if (el.tagName == 'SPAN') { var elRect = el.getBoundingClientRect(); var move = 0; // 0 = middle, 1 = top, 2 = bottom var elRectTop = elRect.top, elRectHeight = elRect.height; var elParent = el.parentNode; if (elParent.dataset.parentid != '0') { if (clientY < elRectTop + elRectHeight * 0.3) { move = 1; } else if (clientY > elRectTop + elRectHeight * 0.7 && !elParent.hasClass('open')) { move = 2; } } if (move > 0) { var moveBottom = (move == 2); chrome.bookmarks.get(id, function(node) { if (!node || !node.length) return; node = node[0]; var index = node.index; var parentId = node.parentId; chrome.bookmarks.move(draggedID, { parentId: parentId, index: moveBottom ? ++index : index }, function() { draggedBookmarkParent.inject(elParent, moveBottom ? 'after' : 'before'); draggedBookmark.style.webkitPaddingStart = el.style.webkitPaddingStart; draggedBookmark.focus(); onDrop(); }); }); } else { chrome.bookmarks.move(draggedID, { parentId: id }, function() { var ul = elParent.querySelector('ul'); var level = parseInt(elParent.parentNode.dataset.level) + 1; draggedBookmark.style.webkitPaddingStart = (14 * level) + 'px'; if (ul) { draggedBookmarkParent.inject(ul); } else { draggedBookmarkParent.destroy(); } el.focus(); onDrop(); }); } } else { onDrop(); } }); // Resizer var $resizer = $('resizer'); var resizerDown = false; var bodyWidth, screenX; $resizer.addEventListener('mousedown', function(e) { e.preventDefault(); e.stopPropagation(); resizerDown = true; bodyWidth = body.offsetWidth; screenX = e.screenX; }); document.addEventListener('mousemove', function(e) { if (!resizerDown) return; e.preventDefault(); var changedWidth = rtl ? (e.screenX - screenX) : (screenX - e.screenX); var width = bodyWidth + changedWidth; width = Math.min(640, Math.max(320, width)); body.style.width = width + 'px'; localStorage.popupWidth = width; clearMenu(); // messes the context menu }); document.addEventListener('mouseup', function(e) { if (!resizerDown) return; e.preventDefault(); resizerDown = false; adaptBookmarkTooltips(); }); // Closing dialogs on escape var closeDialogs = function() { if (body.hasClass('needConfirm')) ConfirmDialog.fn2(); ConfirmDialog.close(); if (body.hasClass('needEdit')) EditDialog.closeNoSave(); if (body.hasClass('needSetHotkey')) HotkeyDialog.closeNoSave(); if (body.hasClass('needAlert')) AlertDialog.close(); }; document.addEventListener('keydown', function(e) { if (e.keyCode == 27 && (body.hasClass('needConfirm') || body.hasClass('needEdit') || body.hasClass('needSetHotkey') || body.hasClass('needAlert'))) { // esc e.preventDefault(); closeDialogs(); } }); $('cover').addEventListener('click', closeDialogs); // Make webkit transitions work only after elements are settled down setTimeout(function() { body.addClass('transitional'); }, 10); })(window);
mit