text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Replace AsyncTask with AsyncTaskLoader and do some clean up.
package com.example.android.quakereport; import android.content.AsyncTaskLoader; import android.content.Context; import android.util.Log; import java.util.List; /** * Created by Lenovo on 7/6/2017. */ /* Loads a list of earthquakes by using an AsyncTaskLoader to perform the network request to the destination(USGS) url. */ public class EarthquakeLoader extends AsyncTaskLoader<List<Earthquake>> { /* Tag for log messages */ private final static String LOG_TAG = EarthquakeLoader.class.getSimpleName(); /* Query URL */ private String mUrl; //TODO: Extract the earthquake data from the USGS url public EarthquakeLoader(Context context, String url) { super(context); this.mUrl = url; } @Override protected void onStartLoading() { forceLoad(); } /* * Run the earthquake data request in the background */ @Override public List<Earthquake> loadInBackground() { List<Earthquake> earthquakes = null; // Don't perform the request if there are no URLs, or the first URL if(mUrl == null) return null; try { /* Perform the HTTP request for earthquake data and process the response. */ earthquakes = QueryUtils.fetchEarthquakeData(mUrl); }catch (SecurityException e) { Log.e(LOG_TAG, e.getMessage(), e); } return earthquakes; } }
package com.example.android.quakereport; import android.content.AsyncTaskLoader; import android.content.Context; import android.util.Log; import java.util.List; /** * Created by Lenovo on 7/6/2017. */ public class EarthquakeLoader extends AsyncTaskLoader<List<Earthquake>> { final static String LOG_TAG = EarthquakeLoader.class.getSimpleName(); private String mUrl; //TODO: Extract the earthquake data from the USGS url public EarthquakeLoader(Context context, String url) { super(context); this.mUrl = url; } @Override protected void onStartLoading() { forceLoad(); } @Override public List<Earthquake> loadInBackground() { List<Earthquake> result = null; // Don't perform the request if there are no URLs, or the first URL if(getUrl().length() < 1) return null; try { // Perform the HTTP request for earthquake data and process the response. result = QueryUtils.fetchEarthquakeData(getUrl()); }catch (SecurityException e) { Log.e(LOG_TAG, e.getMessage(), e); } return result; } //@return the url of the earthquake data to the displayed public String getUrl() { return mUrl; } }
Revert names to slugs again! SORRY!!
<?php declare(strict_types=1); namespace Cortex\Foundation\Transformers; use Cortex\Foundation\Models\Log; use Illuminate\Support\Facades\Route; use League\Fractal\TransformerAbstract; class LogTransformer extends TransformerAbstract { /** * @return array */ public function transform(Log $log): array { $causer_route = ''; if ($log->causer) { $class = explode('\\', get_class($log->causer)); $singleResource = lower_case(end($class)); $pluralResource = str_plural(lower_case(end($class))); $causer = ucfirst($singleResource).': '.($log->causer->username ?? $log->causer->title ?? $log->causer->slug); $causer_route = Route::has("adminarea.{$pluralResource}.edit") ? route("adminarea.{$pluralResource}.edit", [$singleResource => $log->causer]) : null; } else { $causer = 'System'; } return [ 'id' => (int) $log->getKey(), 'description' => (string) $log->description, 'causer' => $causer, 'causer_route' => $causer_route, 'properties' => (object) $log->properties, 'created_at' => (string) $log->created_at, ]; } }
<?php declare(strict_types=1); namespace Cortex\Foundation\Transformers; use Cortex\Foundation\Models\Log; use Illuminate\Support\Facades\Route; use League\Fractal\TransformerAbstract; class LogTransformer extends TransformerAbstract { /** * @return array */ public function transform(Log $log): array { $causer_route = ''; if ($log->causer) { $class = explode('\\', get_class($log->causer)); $singleResource = lower_case(end($class)); $pluralResource = str_plural(lower_case(end($class))); $causer = ucfirst($singleResource).': '.($log->causer->username ?? $log->causer->title ?? $log->causer->name); $causer_route = Route::has("adminarea.{$pluralResource}.edit") ? route("adminarea.{$pluralResource}.edit", [$singleResource => $log->causer]) : null; } else { $causer = 'System'; } return [ 'id' => (int) $log->getKey(), 'description' => (string) $log->description, 'causer' => $causer, 'causer_route' => $causer_route, 'properties' => (object) $log->properties, 'created_at' => (string) $log->created_at, ]; } }
Fix the Class Type Test Cases class name, and enhance the create new
from decimal import Decimal from django.db import IntegrityError from django.test import TestCase from .models import ClassType class ClassTypeTestCases(TestCase): """ Testing Class Type model """ def setUp(self): self.class_type, created = ClassType.objects.get_or_create(name='Class Type 1', monthly_fees=Decimal(12)) def test_create_new_class_type(self): new_class_type = ClassType(name='Class Type 2', monthly_fees=Decimal(10)) new_class_type.save() self.assertIsInstance(new_class_type, ClassType) self.assertTrue(new_class_type.pk) def test_update_class_type(self): new_monthly_fees = Decimal(15) self.class_type.monthly_fees = new_monthly_fees self.class_type.save() self.assertEqual(new_monthly_fees, self.class_type.monthly_fees) self.assertTrue(self.class_type.pk) def test_delete_class_type(self): self.class_type.delete() self.assertFalse(self.class_type.pk) def test_create_class_type_with_duplicate_names(self): new_class_type = ClassType(name='Class Type 1', monthly_fees=Decimal(10)) self.assertRaises(IntegrityError, lambda: new_class_type.save())
from decimal import Decimal from django.db import IntegrityError from django.test import TestCase from .models import ClassType class ClassTypeClassTypeTestCases(TestCase): """ Testing Class Type model """ def setUp(self): self.class_type, created = ClassType.objects.get_or_create(name='Class Type 1', monthly_fees=Decimal(12)) def test_create_new_class_type(self): new_class_type = ClassType(name='Class Type 2', monthly_fees=Decimal(10)) new_class_type.save() self.assertEqual(type(new_class_type), ClassType) self.assertTrue(new_class_type.pk) def test_update_class_type(self): new_monthly_fees = Decimal(15) self.class_type.monthly_fees = new_monthly_fees self.class_type.save() self.assertEqual(new_monthly_fees, self.class_type.monthly_fees) self.assertTrue(self.class_type.pk) def test_delete_class_type(self): self.class_type.delete() self.assertFalse(self.class_type.pk) def test_create_class_type_with_duplicate_names(self): new_class_type = ClassType(name='Class Type 1', monthly_fees=Decimal(10)) self.assertRaises(IntegrityError, lambda: new_class_type.save())
Change official reference message wording
import React from "react"; import { connect } from "react-redux"; import styled from "styled-components"; import { Box, Button, ExternalLink } from "../../base"; import { checkAdminOrPermission } from "../../utils/utils"; import { remoteReference } from "../actions"; const StyledReferenceOfficial = styled(Box)` align-items: center; display: flex; h5 { font-size: 16px; font-weight: bold; } button { margin-left: auto; } `; export const ReferenceOfficial = ({ show, onRemote }) => { if (show) { return ( <StyledReferenceOfficial> <div> <h5>Official Reference</h5> <p> <span>We have published an official </span> <ExternalLink href="https://github.com/virtool/ref-plant-viruses"> plant virus reference </ExternalLink> <span> {" "} that can be installed automatically. Once installed, it can easily be kept up-to-date. </span> </p> </div> <Button color="blue" icon="cloud-download-alt" onClick={onRemote}> Install </Button> </StyledReferenceOfficial> ); } return null; }; const mapStateToProps = state => ({ show: !state.references.official_installed && checkAdminOrPermission(state, "create_ref") }); const mapDispatchToProps = dispatch => ({ onRemote: () => { dispatch(remoteReference()); } }); export default connect(mapStateToProps, mapDispatchToProps)(ReferenceOfficial);
import React from "react"; import { connect } from "react-redux"; import styled from "styled-components"; import { Box, Button, ExternalLink } from "../../base"; import { checkAdminOrPermission } from "../../utils/utils"; import { remoteReference } from "../actions"; const StyledReferenceOfficial = styled(Box)` align-items: center; display: flex; h5 { font-size: 16px; font-weight: bold; } button { margin-left: auto; } `; export const ReferenceOfficial = ({ show, onRemote }) => { if (show) { return ( <StyledReferenceOfficial> <div> <h5>Official Reference</h5> <p> <span>We have published an official </span> <ExternalLink href="https://github.com/virtool/ref-plant-viruses"> plant virus reference </ExternalLink> <span> for install. Once installed, it can be kept automatically up-to-date.</span> </p> </div> <Button color="blue" icon="cloud-download-alt" onClick={onRemote}> Install </Button> </StyledReferenceOfficial> ); } return null; }; const mapStateToProps = state => ({ show: !state.references.official_installed && checkAdminOrPermission(state, "create_ref") }); const mapDispatchToProps = dispatch => ({ onRemote: () => { dispatch(remoteReference()); } }); export default connect(mapStateToProps, mapDispatchToProps)(ReferenceOfficial);
Remove explicit python2 call -- works with Python 3
#!/bin/env python """ moref: more for FASTA files """ import sys import os from Bio import SeqIO def main(): """moref main""" # Check for input file if len(sys.argv) < 2: print("No input file specified") sys.exit() filepath = os.path.expanduser(sys.argv[1]) if not os.path.isfile(filepath): print("No input file specified") sys.exit() # Read in FASTA file seqs = SeqIO.parse(filepath, 'fasta') # Generate list of colors to use for printing, ex: # regular - \033[032m # emphasized - \033[1;032m # bright - \033[092m colors = ['\033[0%dm' % i for i in range(91, 95)] # DNA dna = dict((x, colors[i] + x) for i, x in enumerate(('A', 'C', 'G', 'T'))) # bold text regular = '\033[0;090m' bold = '\033[1;090m' # loop through and print seqs for seq in seqs: print(bold + seq.description) pretty = regular for letter in seq.seq: pretty += dna[letter] print(pretty + "\n") if __name__ == "__main__": main()
#!/bin/env python2 """ moref: more for FASTA files """ import sys import os from Bio import SeqIO def main(): """moref main""" # Check for input file if len(sys.argv) < 2: print("No input file specified") sys.exit() filepath = os.path.expanduser(sys.argv[1]) if not os.path.isfile(filepath): print("No input file specified") sys.exit() # Read in FASTA file seqs = SeqIO.parse(filepath, 'fasta') # Generate list of colors to use for printing, ex: # regular - \033[032m # emphasized - \033[1;032m # bright - \033[092m colors = ['\033[0%dm' % i for i in range(91, 95)] # DNA dna = dict((x, colors[i] + x) for i, x in enumerate(('A', 'C', 'G', 'T'))) # bold text regular = '\033[0;090m' bold = '\033[1;090m' # loop through and print seqs for seq in seqs: print(bold + seq.description) pretty = regular for letter in seq.seq: pretty += dna[letter] print(pretty + "\n") if __name__ == "__main__": main()
Work around Python3's byte semantics.
from suelta.util import bytes from suelta.sasl import Mechanism, register_mechanism try: import urlparse except ImportError: import urllib.parse as urlparse class X_FACEBOOK_PLATFORM(Mechanism): def __init__(self, sasl, name): super(X_FACEBOOK_PLATFORM, self).__init__(sasl, name) self.check_values(['access_token', 'api_key']) def process(self, challenge=None): if challenge is not None: values = {} for kv in challenge.split(b'&'): key, value = kv.split(b'=') values[key] = value resp_data = { b'method': values[b'method'], b'v': b'1.0', b'call_id': b'1.0', b'nonce': values[b'nonce'], b'access_token': self.values['access_token'], b'api_key': self.values['api_key'] } resp = '&'.join(['%s=%s' % (k, v) for k, v in resp_data.items()]) return bytes(resp) return b'' def okay(self): return True register_mechanism('X-FACEBOOK-PLATFORM', 40, X_FACEBOOK_PLATFORM, use_hashes=False)
from suelta.util import bytes from suelta.sasl import Mechanism, register_mechanism try: import urlparse except ImportError: import urllib.parse as urlparse class X_FACEBOOK_PLATFORM(Mechanism): def __init__(self, sasl, name): super(X_FACEBOOK_PLATFORM, self).__init__(sasl, name) self.check_values(['access_token', 'api_key']) def process(self, challenge=None): if challenge is not None: values = {} for kv in challenge.split('&'): key, value = kv.split('=') values[key] = value resp_data = { 'method': values['method'], 'v': '1.0', 'call_id': '1.0', 'nonce': values['nonce'], 'access_token': self.values['access_token'], 'api_key': self.values['api_key'] } resp = '&'.join(['%s=%s' % (k, v) for k, v in resp_data.items()]) return bytes(resp) return bytes('') def okay(self): return True register_mechanism('X-FACEBOOK-PLATFORM', 40, X_FACEBOOK_PLATFORM, use_hashes=False)
Fix "covers" annotation in tests
<?php /** * @author Sergii Bondarenko, <[email protected]> */ namespace Drupal\Tests\TqExtension\Utils; use Drupal\TqExtension\Utils\LogicalAssertion; /** * Class LogicalAssertionTest. * * @package Drupal\Tests\TqExtension\Utils * * @coversDefaultClass \Drupal\TqExtension\Utils\LogicalAssertion */ class LogicalAssertionTest extends \PHPUnit_Framework_TestCase { /** * @var LogicalAssertion */ private $logicalAssertion; /** * {@inheritdoc} */ public function setUp() { $this->logicalAssertion = $this->getMockForTrait(LogicalAssertion::class); } /** * @covers ::assertion * @dataProvider dataset * * @param mixed $value * @param bool $negate * @param int $expected */ public function testAssertion($value, $negate, $expected) { $this->assertSame($expected, $this->logicalAssertion->assertion($value, $negate)); } /** * @dataProvider */ public function dataset() { return [ // Value is equalled to "true" and not negated. [1, false, 0], // Value is equalled to "true" and negated. [1, true, 1], // Value is equalled to "false" and not negated. [0, false, 2], // Value is equalled to "false" and negated. [0, true, 0], ]; } }
<?php /** * @author Sergii Bondarenko, <[email protected]> */ namespace Drupal\Tests\TqExtension\Utils; use Drupal\TqExtension\Utils\LogicalAssertion; /** * Class LogicalAssertionTest. * * @package Drupal\Tests\TqExtension\Utils * * @coversDefaultClass \Drupal\TqExtension\Utils\LogicalAssertion */ class LogicalAssertionTest extends \PHPUnit_Framework_TestCase { /** * @var LogicalAssertion */ private $logicalAssertion; /** * {@inheritdoc} */ public function setUp() { $this->logicalAssertion = $this->getMockForTrait(LogicalAssertion::class); } /** * @covers assertion * @dataProvider dataset * * @param mixed $value * @param bool $negate * @param int $expected */ public function testAssertion($value, $negate, $expected) { $this->assertSame($expected, $this->logicalAssertion->assertion($value, $negate)); } /** * @dataProvider */ public function dataset() { return [ // Value is equalled to "true" and not negated. [1, false, 0], // Value is equalled to "true" and negated. [1, true, 1], // Value is equalled to "false" and not negated. [0, false, 2], // Value is equalled to "false" and negated. [0, true, 0], ]; } }
test: Use old-school looping since travis stuck on ancient Chromium: - See travis-ci/travis-ci#3475 - TODO: switch to full Chrome on travis
describe('ZendeskWidgetProvider', function() { 'use strict'; var subject, mockService, $window; beforeEach(module('zendeskWidget')); beforeEach(inject(function(_$window_, _ZendeskWidget_) { subject = _ZendeskWidget_; $window = _$window_; })); describe('a set of API methods', function() { beforeEach(function() { var apiMethods = ['setLocale', 'identify', 'hide', 'show', 'activate']; // Stub out $window.zE() wrapper and all apiMethods mockService = $window.zE = function(fn) { fn(); }; for (var i = 0; i < apiMethods.length; i++) { var apiMethod = apiMethods[i]; $window.zE[apiMethod] = function() {}; spyOn($window.zE, apiMethod).and.callThrough(); } }); it("delegates to Zendesk's Web Widget API", function() { var anyArgs = ['foo', 'bar', 'baz']; subject.identify(anyArgs); subject.hide(anyArgs); subject.show(anyArgs); subject.activate(anyArgs); subject.setLocale(anyArgs); expect(mockService.identify).toHaveBeenCalledWith(anyArgs); expect(mockService.hide).toHaveBeenCalledWith(anyArgs); expect(mockService.show).toHaveBeenCalledWith(anyArgs); expect(mockService.activate).toHaveBeenCalledWith(anyArgs); expect(mockService.setLocale).toHaveBeenCalledWith(anyArgs); }); }); })
describe('ZendeskWidgetProvider', function() { 'use strict'; var subject, mockService, $window; beforeEach(module('zendeskWidget')); beforeEach(inject(function(_$window_, _ZendeskWidget_) { subject = _ZendeskWidget_; $window = _$window_; })); describe('a set of API methods', function() { beforeEach(function() { var apiMethods = ['setLocale', 'identify', 'hide', 'show', 'activate']; // Stub out $window.zE() wrapper and all apiMethods mockService = $window.zE = function(fn) { fn(); }; for (var apiMethod of apiMethods) { $window.zE[apiMethod] = function() {}; spyOn($window.zE, apiMethod).and.callThrough(); } }); it("delegates to Zendesk's Web Widget API", function() { var anyArgs = ['foo', 'bar', 'baz']; subject.identify(anyArgs); subject.hide(anyArgs); subject.show(anyArgs); subject.activate(anyArgs); subject.setLocale(anyArgs); expect(mockService.identify).toHaveBeenCalledWith(anyArgs); expect(mockService.hide).toHaveBeenCalledWith(anyArgs); expect(mockService.show).toHaveBeenCalledWith(anyArgs); expect(mockService.activate).toHaveBeenCalledWith(anyArgs); expect(mockService.setLocale).toHaveBeenCalledWith(anyArgs); }); }); })
Comment getList docstring with variable names
<?php class Services_Twilio_Rest_AvailablePhoneNumbers extends Services_Twilio_ListResource { public function getLocal($country) { $curried = new Services_Twilio_PartialApplicationHelper(); $curried->set( 'getList', array($this, 'getList'), array($country, 'Local') ); return $curried; } public function getTollFree($country) { $curried = new Services_Twilio_PartialApplicationHelper(); $curried->set( 'getList', array($this, 'getList'), array($country, 'TollFree') ); return $curried; } /** * Get a list of available phone numbers. * * @param string $country The 2-digit country code you'd like to search for * numbers e.g. ('US', 'CA', 'GB') * @param string $type The type of number ('Local' or 'TollFree') * @return object The object representation of the resource */ public function getList($country, $type, array $params = array()) { return $this->client->retrieveData($this->uri . "/$country/$type", $params); } public function getResourceName($camelized = false) { // You can't page through the list of available phone numbers. $this->instance_name = 'Services_Twilio_Rest_AvailablePhoneNumber'; return $camelized ? 'Countries' : 'countries'; } }
<?php class Services_Twilio_Rest_AvailablePhoneNumbers extends Services_Twilio_ListResource { public function getLocal($country) { $curried = new Services_Twilio_PartialApplicationHelper(); $curried->set( 'getList', array($this, 'getList'), array($country, 'Local') ); return $curried; } public function getTollFree($country) { $curried = new Services_Twilio_PartialApplicationHelper(); $curried->set( 'getList', array($this, 'getList'), array($country, 'TollFree') ); return $curried; } /** * Get a list of available phone numbers. * * @param string country The 2-digit country code you'd like to search for * numbers e.g. ('US', 'CA', 'GB') * @param string type The type of number ('Local' or 'TollFree') * @return object The object representation of the resource */ public function getList($country, $type, array $params = array()) { return $this->client->retrieveData($this->uri . "/$country/$type", $params); } public function getResourceName($camelized = false) { // You can't page through the list of available phone numbers. $this->instance_name = 'Services_Twilio_Rest_AvailablePhoneNumber'; return $camelized ? 'Countries' : 'countries'; } }
Set time to utc time
package ch.squix.esp8266.fontconverter.rest.time; import java.awt.FontFormatException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.restlet.resource.Post; import org.restlet.resource.ServerResource; public class TimeResource extends ServerResource { @Post(value = "json") public TimeOutDto execute(TimeInDto inDto) throws FontFormatException, IOException { TimeOutDto outDto = new TimeOutDto(); DateTime dateTime = new DateTime(DateTimeZone.UTC); Locale locale = new Locale(inDto.getLanguage(), inDto.getCountry()); outDto.setMillisOfDayUtc(dateTime.getMillisOfDay()); List<TimeZoneDto> timeZones = new ArrayList<>(); outDto.setTimeZoneDto(timeZones); for (String timeZoneId : inDto.getTimeZoneIds()) { DateTimeZone zone = DateTimeZone.forID(timeZoneId); DateTime localDateTime = new DateTime(zone); TimeZoneDto zoneDto = new TimeZoneDto(); zoneDto.setIndex(timeZones.size()); zoneDto.setTimeZoneId(timeZoneId); zoneDto.setTimeZoneOffsetToUtcMillis(zone.getOffset(dateTime.getMillis())); zoneDto.setFormattedDate(localDateTime.toString(inDto.getDateFormat(), locale)); timeZones.add(zoneDto); } return outDto; } }
package ch.squix.esp8266.fontconverter.rest.time; import java.awt.FontFormatException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.restlet.resource.Post; import org.restlet.resource.ServerResource; public class TimeResource extends ServerResource { @Post(value = "json") public TimeOutDto execute(TimeInDto inDto) throws FontFormatException, IOException { TimeOutDto outDto = new TimeOutDto(); DateTime dateTime = new DateTime(); Locale locale = new Locale(inDto.getLanguage(), inDto.getCountry()); outDto.setMillisOfDayUtc(dateTime.getMillisOfDay()); List<TimeZoneDto> timeZones = new ArrayList<>(); outDto.setTimeZoneDto(timeZones); for (String timeZoneId : inDto.getTimeZoneIds()) { DateTimeZone zone = DateTimeZone.forID(timeZoneId); DateTime localDateTime = new DateTime(zone); TimeZoneDto zoneDto = new TimeZoneDto(); zoneDto.setIndex(timeZones.size()); zoneDto.setTimeZoneId(timeZoneId); zoneDto.setTimeZoneOffsetToUtcMillis(zone.getOffset(dateTime.getMillis())); zoneDto.setFormattedDate(localDateTime.toString(inDto.getDateFormat(), locale)); timeZones.add(zoneDto); } return outDto; } }
Load and test for admin users.
module.exports = function(access) { 'use strict'; let _ = require('lodash'); let projectAccessCache = {}; let adminUsersCache = {}; return { find: find, clear: clear, validateAccess: validateAccess }; // find looks up a given project in the project cache. // If the projectAccessCache hasn't been loaded it loads the // cache. function *find(project_id) { if (_.isEmpty(adminUsersCache)) { let adminUsers = yield access.adminUsers(); adminUsers.forEach(function(user) { adminUsersCache[user.id] = user; }); } if (! _.isEmpty(projectAccessCache)) { return projectAccessCache[project_id]; } projectAccessCache = yield access.allByProject(); return projectAccessCache[project_id]; } // clear will clear the current project cache. This is useful // when project permissions have been updated or a new project // has been created. function clear() { projectAccessCache = {}; } // validateAccess checks if the user has access to the // given project. This method assumes that find was called // first so that the projectAccessCache was preloaded. If the // projectAccessCache is empty then it returns false (no access). function validateAccess(project_id, user) { if (user.id in adminUsersCache) { return true; } if (_.isEmpty(projectAccessCache)) { return false; } if (!(project_id in projectAccessCache)) { return false; } let index = _.indexOf(projectAccessCache[project_id], function(a) { return a.user_id == user.id; }); // when index !== -1 we found the given user in the project. return index !== -1; } };
module.exports = function(access) { 'use strict'; let _ = require('lodash'); let projectAccessCache = {}; return { find: find, clear: clear, validateAccess: validateAccess }; // find looks up a given project in the project cache. // If the projectAccessCache hasn't been loaded it loads the // cache. function *find(project_id) { if (! _.isEmpty(projectAccessCache)) { return projectAccessCache[project_id]; } projectAccessCache = yield access.allByProject(); return projectAccessCache[project_id]; } // clear will clear the current project cache. This is useful // when project permissions have been updated or a new project // has been created. function clear() { projectAccessCache = {}; } // validateAccess checks if the user has access to the // given project. This method assumes that find was called // first so that the projectAccessCache was preloaded. If the // projectAccessCache is empty then it returns false (no access). function validateAccess(project_id, user) { if (_.isEmpty(projectAccessCache)) { return false; } if (!(project_id in projectAccessCache)) { return false; } let index = _.indexOf(projectAccessCache[project_id], function(a) { return a.user_id == user.id; }); // when index !== -1 we found the given user in the project. return index !== -1; } };
Fix to git status info
import os import subprocess __version__ = "0.1.0-1" def _try_init_git_attrs(): try: _init_git_commit() except (OSError, subprocess.CalledProcessError): pass else: try: _init_git_status() except (OSError, subprocess.CalledProcessError): pass def _init_git_commit(): commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1") globals()["__git_commit__"] = commit def _init_git_status(): raw = _git_cmd("git -C \"%(repo)s\" status -s") globals()["__git_status__"] = raw.split("\n") if raw else [] def _git_cmd(cmd, **kw): repo = os.path.dirname(__file__) cmd = cmd % dict(repo=repo, **kw) return subprocess.check_output(cmd, shell=True).strip() def version(): git_commit = globals().get("__git_commit__") if git_commit: git_status = globals().get("__git_status__", []) workspace_changed_marker = "*" if git_status else "" return "%s (dev %s%s)" % (__version__, git_commit, workspace_changed_marker) else: return __version__ _try_init_git_attrs()
import os import subprocess __version__ = "0.1.0-1" def _try_init_git_attrs(): try: _init_git_commit() except (OSError, subprocess.CalledProcessError): pass else: try: _init_git_status() except (OSError, subprocess.CalledProcessError): pass def _init_git_commit(): commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1") globals()["__git_commit__"] = commit def _init_git_status(): raw = _git_cmd("git -C \"%(repo)s\" status -s") globals()["__git_status__"] = raw.split("\n") def _git_cmd(cmd, **kw): repo = os.path.dirname(__file__) cmd = cmd % dict(repo=repo, **kw) return subprocess.check_output(cmd, shell=True).strip() def version(): git_commit = globals().get("__git_commit__") if git_commit: git_status = globals().get("__git_status__", []) workspace_changed_marker = "*" if git_status else "" return "%s (dev %s%s)" % (__version__, git_commit, workspace_changed_marker) else: return __version__ _try_init_git_attrs()
Add method to get currently logged in user from http request
package uk.ac.ebi.spot.goci.curation.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import uk.ac.ebi.spot.goci.curation.model.CurrentUser; import uk.ac.ebi.spot.goci.model.SecureUser; import uk.ac.ebi.spot.goci.repository.SecureUserRepository; import javax.servlet.http.HttpServletRequest; import java.security.Principal; /** * Created by emma on 10/02/15. * * @author emma * <p> * Implementation of springs UserDetailsService */ @Service public class CurrentUserDetailsService implements UserDetailsService { // Repository used to find users private SecureUserRepository secureUserRepository; @Autowired public CurrentUserDetailsService(SecureUserRepository secureUserRepository) { this.secureUserRepository = secureUserRepository; } @Override public CurrentUser loadUserByUsername(String email) throws UsernameNotFoundException { // Check user with email exists if (secureUserRepository.findByEmail(email) != null) { SecureUser secureUser = secureUserRepository.findByEmail(email); return new CurrentUser(secureUser); } else { throw new UsernameNotFoundException("User with email: " + email + " " + "was not found"); } } /** * Update a study status * * @param request request from which to obtain current user * @return SecureUser that represents currently logged in user */ public SecureUser getUserFromRequest(HttpServletRequest request) { Principal principal = request.getUserPrincipal(); String name = principal.getName(); return secureUserRepository.findByEmail(name); } }
package uk.ac.ebi.spot.goci.curation.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import uk.ac.ebi.spot.goci.curation.model.CurrentUser; import uk.ac.ebi.spot.goci.model.SecureUser; import uk.ac.ebi.spot.goci.repository.SecureUserRepository; /** * Created by emma on 10/02/15. * * @author emma * <p> * Implementation of springs UserDetailsService */ @Service public class CurrentUserDetailsService implements UserDetailsService { // Repository used to find users private SecureUserRepository secureUserRepository; @Autowired public CurrentUserDetailsService(SecureUserRepository secureUserRepository) { this.secureUserRepository = secureUserRepository; } @Override public CurrentUser loadUserByUsername(String email) throws UsernameNotFoundException { // Check user with email exists if (secureUserRepository.findByEmail(email) != null) { SecureUser secureUser = secureUserRepository.findByEmail(email); return new CurrentUser(secureUser); } else { throw new UsernameNotFoundException("User with email: " + email + " " + "was not found"); } } }
Use @staff_member_required decorator for the dashboard view as well
from django.contrib.admin.views.decorators import staff_member_required from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response from django.contrib import messages try: from django.views.decorators.csrf import csrf_exempt except ImportError: from django.contrib.csrf.middleware import csrf_exempt from .forms import DashboardPreferencesForm from .models import DashboardPreferences @staff_member_required @csrf_exempt def set_preferences(request, dashboard_id): """ This view serves and validates a preferences form. """ try: preferences = DashboardPreferences.objects.get( user=request.user, dashboard_id=dashboard_id ) except DashboardPreferences.DoesNotExist: preferences = None if request.method == "POST": form = DashboardPreferencesForm( user=request.user, dashboard_id=dashboard_id, data=request.POST, instance=preferences ) if form.is_valid(): preferences = form.save() if request.is_ajax(): return HttpResponse('true') messages.success(request, 'Preferences saved') elif request.is_ajax(): return HttpResponse('false') else: form = DashboardPreferencesForm( user=request.user, dashboard_id=dashboard_id, instance=preferences ) return render_to_response('admin_tools/dashboard/preferences_form.html', RequestContext(request, {'form': form}))
from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response from django.contrib import messages try: from django.views.decorators.csrf import csrf_exempt except ImportError: from django.contrib.csrf.middleware import csrf_exempt from .forms import DashboardPreferencesForm from .models import DashboardPreferences @login_required @csrf_exempt def set_preferences(request, dashboard_id): """ This view serves and validates a preferences form. """ try: preferences = DashboardPreferences.objects.get( user=request.user, dashboard_id=dashboard_id ) except DashboardPreferences.DoesNotExist: preferences = None if request.method == "POST": form = DashboardPreferencesForm( user=request.user, dashboard_id=dashboard_id, data=request.POST, instance=preferences ) if form.is_valid(): preferences = form.save() if request.is_ajax(): return HttpResponse('true') messages.success(request, 'Preferences saved') elif request.is_ajax(): return HttpResponse('false') else: form = DashboardPreferencesForm( user=request.user, dashboard_id=dashboard_id, instance=preferences ) return render_to_response('admin_tools/dashboard/preferences_form.html', RequestContext(request, {'form': form}))
Handle case of zero forms more gracefully for JSON option.
const xml2js = require('xml2js'); const parser = new xml2js.Parser({explicitArray: false, attrkey: "attributes"}); const createFormList = require('openrosa-formlist'); const getFormUrls = require('../helpers/get-form-urls'); /** * Searches for XForm XML Files on the file system and * returns valid OpenRosa formList XML. */ module.exports = function (req, res, next) { var options = { headers: { 'User-Agent': 'OpenMapKitServer' }, baseUrl: req.protocol + '://' + req.headers.host + '/public/forms' }; // Look for "json" query param var json = req.query.json || false; getFormUrls(options, function (err, formUrls) { if (err) return next(err); var formListOptions = { headers: options.headers }; createFormList(formUrls, formListOptions, function(err, xml) { if (err) return next(err); // Default is XML, but JSON is an option if(json) { parser.parseString(xml, function (err, result) { if (result === undefined) { res.status(200).json(null); } else { res.status(200).json(result); } }); } else { res.set('content-type', 'text/xml; charset=utf-8'); res.status(200).send(xml); } }); }); };
const xml2js = require('xml2js'); const parser = new xml2js.Parser({explicitArray: false, attrkey: "attributes"}); const createFormList = require('openrosa-formlist'); const getFormUrls = require('../helpers/get-form-urls'); /** * Searches for XForm XML Files on the file system and * returns valid OpenRosa formList XML. */ module.exports = function (req, res, next) { var options = { headers: { 'User-Agent': 'OpenMapKitServer' }, baseUrl: req.protocol + '://' + req.headers.host + '/public/forms' }; // Look for "json" query param var json = req.query.json || false; getFormUrls(options, function (err, formUrls) { if (err) return next(err); var formListOptions = { headers: options.headers }; createFormList(formUrls, formListOptions, function(err, xml) { if (err) return next(err); // Default is XML, but JSON is an option if(json) { parser.parseString(xml, function (err, result) { res.status(200).json(result); }); } else { res.set('content-type', 'text/xml; charset=utf-8'); res.status(200).send(xml); } }); }); };
Fix data source for employees page
define(function(require) { var BasePageView = require('./BasePageView'), TimeSelectorView = require('app/ui/views/TimeSelectorView'), BarChartView = require('app/ui/views/BarChartView'), revenueByCategoryCollection = require('app/models/RevenueByCategoryCollection'), SmallRevenueByCategoryView = require('app/ui/views/SmallRevenueByCategoryView'), timeRangeModel = require('app/models/TimeRangeModel'); require('rdust!templates/employees'); /** * Employee View * @class app.ui.pageviews.EmployeesView * @extends app.ui.pageviews.BasePageView */ var EmployeesView = BasePageView.extend(function() { BasePageView.apply(this, arguments); this.mapChildView({ '.time-selector': { TView: TimeSelectorView, model: timeRangeModel }, '.bar-chart': { TView: BarChartView }, '.revenue-by-category': { TView: SmallRevenueByCategoryView, model: revenueByCategoryCollection } }); }, { /** * The name of the template used by the view * @property {String} template * @default 'example' */ template: 'templates/employees', /** * A class name added to the view container * @property {String} className * @default 'example' */ className: 'employees' }); return EmployeesView; });
define(function(require) { var BasePageView = require('./BasePageView'), TimeSelectorView = require('app/ui/views/TimeSelectorView'), BarChartView = require('app/ui/views/BarChartView'), revenueByEmployeeCollection = require('app/models/RevenueByEmployeeCollection'), SmallRevenueByCategoryView = require('app/ui/views/SmallRevenueByCategoryView'), timeRangeModel = require('app/models/TimeRangeModel'); require('rdust!templates/employees'); /** * Employee View * @class app.ui.pageviews.EmployeesView * @extends app.ui.pageviews.BasePageView */ var EmployeesView = BasePageView.extend(function() { BasePageView.apply(this, arguments); this.mapChildView({ '.time-selector': { TView: TimeSelectorView, model: timeRangeModel }, '.bar-chart': { TView: BarChartView }, '.revenue-by-category':{ TView: SmallRevenueByCategoryView, model: revenueByEmployeeCollection } }); }, { /** * The name of the template used by the view * @property {String} template * @default 'example' */ template: 'templates/employees', /** * A class name added to the view container * @property {String} className * @default 'example' */ className: 'employees' }); return EmployeesView; });
Remove call to class_basename which only exists when Laravel is used.
<?php namespace Dxi\Commands\Dataset\Contact; use Dxi\Commands\Command; class Create extends Command { /** * Get the payload for the command * * @return array */ public function getRequiredParams() { return [ 'firstname', 'dataset', [ 'ddi_home', 'ddi_mobile', 'ddi_work' ] ]; } /** * Set the phone number * * @param $phone * @return $this */ public function getPhone($phone) { $phoneType = (preg_match('/^(07|\+447)/', $phone, $ret) ? 'ddi_mobile' : 'ddi_home'); $this->params[$phoneType] = $phone; return $this; } /** * Get the method for the command * * @return string */ public function getMethod() { return 'ecnow_records'; } /** * Get the url path * * @return string */ public function getUrlPath() { return '/ecnow.php'; } /** * Get the action for the command * * @return string */ public function getAction() { return 'create'; } }
<?php namespace Dxi\Commands\Dataset\Contact; use Dxi\Commands\Command; class Create extends Command { /** * Get the payload for the command * * @return array */ public function getRequiredParams() { return [ 'firstname', 'dataset', [ 'ddi_home', 'ddi_mobile', 'ddi_work' ] ]; } /** * Set the phone number * * @param $phone * @return $this */ public function getPhone($phone) { $phoneType = (preg_match('/^(07|\+447)/', $phone, $ret) ? 'ddi_mobile' : 'ddi_home'); $this->params[$phoneType] = $phone; return $this; } /** * Get the method for the command * * @return string */ public function getMethod() { return 'ecnow_records'; } /** * Get the url path * * @return string */ public function getUrlPath() { return '/ecnow.php'; } /** * Get the action for the command * * @return string */ public function getAction() { return strtolower(class_basename(__CLASS__)); } }
Solve RuntimeWarning that arose without knowing why.
from setuptools import setup, find_packages import sys, os setup(name='cc.license', version='0.01', description="License selection based on ccREL-based metadata.", classifiers=[], keywords='', author='Creative Commons', author_email='[email protected]', url='http://wiki.creativecommons.org/CcLicense', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, #package_data={'cc.license': ['*.xml', '*.txt']}, # doesn't work data_files=[('cc/license/rdf', ['license.rdf/rdf/index.rdf', 'license.rdf/rdf/selectors.rdf', 'license.rdf/rdf/jurisdictions.rdf']), ('cc/license/xml', ['license.rdf/xml/questions.xml'])], zip_safe=False, test_suite='nose.collector', install_requires=[ 'setuptools', 'zope.interface', 'nose', 'Genshi', 'pylons', # XXX why does nose throw a RuntimeWarning without this? ], setup_requires=['setuptools-git',], entry_points=""" # -*- Entry points: -*- [nose.plugins] pylons = pylons.test:PylonsPlugin """, )
from setuptools import setup, find_packages import sys, os setup(name='cc.license', version='0.01', description="License selection based on ccREL-based metadata.", classifiers=[], keywords='', author='Creative Commons', author_email='[email protected]', url='http://wiki.creativecommons.org/CcLicense', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, #package_data={'cc.license': ['*.xml', '*.txt']}, # doesn't work data_files=[('cc/license/rdf', ['license.rdf/rdf/index.rdf', 'license.rdf/rdf/selectors.rdf', 'license.rdf/rdf/jurisdictions.rdf']), ('cc/license/xml', ['license.rdf/xml/questions.xml'])], zip_safe=False, test_suite='nose.collector', install_requires=[ 'setuptools', 'zope.interface', 'nose', 'Genshi', ], setup_requires=['setuptools-git',], entry_points=""" # -*- Entry points: -*- """, )
Change the alerts viirs response to unify with the others alerts
'use strict'; var logger = require('logger'); var imageService = require('services/imageService'); var analysisService = require('services/analysisService'); class VIIRSPresenter { static * transform(results, layer, subscription, begin, end) { logger.debug('Obtaining fires'); let alerts = yield analysisService.execute(subscription, layer.slug, begin, end, true); if(alerts && alerts.length && alerts.length > 0){ let alertsFormat = []; let length = 10; if(alerts.length < 10){ length = alerts.length; } for(let i=0; i < length; i++){ try{ alertsFormat.push({ acq_date: alerts[i].acqDate.split('T')[0], acq_time: `${alerts[i].acqTime.substr(0, 2)}:${alerts[i].acqTime.substr(2, 4)}`, latitude: alerts[i].latitude, longitude: alerts[i].longitude }); }catch(err){ logger.error(err); throw err; } } logger.debug('Alerts formated', alertsFormat); results.alerts = alertsFormat; } results.alert_count = results.value; results.map_image = yield imageService.overviewImage(subscription); return results; } } module.exports = VIIRSPresenter;
'use strict'; var logger = require('logger'); var imageService = require('services/imageService'); var analysisService = require('services/analysisService'); class VIIRSPresenter { static * transform(results, layer, subscription, begin, end) { logger.debug('Obtaining fires'); let alerts = yield analysisService.execute(subscription, layer.slug, begin, end, true); if(alerts && alerts.length && alerts.length > 0){ let alertsFormat = []; let length = 10; if(alerts.length < 10){ length = alerts.length; } for(let i=0; i < length; i++){ try{ alertsFormat.push({ acq_date: alerts[i].acqDate.split('T')[0], acq_time: `${alerts[i].acqTime.substr(0, 2)}:${alerts[i].acqTime.substr(2, 4)}`, latitude: alerts[i].latitude, longitude: alerts[i].longitude }); }catch(err){ logger.error(err); throw err; } } logger.debug('Alerts formated', alertsFormat); results.fire_alerts = alertsFormat; } results.alert_count = results.value; results.map_image = yield imageService.overviewImage(subscription); return results; } } module.exports = VIIRSPresenter;
Disable the style checking for now
'use strict'; var path = require('path'); var webpack = require('webpack'); var autoprefixer = require('autoprefixer'); var ExtractTextPlugin = require("extract-text-webpack-plugin"); var styleLintPlugin = require('stylelint-webpack-plugin'); require('es6-promise').polyfill(); module.exports = { entry: './src/js/main.js', output: { path: __dirname, filename: 'js/app.js' }, plugins: [ // Specify the resulting CSS filename new ExtractTextPlugin('css/app.css'), // Stylelint plugin // new styleLintPlugin({ // configFile: '.stylelintrc', // context: '', // files: '**/*.scss', // syntax: 'scss', // failOnError: false, // quiet: false // }) ], module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.scss$/, loader: ExtractTextPlugin.extract( 'style-loader', 'css-loader!postcss!sass-loader?outputStyle=expanded' ) } ] }, postcss: [ autoprefixer({ browsers: ['last 2 versions'] }) ], stats: { // Colored output colors: true }, // Create Sourcemaps for the bundle devtool: 'source-map' };
'use strict'; var path = require('path'); var webpack = require('webpack'); var autoprefixer = require('autoprefixer'); var ExtractTextPlugin = require("extract-text-webpack-plugin"); var styleLintPlugin = require('stylelint-webpack-plugin'); require('es6-promise').polyfill(); module.exports = { entry: './src/js/main.js', output: { path: __dirname, filename: 'js/app.js' }, plugins: [ // Specify the resulting CSS filename new ExtractTextPlugin('css/app.css'), // Stylelint plugin new styleLintPlugin({ configFile: '.stylelintrc', context: '', files: '**/*.scss', syntax: 'scss', failOnError: false, quiet: false }) ], module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.scss$/, loader: ExtractTextPlugin.extract( 'style-loader', 'css-loader!postcss!sass-loader?outputStyle=expanded' ) } ] }, postcss: [ autoprefixer({ browsers: ['last 2 versions'] }) ], stats: { // Colored output colors: true }, // Create Sourcemaps for the bundle devtool: 'source-map' };
Update and fix sass gulp path
var gulp = require('gulp'), browserSync = require('browser-sync'), sass = require('gulp-sass'), bower = require('gulp-bower'), notify = require('gulp-notify'), reload = browserSync.reload, bs = require("browser-sync").create(), Hexo = require('hexo'), hexo = new Hexo(process.cwd(), {}); var src = { scss: './scss/', css: './source/css', ejs: 'layout' }; // Static Server + watching scss/html files gulp.task('serve', ['sass'], function() { // init starts the server bs.init({ baseDir: "../../public" }); // hexo.call('generate', {}).then(function(){ // console.log('Generating Files'); // }); // Now call methods on bs instead of the // main browserSync module export bs.reload("*.html"); bs.reload("*.css"); }); // Compile sass into CSS gulp.task('sass', function() { // gulp.src(src.scss + "/*/*.scss") gulp.src(src.scss + "{,*}/*.scss") .pipe(sass({})) // .pipe(gulp.dest(src.css)) .pipe(gulp.dest('./css/')) .pipe(reload({stream: true})); }); gulp.task('sass:watch', function () { gulp.watch('./scss/**/*.scss', ['sass']); }); gulp.task('bower', function() { return bower() .pipe(gulp.dest('source/lib')) }); gulp.task('default', ['serve']);
var gulp = require('gulp'), browserSync = require('browser-sync'), sass = require('gulp-sass'), bower = require('gulp-bower'), notify = require('gulp-notify'), reload = browserSync.reload, bs = require("browser-sync").create(), Hexo = require('hexo'), hexo = new Hexo(process.cwd(), {}); var src = { scss: 'scss', css: 'source/css', ejs: 'layout' }; // Static Server + watching scss/html files gulp.task('serve', ['sass'], function() { // init starts the server bs.init({ baseDir: "../../public" }); // hexo.call('generate', {}).then(function(){ // console.log('Generating Files'); // }); // Now call methods on bs instead of the // main browserSync module export bs.reload("*.html"); bs.reload("*.css"); }); // Compile sass into CSS gulp.task('sass', function() { gulp.src(src.scss) .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest(src.css)) .pipe(reload({stream: true})); }); gulp.task('sass:watch', function () { gulp.watch('./scss/**/*.scss', ['sass']); }); gulp.task('bower', function() { return bower() .pipe(gulp.dest('source/lib')) }); gulp.task('default', ['serve']);
Clean up some console chatter
var hooks = require('hooks'); var async = require('async'); function Renderable(View) { this.data = {}; this.mode = 'main'; this.view = {}; if (typeof View === 'function') { this.view = new View(); } this.render = function(cb) { // recursively render any Renderable objects inside this.data // this currently has one flaw, Renderable objects cannot be in nested objects, // or you need to render them manually var renders = []; var item; for (item in this.data) { // Intent of hasOwnProperty check is handled by constructor test. // noinspection JSUnfilteredForInLoop if (this.data[item].constructor.name === 'Renderable') { renders.push(function(item, next) { this.data[item].render(function(rendered) { this.data[item] = rendered; next(false); }.bind(this)); }.bind(this, item)); } } async.parallel( renders, function(err) { if (err) { cb(err) } else { this.view.data(this.data).mode(this.mode).render(cb); } }.bind(this)); } } for (var k in hooks) { // Per hooks module documentation // noinspection JSUnfilteredForInLoop Renderable[k] = Renderable.prototype[k] = hooks[k]; } module.exports = Renderable;
var hooks = require('hooks'); var async = require('async'); function Renderable(View) { this.data = {}; this.mode = 'main'; this.view = {}; if (typeof View === 'function') { this.view = new View(); } this.render = function(cb) { // recursively render any Renderable objects inside this.data // this currently has one flaw, Renderable objects cannot be in nested objects, // or you need to render them manually var renders = []; var item; console.log(this.data); for (item in this.data) { // Intent of hasOwnProperty check is handled by constructor test. // noinspection JSUnfilteredForInLoop if (this.data[item].constructor.name === 'Renderable') { renders.push(function(item, next) { this.data[item].render(function(rendered) { console.log(rendered); this.data[item] = rendered; next(false); }.bind(this)); }.bind(this, item)); } } async.parallel( renders, function(err) { if (err) { cb(err) } else { this.view.data(this.data).mode(this.mode).render(cb); } }.bind(this)); } } for (var k in hooks) { // Per hooks module documentation // noinspection JSUnfilteredForInLoop Renderable[k] = Renderable.prototype[k] = hooks[k]; } module.exports = Renderable;
Read lib dir, before local dir.
#!/usr/bin/env python3 from os import scandir from sys import argv from platform import uname from pathlib import Path filename_template = """ # ------------------------------------------------------------------------------- # filename: {filename} # ------------------------------------------------------------------------------- {data} # ------------------------------------------------------------------------------- # END # ------------------------------------------------------------------------------- """ def read_and_format_data(filename, outbuf): """ Read file and format Args: filename: Returns: str """ with open(filename, 'r') as inbuf: data = inbuf.read() data = filename_template.format(filename=filename, data=data) outbuf.write(data) def main(args): parent_dir = Path(args[0]).parent lib_dir = parent_dir.joinpath('lib') hostname = uname()[1] local_dir = parent_dir.joinpath('local') outfilename = parent_dir.joinpath("zsh_plugins.zsh") with open(str(outfilename), 'w') as outbuf: for filename in scandir(str(local_dir)): filename = Path(filename.path) if filename.stem == hostname: read_and_format_data(str(filename), outbuf) for filename in scandir(str(lib_dir)): read_and_format_data(filename.path, outbuf) if __name__ == "__main__": main(argv)
#!/usr/bin/env python3 from os import scandir from sys import argv from platform import uname from pathlib import Path filename_template = """ # ------------------------------------------------------------------------------- # filename: {filename} # ------------------------------------------------------------------------------- {data} # ------------------------------------------------------------------------------- # END # ------------------------------------------------------------------------------- """ def read_and_format_data(filename, outbuf): """ Read file and format Args: filename: Returns: str """ with open(filename, 'r') as inbuf: data = inbuf.read() data = filename_template.format(filename=filename, data=data) outbuf.write(data) def main(args): parent_dir = Path(args[0]).parent lib_dir = parent_dir.joinpath('lib') hostname = uname()[1] local_dir = parent_dir.joinpath('local') outfilename = parent_dir.joinpath("zsh_plugins.zsh") with open(str(outfilename), 'w') as outbuf: for filename in scandir(str(lib_dir)): read_and_format_data(filename.path, outbuf) for filename in scandir(str(local_dir)): filename = Path(filename.path) if filename.stem == hostname: read_and_format_data(str(filename), outbuf) if __name__ == "__main__": main(argv)
Fix high cpu usage through sleep
import thread import json import time from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer from game import Game def client_thread(game, conn, data): player = game.add_player(conn, data) while True: answer_data = game.wait_for_answer(player) if answer_data: conn.sendMessage(answer_data) request = conn.wait() print request # Thread loop ended conn.sendClose() class CartetsServer(WebSocket): def handleMessage(self): if not self.data: return {} try: data = json.loads(self.data.decode('utf-8')) value = data['action'] except Exception: data = {} value = '' if value == 'init': thread.start_new_thread(client_thread, (game, self, data)) # self.sendMessage(str(self.data)) return data def handleConnected(self): print self.address, 'connected' def handleClose(self): print self.address, 'closed' def wait(self): while True: data = self.handleMessage() if data: break else: time.sleep(0.5) return data game = Game() server = SimpleWebSocketServer('', 8080, CartetsServer) server.serveforever()
import thread import json from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer from game import Game def client_thread(game, conn, data): player = game.add_player(conn, data) while True: answer_data = game.wait_for_answer(player) if answer_data: conn.sendMessage(answer_data) request = conn.wait() print request # Thread loop ended conn.sendClose() class CartetsServer(WebSocket): def handleMessage(self): if not self.data: return {} try: data = json.loads(self.data.decode('utf-8')) value = data['action'] except Exception: data = {} value = '' if value == 'init': thread.start_new_thread(client_thread, (game, self, data)) # self.sendMessage(str(self.data)) return data def handleConnected(self): print self.address, 'connected' def handleClose(self): print self.address, 'closed' def wait(self): while True: data = self.handleMessage() if data: break return data game = Game() server = SimpleWebSocketServer('', 8080, CartetsServer) server.serveforever()
Use tresdb-key in attachment generation
var db = require('tresdb-db'); var keygen = require('tresdb-key'); exports.count = function (callback) { // Count non-deleted attachments // // Parameters: // callback // function (err, number) // db.collection('attachments').countDocuments({ deleted: false, }) .then(function (number) { return callback(null, number); }) .catch(function (err) { return callback(err); }); }; exports.create = function (params, callback) { // Parameters: // params: // username // string // filepath // string or null // The relative path of the file in the uploads dir // mimetype // string or null // thumbfilepath // string or null // The relative path of the thumbnail file in the uploads dir // thumbmimetype // string or null // callback // function (err, attachment) var attachment = { key: keygen.generate(), user: params.username, time: timestamp(), deleted: false, filepath: params.filepath, mimetype: params.mimetype, thumbfilepath: params.thumbfilepath, thumbmimetype: params.thumbmimetype, }; db.collection('attachments').insertOne(attachment, function (err) { if (err) { // TODO key already exists return callback(err); } return callback(null, attachment); }); };
var db = require('tresdb-db'); exports.count = function (callback) { // Count non-deleted attachments // // Parameters: // callback // function (err, number) // db.collection('attachments').countDocuments({ deleted: false, }) .then(function (number) { return callback(null, number); }) .catch(function (err) { return callback(err); }); }; exports.create = function (params, callback) { // Parameters: // params: // username // string // filepath // string or null // The relative path of the file in the uploads dir // mimetype // string or null // thumbfilepath // string or null // The relative path of the thumbnail file in the uploads dir // thumbmimetype // string or null // callback // function (err, attachment) var attachment = { key: generate() user: params.username, time: timestamp(), deleted: false, filepath: params.filepath, mimetype: params.mimetype, thumbfilepath: params.thumbfilepath, thumbmimetype: params.thumbmimetype, }; db.collection('attachments').insertOne(attachment, function (err) { if (err) { // TODO key already exists return callback(err); } return callback(null, attachment); }); };
Set type of the button to submit.
<?php namespace RKA; use Zend\Form\Form; use Zend\InputFilter\InputFilterProviderInterface; class ExampleForm extends Form implements InputFilterProviderInterface { public function init() { $this->add([ 'name' => 'email', 'options' => [ 'label' => 'Email address', ], 'attributes' => [ 'id' => 'email', 'class' => 'form-control', 'required' => 'required', ], ]); $this->add([ 'name' => 'submit', 'type' => 'button', 'options' => [ 'label' => 'Go!', ], 'attributes' => [ 'class' => 'btn btn-default', 'type' => 'submit', ], ]); } public function getInputFilterSpecification() { return [ 'email' => [ 'required' => true, 'filters' => [ ['name' => 'StringTrim'], ['name' => 'StripTags'], ], 'validators' => [ ['name' => 'EmailAddress'], ], ], ]; } }
<?php namespace RKA; use Zend\Form\Form; use Zend\InputFilter\InputFilterProviderInterface; class ExampleForm extends Form implements InputFilterProviderInterface { public function init() { $this->add([ 'name' => 'email', 'options' => [ 'label' => 'Email address', ], 'attributes' => [ 'id' => 'email', 'class' => 'form-control', 'required' => 'required', ], ]); $this->add([ 'name' => 'submit', 'type' => 'button', 'options' => [ 'label' => 'Go!', ], 'attributes' => [ 'class' => 'btn btn-default', ], ]); } public function getInputFilterSpecification() { return [ 'email' => [ 'required' => true, 'filters' => [ ['name' => 'StringTrim'], ['name' => 'StripTags'], ], 'validators' => [ ['name' => 'EmailAddress'], ], ], ]; } }
Add page and it's method when displaying 404 response
<?php class Loader { private $instance = array(); public function page($name, $method='index') { if ($name==='') { $name = 'home'; } $page = $this->loadClass($name, 'Page'); if ($page === false || method_exists($page, $method) === false) { not_found($name . ($method!='index'?'/'.$method:'')); } else { $page->$method(); } } private function loadFile($name, $package='library', $data=array()) { $vendors =& loadClass('Vendor', 'Core'); $list = $vendors->lists(); foreach ($list as $vendor) { if (file_exists($vendor . '/' . $package . '/' . $name . '.php')) { include ($vendor . '/' . $package . '/' . $name . '.php'); return true; } } return false; } private function loadClass($name, $package='library') { $package = strtolower($package); $name = strtolower($name); if (isset($this->instance[$package]) && isset($this->instance[$package][$name])) { return $this->instance[$package][$name]; } $hasFile = $this->loadFile($name, $package); if ($hasFile === false || class_exists($name) === false) { return false; } $class = new $name(); $this->instance[$package][$name] = $class; return $class; } } ?>
<?php class Loader { private $instance = array(); public function page($name, $method='index') { if ($name==='') { $name = 'home'; } $page = $this->loadClass($name, 'Page'); if ($page === false || method_exists($page, $method) === false) { not_found(); } else { $page->$method(); } } private function loadFile($name, $package='library', $data=array()) { $vendors =& loadClass('Vendor', 'Core'); $list = $vendors->lists(); foreach ($list as $vendor) { if (file_exists($vendor . '/' . $package . '/' . $name . '.php')) { include ($vendor . '/' . $package . '/' . $name . '.php'); return true; } } return false; } private function loadClass($name, $package='library') { $package = strtolower($package); $name = strtolower($name); if (isset($this->instance[$package]) && isset($this->instance[$package][$name])) { return $this->instance[$package][$name]; } $hasFile = $this->loadFile($name, $package); if ($hasFile === false || class_exists($name) === false) { return false; } $class = new $name(); $this->instance[$package][$name] = $class; return $class; } } ?>
Make numba the default implementation, as it beats weave in major parts of the benchmarks now
def dummy_no_impl(*args, **kwargs): raise NotImplementedError("You may need to install another package (numpy, " "weave, or numba) to access a working implementation.") from .aggregate_purepy import aggregate as aggregate_py aggregate = aggregate_py try: import numpy as np except ImportError: aggregate_np = aggregate_ufunc = dummy_no_impl multi_arange = multi_cumsum = label_contiguous_1d = dummy_no_impl else: from .aggregate_numpy import aggregate aggregate_np = aggregate from .aggregate_numpy_ufunc import aggregate as aggregate_ufunc from .misc_tools_numpy import (multi_arange, multi_cumsum, label_contiguous_1d, find_contiguous_boundaries, relabel_groups_masked, relabel_groups_unique, unpack) try: try: import weave except ImportError: from scipy import weave except ImportError: aggregate_wv = None else: from .aggregate_weave import aggregate as aggregate_wv, step_indices, step_count aggregate = aggregate_wv try: import numba except ImportError: aggregate_nb = None else: from .aggregate_numba import aggregate as aggregate_nb, step_indices, step_count aggregate = aggregate_nb def uaggregate(group_idx, a, **kwargs): return unpack(group_idx, aggregate(group_idx, a, **kwargs))
def dummy_no_impl(*args, **kwargs): raise NotImplementedError("You may need to install another package (numpy, " "weave, or numba) to access a working implementation.") from .aggregate_purepy import aggregate as aggregate_py aggregate = aggregate_py try: import numpy as np except ImportError: aggregate_np = aggregate_ufunc = dummy_no_impl multi_arange = multi_cumsum = label_contiguous_1d = dummy_no_impl else: from .aggregate_numpy import aggregate aggregate_np = aggregate from .aggregate_numpy_ufunc import aggregate as aggregate_ufunc from .misc_tools_numpy import (multi_arange, multi_cumsum, label_contiguous_1d, find_contiguous_boundaries, relabel_groups_masked, relabel_groups_unique, unpack) try: import numba except ImportError: aggregate_nb = None else: from .aggregate_numba import aggregate as aggregate_nb aggregate = aggregate_nb try: try: import weave except ImportError: from scipy import weave except ImportError: aggregate_wv = None else: from .aggregate_weave import aggregate as aggregate_wv, step_indices, step_count aggregate = aggregate_wv def uaggregate(group_idx, a, **kwargs): return unpack(group_idx, aggregate(group_idx, a, **kwargs))
Add package data to package.
from setuptools import setup, find_packages setup(name='facebookinsights', description='A wrapper and command-line interface for the Facebook Insights API.', long_description=open('README.rst').read(), author='Stijn Debrouwere', author_email='[email protected]', #url='http://stdbrouw.github.com/facebook-insights/', download_url='http://www.github.com/debrouwere/facebook-insights/tarball/master', version='0.3.3', license='ISC', packages=find_packages(), include_package_data=True, keywords='data analytics api wrapper facebook insights', entry_points = { 'console_scripts': [ 'insights = insights.commands:main', ], }, install_requires=[ 'click', 'requests', 'rauth', 'facepy', 'python-dateutil', 'pytz', 'addressable', 'flask', 'keyring', ], # test_suite='facebookinsights.tests', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Scientific/Engineering :: Information Analysis', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ], )
from setuptools import setup, find_packages setup(name='facebookinsights', description='A wrapper and command-line interface for the Facebook Insights API.', long_description=open('README.rst').read(), author='Stijn Debrouwere', author_email='[email protected]', #url='http://stdbrouw.github.com/facebook-insights/', download_url='http://www.github.com/debrouwere/facebook-insights/tarball/master', version='0.3.3', license='ISC', packages=find_packages(), keywords='data analytics api wrapper facebook insights', entry_points = { 'console_scripts': [ 'insights = insights.commands:main', ], }, install_requires=[ 'click', 'requests', 'rauth', 'facepy', 'python-dateutil', 'pytz', 'addressable', 'flask', 'keyring', ], # test_suite='facebookinsights.tests', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Scientific/Engineering :: Information Analysis', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ], )
Fix check for valid resolver_match
from django.template import Library from django.template.defaulttags import URLNode, url from django.utils.html import escape, mark_safe register = Library() class MenuLINode(URLNode): def render(self, context): # Pull out the match and hijack asvar # to be used for the link title match = getattr(context.get('request'), 'resolver_match', None) if self.asvar: title = escape(self.asvar.strip('"\'')) elif match: title = match.url_name # Reset asvar and render to get the URL self.asvar = None menu_url = super(MenuLINode, self).render(context) # Check if we're on the defined page if match and str(self.view_name).strip('"\'') == match.url_name: active_class = ' class="active"' else: active_class = '' return mark_safe('<li%s><a href="%s">%s</a></li>' % \ (active_class, menu_url, title)) @register.tag def menu_li(parser, token, node_cls=MenuLINode): """ Add a menu <li> for Twitter Bootstrap, checking adding the "active" class as needed. """ node_instance = url(parser, token) return node_cls(view_name=node_instance.view_name, args=node_instance.args, kwargs=node_instance.kwargs, asvar=node_instance.asvar)
from django.template import Library from django.template.defaulttags import URLNode, url from django.utils.html import escape, mark_safe register = Library() class MenuLINode(URLNode): def render(self, context): # Pull out the match and hijack asvar # to be used for the link title request = context.get('request') if self.asvar: title = escape(self.asvar.strip('"\'')) elif request: title = request.resolver_match.url_name # Reset asvar and render to get the URL self.asvar = None menu_url = super(MenuLINode, self).render(context) # Check if we're on the defined page if request and str(self.view_name).strip('"\'') == \ request.resolver_match.url_name: active_class = ' class="active"' else: active_class = '' return mark_safe('<li%s><a href="%s">%s</a></li>' % \ (active_class, menu_url, title)) @register.tag def menu_li(parser, token, node_cls=MenuLINode): """ Add a menu <li> for Twitter Bootstrap, checking adding the "active" class as needed. """ node_instance = url(parser, token) return node_cls(view_name=node_instance.view_name, args=node_instance.args, kwargs=node_instance.kwargs, asvar=node_instance.asvar)
Support extra params on event manager
;(function(){ var binder = window.addEventListener ? 'addEventListener' : 'attachEvent' , unbinder = window.removeEventListener ? 'removeEventListener' : 'detachEvent' , eventPrefix = binder !== 'addEventListener' ? 'on' : ''; function bind(el, type, fn, capture) { el[binder](eventPrefix + type, fn, capture || false); return fn; } function unbind(el, type, fn, capture) { el[unbinder](eventPrefix + type, fn, capture || false); return fn; } function EventManager(el, obj) { if (!(this instanceof EventManager)) return new EventManager(el, obj); if (!el) throw new Error('Element missing'); // TODO make this optional (for regular event binding) if (!obj) throw new Error('Object missing'); this.el = el; this.obj = obj; this.eventSubscriptionList = {}; } EventManager.prototype.bind = function(evt, fn) { var obj = this.obj , el = this.el , args = [].slice.call(arguments, 2); function cb(e) { var a = [].slice.call(arguments).concat(args); fn.apply(obj, a); } this.eventSubscriptionList[evt] = cb; bind(el, evt, cb); return cb; }; // TODO this needs to be able to accept method names and not just callbacks EventManager.prototype.unbind = function(evt) { var obj = this.obj , el = this.el , cb = this.eventSubscriptionList[evt]; unbind(el, evt, cb); }; window.EventManager = EventManager; })();
;(function(){ var binder = window.addEventListener ? 'addEventListener' : 'attachEvent' , unbinder = window.removeEventListener ? 'removeEventListener' : 'detachEvent' , eventPrefix = binder !== 'addEventListener' ? 'on' : ''; function bind(el, type, fn, capture) { el[binder](eventPrefix + type, fn, capture || false); return fn; } function unbind(el, type, fn, capture) { el[unbinder](eventPrefix + type, fn, capture || false); return fn; } function EventManager(el, obj) { if (!(this instanceof EventManager)) return new EventManager(el, obj); if (!el) throw new Error('Element missing'); // TODO make this optional (for regular event binding) if (!obj) throw new Error('Object missing'); this.el = el; this.obj = obj; this.eventSubscriptionList = {}; } EventManager.prototype.bind = function(evt, fn) { var obj = this.obj , el = this.el; function cb(e) { fn.call(obj, e); } this.eventSubscriptionList[evt] = cb; bind(el, evt, cb); return cb; }; // TODO this needs to be able to accept method names and not just callbacks EventManager.prototype.unbind = function(evt) { var obj = this.obj , el = this.el , cb = this.eventSubscriptionList[evt]; unbind(el, evt, cb); return cb; }; window.EventManager = EventManager; })();
Make the "check" command available via the Werkzeug extension.
import logging from webassets.script import CommandLineEnvironment __all__ = ('make_assets_action',) def make_assets_action(environment, loaders=[]): """Creates a ``werkzeug.script`` action which interfaces with the webassets command line tools. Since Werkzeug does not provide a way to have subcommands, we need to model the assets subcommands as options. If ``loaders`` is given, the command will use these loaders to add bundles to the environment. This is mainly useful if you are defining your bundles inside templates only, and need to find them first using something like the Jinja2Loader. """ log = logging.getLogger('webassets') log.addHandler(logging.StreamHandler()) def action(rebuild=False, watch=False, check=False, clean=False, quiet=('q', False), verbose=('v', False)): if len(filter(bool, [rebuild, watch, clean, check])) != 1: print "Error: exactly one of --rebuild, --watch, --check or --clean must be given" return 1 if rebuild: command = 'rebuild' elif watch: command = 'watch' elif clean: command = 'clean' elif check: command = 'check' log.setLevel(logging.DEBUG if verbose else (logging.WARNING if quiet else logging.INFO)) cmdenv = CommandLineEnvironment(environment, log) if loaders: log.info('Finding bundles...') for loader in loaders: environment.add(*[b for b in loader.load_bundles() if not b.is_container]) cmdenv.invoke(command) return action
import logging from webassets.script import CommandLineEnvironment __all__ = ('make_assets_action',) def make_assets_action(environment, loaders=[]): """Creates a ``werkzeug.script`` action which interfaces with the webassets command line tools. Since Werkzeug does not provide a way to have subcommands, we need to model the assets subcommands as options. If ``loaders`` is given, the command will use these loaders to add bundles to the environment. This is mainly useful if you are defining your bundles inside templates only, and need to find them first using something like the Jinja2Loader. """ log = logging.getLogger('webassets') log.addHandler(logging.StreamHandler()) def action(rebuild=False, watch=False, clean=False, quiet=('q', False), verbose=('v', False)): if len(filter(bool, [rebuild, watch, clean])) != 1: print "Error: exactly one of --rebuild, --watch or --clean must be given" return 1 if rebuild: command = 'rebuild' elif watch: command = 'watch' elif clean: command = 'clean' log.setLevel(logging.DEBUG if verbose else (logging.WARNING if quiet else logging.INFO)) cmdenv = CommandLineEnvironment(environment, log) if loaders: log.info('Finding bundles...') for loader in loaders: environment.add(*[b for b in loader.load_bundles() if not b.is_container]) cmdenv.invoke(command) return action
Add token to perform a full content swap
<?php namespace Concrete\Core\Backup\ContentImporter\Importer\Routine; use Concrete\Core\Attribute\Type; use Concrete\Core\Block\BlockType\BlockType; use Concrete\Core\Package\Package; use Concrete\Core\Permission\Category; use Concrete\Core\Support\Facade\Facade; use Concrete\Core\Validation\BannedWord\BannedWord; use Concrete\Core\Package\PackageService; use Concrete\Core\Validation\CSRF\Token; class ImportPackagesRoutine extends AbstractRoutine { public function getHandle() { return 'packages'; } public function import(\SimpleXMLElement $sx) { if (isset($sx->packages)) { foreach ($sx->packages->package as $p) { $pkg = Package::getByHandle((string) $p['handle']); if (!$pkg) { $pkgClass = Package::getClass((string) $p['handle']); if ($pkgClass) { $app = Facade::getFacadeApplication(); $service = $app->make(PackageService::class); /** @var Token $token */ $token = $app->make(Token::class); $data = []; if (isset($p['full-content-swap'])) { $data["pkgDoFullContentSwap"] = true; // set this token to perform a full content swap when installing starting point packages $data["ccm_token"] = $token->generate("install_options_selected"); if (isset($p['content-swap-file'])) { $data["contentSwapFile"] = (string)$p['content-swap-file']; } else { $data["contentSwapFile"] = "content.xml"; } } $service->install($pkgClass, $data); } } } } } }
<?php namespace Concrete\Core\Backup\ContentImporter\Importer\Routine; use Concrete\Core\Attribute\Type; use Concrete\Core\Block\BlockType\BlockType; use Concrete\Core\Package\Package; use Concrete\Core\Permission\Category; use Concrete\Core\Support\Facade\Facade; use Concrete\Core\Validation\BannedWord\BannedWord; use Concrete\Core\Package\PackageService; class ImportPackagesRoutine extends AbstractRoutine { public function getHandle() { return 'packages'; } public function import(\SimpleXMLElement $sx) { if (isset($sx->packages)) { foreach ($sx->packages->package as $p) { $pkg = Package::getByHandle((string) $p['handle']); if (!$pkg) { $pkgClass = Package::getClass((string) $p['handle']); if ($pkgClass) { $app = Facade::getFacadeApplication(); $service = $app->make(PackageService::class); $data = []; if (isset($p['full-content-swap'])) { $data["pkgDoFullContentSwap"] = true; } if (isset($p['content-swap-file'])) { $data["contentSwapFile"] = (string)$p['content-swap-file']; } $service->install($pkgClass, $data); } } } } } }
Update check update error handler.
(function () { function showMessage(message, type) { $('#check-update-info a.close').trigger('click.fndtn.alert'); var alertBox = '<div data-alert id="check-update-info" class="alert-box ' + type + '">' + message + '<a href="#" class="close">&times;</a> ' + '</div>'; $(".large-10").prepend(alertBox).foundation(); } function showLoading() { var loading = '<div id="loading" class="alert-box loader"><img src="/static/img/loader.gif" alt="Loading..." /></div>'; $(".large-10").prepend(loading); } function hideLoading() { $('#loading').remove(); } $("#checkupdate").bind('click', function (event) { $.ajax({ url: "/api/checkupdate", type: "get", dataType: "json", beforeSend: function (xhr) { $('#check-update-info a.close').trigger('click.fndtn.alert'); showLoading(); }, success: function (res, status, xhr) { console.log(res); var message = res.message + '<a class="box-link" href="/docs/update">点此</a>查看升级方法。' showMessage(message, 'success'); }, complete: function (xhr, status) { hideLoading(); }, error: function (xhr, status, thrown) { var err = xhr.responseJSON; console.log(err); showMessage(err ? err.message : '检测更新失败!', 'alert'); } }); }); })();
(function () { function showMessage(message, type) { $('#check-update-info a.close').trigger('click.fndtn.alert'); var alertBox = '<div data-alert id="check-update-info" class="alert-box ' + type + '">' + message + '<a href="#" class="close">&times;</a> ' + '</div>'; $(".large-10").prepend(alertBox).foundation(); } function showLoading() { var loading = '<div id="loading" class="alert-box loader"><img src="/static/img/loader.gif" alt="Loading..." /></div>'; $(".large-10").prepend(loading); } function hideLoading() { $('#loading').remove(); } $("#checkupdate").bind('click', function (event) { $.ajax({ url: "/api/checkupdate", type: "get", dataType: "json", beforeSend: function (xhr) { $('#check-update-info a.close').trigger('click.fndtn.alert'); showLoading(); }, success: function (res, status, xhr) { console.log(res); var message = res.message + '<a class="box-link" href="/docs/update">点此</a>查看升级方法。' showMessage(message, 'success'); }, complete: function (xhr, status) { hideLoading(); }, error: function (xhr, status, thrown) { var err = xhr.responseJSON; console.log(err); showMessage(err.message, 'alert'); } }); }); })();
Extend Broadcast protocol abstraction with a Handler interface for message delivery
from abc import ABCMeta, abstractmethod import socket, json class Broadcast(metaclass=ABCMeta): """ An interface for defining a broadcast protocol. The 'propose' and 'decide' methods need to be defined """ BUFFER_SIZE = 1024 def __init__(self, peer_list): self.peers = peer_list def broadcast(self, message_type, message): """ Sends a message to all of the nodes in the network. :param message_type: The type of message to be sent. :param message: The message to be sent. :return: """ def _broadcast(final_msg): final_msg = final_msg.encode('utf-8') for addr in self.peers: broadcast_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) broadcast_client.connect(addr) broadcast_client.sendall(final_msg) broadcast_client.shutdown(socket.SHUT_RD) broadcast_client.close() message = {"peer": socket.gethostname(), "type": message_type, "message": message} message = json.dumps(message) _broadcast(message) @abstractmethod def broadcast_listener(self): pass class IBroadcastHandler(metaclass=ABCMeta): """ An interface for providing the deliver event of a broadcast protocol """ @abstractmethod def deliver(self, message): pass
from abc import ABCMeta, abstractmethod import socket, json class Broadcast(metaclass=ABCMeta): """ An interface for defining a broadcast protocol. The 'propose' and 'decide' methods need to be defined """ BUFFER_SIZE = 1024 def __init__(self, peer_list): self.peers = peer_list def broadcast(self, message_type, message): """ Sends a message to all of the nodes in the network. :param message_type: The type of message to be sent. :param message: The message to be sent. :return: """ def _broadcast(final_msg): final_msg = final_msg.encode('utf-8') for addr in self.peers: broadcast_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) broadcast_client.connect(addr) broadcast_client.sendall(final_msg) broadcast_client.shutdown(socket.SHUT_RD) broadcast_client.close() message = {"source": socket.gethostname(), "type": message_type, "message": message} message = json.dumps(message) _broadcast(message) @abstractmethod def broadcast_listener(self): pass @abstractmethod def deliver(self, message): pass
Fix check user is active by email or username
<?php namespace Passengers\Event; use Cake\Event\Event; use Cake\Event\EventListenerInterface; use Cake\Controller\Component\AuthComponent; use Cake\Core\Configure; use Cake\Core\Plugin; use Cake\ORM\Association; use Cake\ORM\Tableregistry; class SignInEvent implements EventListenerInterface { public function implementedEvents() { return array( 'Controller.Users.beforeSignIn' => array( 'callable' => 'beforeUsersControllerSignIn', ), ); } public function beforeUsersControllerSignIn(Event $event) { $controller = $event->subject(); $active = true; if($controller->request->is('post')){ $userName = ''; if ($controller->request->data('username')) $userName = $controller->request->data('username'); if ($controller->request->data('email')) $userName = $controller->request->data('email'); if($userName) { $active = $controller->Users->find('all', [ 'conditions' => [ 'Users.active' => true, 'OR' => [ 'Users.email' => $userName, 'Users.username' => $userName ] ] ])->count(); } } if(!$active){ $event->stopPropagation(); return __d('passengers', 'Sorry, but your account has been not activated yet.'); } } }
<?php namespace Passengers\Event; use Cake\Event\Event; use Cake\Event\EventListenerInterface; use Cake\Controller\Component\AuthComponent; use Cake\Core\Configure; use Cake\Core\Plugin; use Cake\ORM\Association; use Cake\ORM\Tableregistry; class SignInEvent implements EventListenerInterface { public function implementedEvents() { return array( 'Controller.Users.beforeSignIn' => array( 'callable' => 'beforeUsersControllerSignIn', ), ); } public function beforeUsersControllerSignIn(Event $event) { $controller = $event->subject(); $active = true; if($controller->request->is('post')){ if($controller->request->data('username') || $controller->request->data('email')) { $active = $controller->Users->find('all', [ 'conditions' => [ 'Users.active' => true, 'OR' => [ 'Users.email' => $controller->request->data('email'), 'Users.username' => $controller->request->data('username') ] ] ])->count(); } } if(!$active){ $event->stopPropagation(); return __d('passengers', 'Sorry, but your account has been not activated yet.'); } } }
Make sure that all requests for static files are correctly hidden from output
from django.conf import settings from django.core.servers.basehttp import WSGIRequestHandler from django.db import connection from devserver.utils.time import ms_from_timedelta from datetime import datetime class SlimWSGIRequestHandler(WSGIRequestHandler): """ Hides all requests that originate from either ``STATIC_URL`` or ``MEDIA_URL`` as well as any request originating with a prefix included in ``DEVSERVER_IGNORED_PREFIXES``. """ def handle(self, *args, **kwargs): self._start_request = datetime.now() return WSGIRequestHandler.handle(self, *args, **kwargs) def log_message(self, format, *args): duration = datetime.now() - self._start_request env = self.get_environ() for url in (settings.STATIC_URL, settings.MEDIA_URL): if self.path.startswith(url): return elif url.startswith('http:'): if ('http://%s%s' % (env['HTTP_HOST'], self.path)).startswith(url): return for path in getattr(settings, 'DEVSERVER_IGNORED_PREFIXES', []): if self.path.startswith(path): return format += " (time: %.2fs; sql: %dms (%dq))" args = list(args) + [ ms_from_timedelta(duration) / 1000, sum(float(c.get('time', 0)) for c in connection.queries) * 1000, len(connection.queries), ] return WSGIRequestHandler.log_message(self, format, *args)
from django.conf import settings from django.core.servers.basehttp import WSGIRequestHandler from django.db import connection from devserver.utils.time import ms_from_timedelta from datetime import datetime class SlimWSGIRequestHandler(WSGIRequestHandler): """ Hides all requests that originate from ```MEDIA_URL`` as well as any request originating with a prefix included in ``DEVSERVER_IGNORED_PREFIXES``. """ def handle(self, *args, **kwargs): self._start_request = datetime.now() return WSGIRequestHandler.handle(self, *args, **kwargs) def log_message(self, format, *args): duration = datetime.now() - self._start_request env = self.get_environ() if settings.MEDIA_URL.startswith('http:'): if ('http://%s%s' % (env['HTTP_HOST'], self.path)).startswith(settings.MEDIA_URL): return # if self.path.startswith(settings.MEDIA_URL): # return for path in getattr(settings, 'DEVSERVER_IGNORED_PREFIXES', []): if self.path.startswith(path): return format += " (time: %.2fs; sql: %dms (%dq))" args = list(args) + [ ms_from_timedelta(duration) / 1000, sum(float(c.get('time', 0)) for c in connection.queries) * 1000, len(connection.queries), ] return WSGIRequestHandler.log_message(self, format, *args)
Allow to use Promises on `discard` function
import { busy, scheduleRetry } from './actions'; import { JS_ERROR } from './constants'; import type { Config, OfflineAction, ResultAction } from './types'; const complete = ( action: ResultAction, success: boolean, payload: {} ): ResultAction => ({ ...action, payload, meta: { ...action.meta, success, completed: true } }); const send = (action: OfflineAction, dispatch, config: Config, retries = 0) => { const metadata = action.meta.offline; dispatch(busy(true)); return config .effect(metadata.effect, action) .then(result => { const commitAction = metadata.commit || { ...config.defaultCommit, meta: { ...config.defaultCommit.meta, offlineAction: action } }; try { dispatch(complete(commitAction, true, result)); } catch (e) { dispatch(complete({ type: JS_ERROR, payload: e }, false)); } }) .catch(async error => { const rollbackAction = metadata.rollback || { ...config.defaultRollback, meta: { ...config.defaultRollback.meta, offlineAction: action } }; // discard let mustDiscard = true try { mustDiscard = await config.discard(error, action, retries) } catch(e) { console.warn(e) } if (!mustDiscard) { const delay = config.retry(action, retries); if (delay != null) { dispatch(scheduleRetry(delay)); return; } } dispatch(complete(rollbackAction, false, error)); }); }; export default send;
import { busy, scheduleRetry } from './actions'; import { JS_ERROR } from './constants'; import type { Config, OfflineAction, ResultAction } from './types'; const complete = ( action: ResultAction, success: boolean, payload: {} ): ResultAction => ({ ...action, payload, meta: { ...action.meta, success, completed: true } }); const send = (action: OfflineAction, dispatch, config: Config, retries = 0) => { const metadata = action.meta.offline; dispatch(busy(true)); return config .effect(metadata.effect, action) .then(result => { const commitAction = metadata.commit || { ...config.defaultCommit, meta: { ...config.defaultCommit.meta, offlineAction: action } }; try { dispatch(complete(commitAction, true, result)); } catch (e) { dispatch(complete({ type: JS_ERROR, payload: e }, false)); } }) .catch(error => { const rollbackAction = metadata.rollback || { ...config.defaultRollback, meta: { ...config.defaultRollback.meta, offlineAction: action } }; // discard if (config.discard(error, action, retries)) { dispatch(complete(rollbackAction, false, error)); return; } const delay = config.retry(action, retries); if (delay != null) { dispatch(scheduleRetry(delay)); return; } dispatch(complete(rollbackAction, false, error)); }); }; export default send;
Test changing tab complete list
package io.github.lasercar.simplemention; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerChatTabCompleteEvent; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Events implements Listener { @EventHandler public void onChat(AsyncPlayerChatEvent event) { String message = event.getMessage(); if (MessageParser.hasMentions(message)) { Pattern pattern = Pattern.compile("@(\\w+)"); Matcher matcher = pattern.matcher(message); StringBuffer messageBuffer = new StringBuffer(); while (matcher.find()) { String mention = matcher.group(1); Player[] playersMatched = PlayerMatcher.findAllByName(mention); if (playersMatched.length > 0) { matcher.appendReplacement(messageBuffer, MessageParser.highlightMention(mention)); SoundManager.pingPlayers(playersMatched); } } matcher.appendTail(messageBuffer); event.setMessage(messageBuffer.toString()); } } @EventHandler public void onTabComplete(PlayerChatTabCompleteEvent event) { // if (event.getLastToken().equals("@")) { // event.getTabCompletions().push(Bukkit.getOnlinePlayers()); // } //DEBUG Bukkit.getLogger().info(event.getTabCompletions().toString()); event.getTabCompletions().clear(); Bukkit.getLogger().info(event.getTabCompletions().toString()); } }
package io.github.lasercar.simplemention; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerChatTabCompleteEvent; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Events implements Listener { @EventHandler public void onChat(AsyncPlayerChatEvent event) { String message = event.getMessage(); if (MessageParser.hasMentions(message)) { Pattern pattern = Pattern.compile("@(\\w+)"); Matcher matcher = pattern.matcher(message); StringBuffer messageBuffer = new StringBuffer(); while (matcher.find()) { String mention = matcher.group(1); Player[] playersMatched = PlayerMatcher.findAllByName(mention); if (playersMatched.length > 0) { matcher.appendReplacement(messageBuffer, MessageParser.highlightMention(mention)); SoundManager.pingPlayers(playersMatched); } } matcher.appendTail(messageBuffer); event.setMessage(messageBuffer.toString()); } } @EventHandler public void onTabComplete(PlayerChatTabCompleteEvent event) { Bukkit.getLogger().info(event.toString()); } }
Reorder keys that were being declared in the wrong place
# -*- coding: utf-8 -*- ''' This thorium state is used to track the status beacon events and keep track of the active status of minions .. versionadded:: 2016.11.0 ''' # Import python libs from __future__ import absolute_import import time import fnmatch def reg(name): ''' Activate this register to turn on a minion status tracking register, this register keeps the current status beacon data and the time that each beacon was last checked in. ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} now = time.time() if 'status' not in __reg__: __reg__['status'] = {} __reg__['status']['val'] = {} for event in __events__: if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'): # Got one! idata = {'recv_time': now} for key in event['data']['data']: if key in ('id', 'recv_time'): continue idata[key] = event['data']['data'][key] __reg__['status']['val'][event['data']['id']] = idata ret['changes'][event['data']['id']] = True return ret
# -*- coding: utf-8 -*- ''' This thorium state is used to track the status beacon events and keep track of the active status of minions .. versionadded:: 2016.11.0 ''' # Import python libs from __future__ import absolute_import import time import fnmatch def reg(name): ''' Activate this register to turn on a minion status tracking register, this register keeps the current status beacon data and the time that each beacon was last checked in. ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} now = time.time() if 'status' not in __reg__: __reg__['status'] = {} __reg__['status']['val'] = {} for event in __events__: if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'): # Got one! idata = {'recv_time': now} for key in event['data']['data']: if key in ('id', 'recv_time'): continue idata[key] = event['data'][key] __reg__['status']['val'][event['data']['data']['id']] = idata ret['changes'][event['data']['data']['id']] = True return ret
Allow ExpressMiddleware without extra prefix
/* * Return express middleware that measures overall performance. */ function factory(parentClient) { return function (prefix, options) { var client = parentClient.getChildClient(prefix || ''); options = options || {}; var timeByUrl = options.timeByUrl || false; var onResponseEnd = options.onResponseEnd; return function (req, res, next) { var startTime = new Date(); // Shadow end request var end = res.end; res.end = function () { end.apply(res, arguments); client.timing('response_time', startTime); client.increment('response.' + res.statusCode); if (timeByUrl && req.route && req.route.path) { var routeName = req.route.path; if (routeName === "/") routeName = "root"; // need to get rid of : in route names, remove first /, and replace rest with _ routeName = routeName.replace(/:/g, "").replace(/\//, "").replace(/\//g, "_"); client.timing('response_time.by_url.' + routeName, startTime); } if (onResponseEnd) { onResponseEnd(client, startTime, req, res); } }; next(); }; }; } module.exports = factory;
/* * Return express middleware that measures overall performance. */ function factory(parentClient) { return function (prefix, options) { var client = parentClient.getChildClient(prefix); options = options || {}; var timeByUrl = options.timeByUrl || false; var onResponseEnd = options.onResponseEnd; return function (req, res, next) { var startTime = new Date(); // Shadow end request var end = res.end; res.end = function () { end.apply(res, arguments); client.timing('response_time', startTime); client.increment('response.' + res.statusCode); if (timeByUrl && req.route && req.route.path) { var routeName = req.route.path; if (routeName === "/") routeName = "root"; // need to get rid of : in route names, remove first /, and replace rest with _ routeName = routeName.replace(/:/g, "").replace(/\//, "").replace(/\//g, "_"); client.timing('response_time.by_url.' + routeName, startTime); } if (onResponseEnd) { onResponseEnd(client, startTime, req, res); } }; next(); }; }; } module.exports = factory;
Fix typo in self.propagate_signal call
from celery import task from django.dispatch.dispatcher import ( _make_id, Signal, ) class AsyncSignal(Signal): def __init__(self, providing_args=None, queue=None): super(AsyncSignal, self).__init__(providing_args=providing_args) self.queue = queue def send(self, sender, **named): """Send the signal via Celery.""" self.propagate_signal.apply_async( args=(sender), kwargs=named, queue=self.queue, ) @task def propagate_signal(self, sender, **named): """ Send signal from sender to all connected receivers catching errors. Arguments: sender The sender of the signal. Can be any python object (normally one registered with a connect if you actually want something to occur). named Named arguments which will be passed to receivers. These arguments must be a subset of the argument names defined in providing_args. Return a list of tuple pairs [(receiver, response), ... ]. May raise DispatcherKeyError. If any receiver raises an error (specifically any subclass of Exception), the error instance is returned as the result for that receiver. """ # Call each receiver with whatever arguments it can accept. for receiver in self._live_receivers(_make_id(sender)): try: receiver(signal=self, sender=sender, **named) except Exception: pass
from celery import task from django.dispatch.dispatcher import ( _make_id, Signal, ) class AsyncSignal(Signal): def __init__(self, providing_args=None, queue=None): super(AsyncSignal, self).__init__(providing_args=providing_args) self.queue = queue def send(self, sender, **named): """Send the signal via Celery.""" self.propogate_signal.apply_async( args=(sender), kwargs=named, queue=self.queue, ) @task def propagate_signal(self, sender, **named): """ Send signal from sender to all connected receivers catching errors. Arguments: sender The sender of the signal. Can be any python object (normally one registered with a connect if you actually want something to occur). named Named arguments which will be passed to receivers. These arguments must be a subset of the argument names defined in providing_args. Return a list of tuple pairs [(receiver, response), ... ]. May raise DispatcherKeyError. If any receiver raises an error (specifically any subclass of Exception), the error instance is returned as the result for that receiver. """ # Call each receiver with whatever arguments it can accept. for receiver in self._live_receivers(_make_id(sender)): try: receiver(signal=self, sender=sender, **named) except Exception: pass
Connect loading and error events to UI
// Main script // ----------- var blackbird = blackbird || {}; blackbird.player = {}; $(document).ready(function() { blackbird.player = new blackbird.Player(blackbird.api_root); // First play blackbird.player.next(); // Create seek slider $("#seek-bar").slider({ min: 0, max: 100, value: 0, range: "min", animate: true, slide: function(event, ui) { blackbird.player.seek(ui.value); } }); // Player control logic $("#prev-btn").click(function() { blackbird.player.previous(); }); $("#next-btn").click(function() { blackbird.player.next(); }); $("#play-btn").click(function() { blackbird.player.pause(); }); // Command line entry $(document).keydown(function(e) { if (e.keyCode==88 && e.altKey) { $("#command-input").val(""); $("#command-input").focus(); } }); // Command line $(document).on("keypress", "#command-input", function(e) { if (e.which == 13) { var cmd = $("#command-input").val(); blackbird.loading(true); $.get( blackbird.player.root + "command", {command: cmd}, function(data) { if (data == "nf") { blackbird.flash(); } blackbird.loading(false); } ); } }); });
// Main script // ----------- var blackbird = blackbird || {}; blackbird.player = {}; $(document).ready(function() { blackbird.player = new blackbird.Player(blackbird.api_root); // First play blackbird.player.next(); // Create seek slider $("#seek-bar").slider({ min: 0, max: 100, value: 0, range: "min", animate: true, slide: function(event, ui) { blackbird.player.seek(ui.value); } }); // Player control logic $("#prev-btn").click(function() { blackbird.player.previous(); }); $("#next-btn").click(function() { blackbird.player.next(); }); $("#play-btn").click(function() { blackbird.player.pause(); }); // Command line entry $(document).keydown(function(e) { if (e.keyCode==88 && e.altKey) { $("#command-input").val(""); $("#command-input").focus(); } }); // Command line $(document).on("keypress", "#command-input", function(e) { if (e.which == 13) { var cmd = $("#command-input").val(); // Show loading $.get( blackbird.player.root + "command", {command: cmd}, function(data) { // Do things here } ); } }); });
Use devtool when developing for easier debugging
var path = require('path'); var webpack = require('webpack'); var isProd = (process.env.NODE_ENV === 'production'); module.exports = { devtool: !isProd && 'eval', entry: { app: './app.js' }, module: { preLoaders: [ { test: /\.js$/, include: /components/, exclude: /node_modules/, loader: 'eslint-loader' } ], loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['react', 'es2015', 'stage-0'], plugins: ['transform-object-assign', 'transform-class-properties'] } } ], noParse: [/autoit.js/] }, output: { filename: './bundle.js' }, plugins:function () { var plugins = [] plugins.push(new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) })); if (isProd) { // Production specific plugins plugins.push(new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, output: { comments: false //Removes comments from minified files }, sourceMap: false //Source maps are slow and unwanted })); } return plugins; }(), resolve: { alias: { components: path.join(__dirname, 'components'), 'mx-react-components': path.join(__dirname, '../src') } } };
var path = require('path'); var webpack = require('webpack'); var isProd = (process.env.NODE_ENV === 'production'); module.exports = { entry: { app: './app.js' }, module: { preLoaders: [ { test: /\.js$/, include: /components/, exclude: /node_modules/, loader: 'eslint-loader' } ], loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['react', 'es2015', 'stage-0'], plugins: ['transform-object-assign', 'transform-class-properties'] } } ], noParse: [/autoit.js/] }, output: { filename: './bundle.js' }, plugins:function () { var plugins = [] plugins.push(new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) })); if (isProd) { // Production specific plugins plugins.push(new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, output: { comments: false //Removes comments from minified files }, sourceMap: false //Source maps are slow and unwanted })); } return plugins; }(), resolve: { alias: { components: path.join(__dirname, 'components'), 'mx-react-components': path.join(__dirname, '../src') } } };
Remove min 1 from reporttype
<?php /** * Created by PhpStorm. * User: ylly * Date: 16/10/15 * Time: 19:01 */ namespace ESN\PermanenceBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; class ReportType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('amountBefore', 'integer', array( 'attr' => array( 'readonly' => true, 'class' => 'span3' ) )) ->add('amountAfter', 'integer', array( 'attr' => array( 'readonly' => true, 'class' => 'span3' ) )) ->add('sellCard', 'integer', array( 'attr' => array( 'class' => 'span3', 'min' => 0 ) )) ->add('availableCard', 'integer', array( 'attr' => array( 'readonly' => true, 'class' => 'span3', 'min' => 1 ) )) ->add('comments', 'textarea') ; } public function getName() { return 'form_report'; } }
<?php /** * Created by PhpStorm. * User: ylly * Date: 16/10/15 * Time: 19:01 */ namespace ESN\PermanenceBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; class ReportType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('amountBefore', 'integer', array( 'attr' => array( 'readonly' => true, 'class' => 'span3' ) )) ->add('amountAfter', 'integer', array( 'attr' => array( 'readonly' => true, 'class' => 'span3' ) )) ->add('sellCard', 'integer', array( 'attr' => array( 'class' => 'span3', 'min' => 1 ) )) ->add('availableCard', 'integer', array( 'attr' => array( 'readonly' => true, 'class' => 'span3', 'min' => 1 ) )) ->add('comments', 'textarea') ; } public function getName() { return 'form_report'; } }
Allow "writable" if *any* field is writable Fixes Internal Issue 598
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from django import template from treemap.json_field import get_attr_from_json_field register = template.Library() def _get_color_from_config(config, name): color = config.get(name) if color: return '#' + color else: return '' @register.filter def primary_color(config): return _get_color_from_config(config, "scss_variables.primary-color") @register.filter def secondary_color(config): return _get_color_from_config(config, "scss_variables.secondary-color") @register.filter def feature_enabled(instance, feature): return instance.feature_enabled(feature) @register.filter def plot_field_is_writable(instanceuser, field): return plot_is_writable(instanceuser, field) @register.filter def plot_is_writable(instanceuser, field=None): if instanceuser is None or instanceuser == '': return False else: perms = instanceuser.role.plot_permissions.all() if field: perms = perms.filter(field_name=field) return any(perm.allows_writes for perm in perms) @register.filter def instance_config(instance, field): if instance: return get_attr_from_json_field(instance, "config." + field) else: return None
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from django import template from treemap.json_field import get_attr_from_json_field register = template.Library() def _get_color_from_config(config, name): color = config.get(name) if color: return '#' + color else: return '' @register.filter def primary_color(config): return _get_color_from_config(config, "scss_variables.primary-color") @register.filter def secondary_color(config): return _get_color_from_config(config, "scss_variables.secondary-color") @register.filter def feature_enabled(instance, feature): return instance.feature_enabled(feature) @register.filter def plot_field_is_writable(instanceuser, field): return plot_is_writable(instanceuser, field) @register.filter def plot_is_writable(instanceuser, field=None): if instanceuser is None or instanceuser == '': return False else: perms = instanceuser.role.plot_permissions.all() if field: perms = perms.filter(field_name=field) if len(perms) == 0: return False else: return perms[0].allows_writes @register.filter def instance_config(instance, field): if instance: return get_attr_from_json_field(instance, "config." + field) else: return None
Remove unused option, fix CS
<?php namespace Gloubster; use PhpAmqpLib\Connection\AMQPConnection; use PhpAmqpLib\Connection\AMQPSSLConnection; class RabbitMQFactory { public static function createConnection(Configuration $conf) { if (isset($conf['server']['ssl']) && $conf['server']['ssl']['enable']) { $connection = new AMQPSSLConnection( $conf['server']['host'], $conf['server']['port'], $conf['server']['user'], $conf['server']['password'], $conf['server']['vhost'], isset($conf['server']['ssl']['options']) ? $conf['server']['ssl']['options'] : array() ); } else { $connection = new AMQPConnection( $conf['server']['host'], $conf['server']['port'], $conf['server']['user'], $conf['server']['password'], $conf['server']['vhost'] ); } register_shutdown_function(function(AMQPConnection $connection) { try { $connection->close(); } catch (\Exception $e) { } }, $connection); return $connection; } }
<?php namespace Gloubster; use PhpAmqpLib\Connection\AMQPConnection; use PhpAmqpLib\Connection\AMQPSSLConnection; class RabbitMQFactory { public static function createConnection(Configuration $conf, $connected = true) { if (isset($conf['server']['ssl']) && $conf['server']['ssl']['enable']) { $connection = new AMQPSSLConnection( $conf['server']['host'], $conf['server']['port'], $conf['server']['user'], $conf['server']['password'], $conf['server']['vhost'], isset($conf['server']['ssl']['options']) ? $conf['server']['ssl']['options'] : array() ); } else { $connection = new AMQPConnection( $conf['server']['host'], $conf['server']['port'], $conf['server']['user'], $conf['server']['password'], $conf['server']['vhost'] ); } register_shutdown_function(function(AMQPConnection $connection) { try { $connection->close(); } catch (\Exception $e) { } }, $connection); return $connection; } }
Fix a few CS issues
'use strict'; var NavbarDirective = function ($window, eehNavigation) { return { restrict: 'AE', templateUrl: 'template/eeh-navigation/decoupled/eeh-navigation-navbar.html', link: function (scope) { scope._navbarBrand = eehNavigation._navbarBrand; scope.isNavbarCollapsed = false; scope._navbarMenuItems = eehNavigation._navbarMenuItems; scope.$watch('_navbarMenuItems', function () { var navbarMenuItems = eehNavigation.navbarMenuItems(); scope.leftNavbarMenuItems = navbarMenuItems.filter(function (item) { return !item.isHeavy(); }); scope.rightNavbarMenuItems = navbarMenuItems.filter(function (item) { return item.isHeavy(); }); }); var windowElement = angular.element($window); windowElement.bind('resize', function () { scope.$apply(); }); var getWindowDimensions = function () { return { height: windowElement.height(), width: windowElement.width(), innerHeight: windowElement.innerHeight(), innerWidth: windowElement.innerWidth() }; }; scope.$watch(getWindowDimensions, function (newValue) { if (angular.isUndefined(newValue)) { return; } var width = (newValue.innerWidth > 0) ? newValue.innerWidth : $window.screen.width; if (width >= 768) { scope.isNavbarCollapsed = false; } }, true); } }; }; angular.module('eehNavigation').directive('eehNavigationNavbar', ['$window', 'eehNavigation', NavbarDirective]);
'use strict'; var NavbarDirective = function ($window, eehNavigation) { return { restrict: 'AE', templateUrl: 'template/eeh-navigation/decoupled/eeh-navigation-navbar.html', link: function (scope, element) { scope._navbarBrand = eehNavigation._navbarBrand; scope.isNavbarCollapsed = false; scope._navbarMenuItems = eehNavigation._navbarMenuItems; scope.$watch('_navbarMenuItems', function () { var navbarMenuItems = eehNavigation.navbarMenuItems(); scope.leftNavbarMenuItems = navbarMenuItems.filter(function (item) { return !item.isHeavy(); }); scope.rightNavbarMenuItems = navbarMenuItems.filter(function (item) { return item.isHeavy(); }); }); var windowElement = angular.element($window); windowElement.bind('resize', function () { scope.$apply(); }); var getWindowDimensions = function () { return { height: windowElement.height(), width: windowElement.width(), innerHeight: windowElement.innerHeight(), innerWidth: windowElement.innerWidth() }; }; var topOffset = 50; scope.$watch(getWindowDimensions, function (newValue) { if (angular.isUndefined(newValue)) { return; } var width = (newValue.innerWidth > 0) ? newValue.innerWidth : $window.screen.width; if (width >= 768) { scope.isNavbarCollapsed = false; } }, true); } }; }; angular.module('eehNavigation').directive('eehNavigationNavbar', ['$window', 'eehNavigation', NavbarDirective]);
Use `devtool: 'source-map'` because 'eval' isn't suited for production (https://webpack.js.org/configuration/devtool/#devtool)
/* eslint-env node */ const webpack = require('webpack'); const packageJson = require('./package.json'); const isProduction = process.env.NODE_ENV === 'production'; function getLicenseComment(version) { return [ 'Likely $version by Ilya Birman (ilyabirman.net)', 'Rewritten sans jQuery by Evgeny Steblinsky (volter9.github.io)', 'Supported by Ivan Akulov (iamakulov.com), Viktor Karpov (vitkarpov.com), and contributors', 'Inspired by Social Likes by Artem Sapegin (sapegin.me)', ].join('\n').replace(/\$version/g, version); } module.exports = { entry: { likely: './source/likely.js', // [] is a workaround, see https://github.com/webpack/webpack/issues/300 'likely-commonjs': ['./source/index.js'], }, output: { filename: '[name].js', library: 'likely', libraryTarget: 'umd', }, module: { rules: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', }], }, devtool: 'source-map', watch: !isProduction, plugins: isProduction ? [ new webpack.BannerPlugin(getLicenseComment(packageJson.version)), ] : [], };
/* eslint-env node */ const webpack = require('webpack'); const packageJson = require('./package.json'); const isProduction = process.env.NODE_ENV === 'production'; function getLicenseComment(version) { return [ 'Likely $version by Ilya Birman (ilyabirman.net)', 'Rewritten sans jQuery by Evgeny Steblinsky (volter9.github.io)', 'Supported by Ivan Akulov (iamakulov.com), Viktor Karpov (vitkarpov.com), and contributors', 'Inspired by Social Likes by Artem Sapegin (sapegin.me)', ].join('\n').replace(/\$version/g, version); } module.exports = { entry: { likely: './source/likely.js', // [] is a workaround, see https://github.com/webpack/webpack/issues/300 'likely-commonjs': ['./source/index.js'], }, output: { filename: '[name].js', library: 'likely', libraryTarget: 'umd', }, module: { rules: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', }], }, devtool: isProduction ? 'eval' : 'source-map', watch: !isProduction, plugins: isProduction ? [ new webpack.BannerPlugin(getLicenseComment(packageJson.version)), ] : [], };
Hide StreamAnalyzer and OsGuesser from the API docs.
#!/usr/bin/env python # Generates the *public* API documentation. # Remember to hide your private parts, people! import os, re, sys project = 'Exscript' base_dir = os.path.join('..', 'src', project) doc_dir = 'api' # Create the documentation directory. if not os.path.exists(doc_dir): os.makedirs(doc_dir) # Generate the API documentation. os.system('epydoc ' + ' '.join(['--name', project, '--exclude Exscript.AbstractMethod', '--exclude Exscript.AccountManager', '--exclude Exscript.HostAction', '--exclude Exscript.Log', '--exclude Exscript.Logfile', '--exclude Exscript.QueueLogger', '--exclude Exscript.QueueListener', '--exclude Exscript.util.otp', '--exclude Exscript.interpreter', '--exclude Exscript.protocols.AbstractMethod', '--exclude Exscript.protocols.StreamAnalyzer', '--exclude Exscript.protocols.OsGuesser', '--exclude Exscript.protocols.telnetlib', '--exclude Exscript.stdlib', '--exclude Exscript.workqueue', '--exclude Exscript.version', '--html', '--no-private', '--no-source', '--no-frames', '--inheritance=included', '-v', '-o %s' % doc_dir, base_dir]))
#!/usr/bin/env python # Generates the *public* API documentation. # Remember to hide your private parts, people! import os, re, sys project = 'Exscript' base_dir = os.path.join('..', 'src', project) doc_dir = 'api' # Create the documentation directory. if not os.path.exists(doc_dir): os.makedirs(doc_dir) # Generate the API documentation. os.system('epydoc ' + ' '.join(['--name', project, '--exclude Exscript.AbstractMethod', '--exclude Exscript.AccountManager', '--exclude Exscript.HostAction', '--exclude Exscript.Log', '--exclude Exscript.Logfile', '--exclude Exscript.QueueLogger', '--exclude Exscript.QueueListener', '--exclude Exscript.util.otp', '--exclude Exscript.interpreter', '--exclude Exscript.protocols.AbstractMethod', '--exclude Exscript.protocols.telnetlib', '--exclude Exscript.stdlib', '--exclude Exscript.workqueue', '--exclude Exscript.version', '--html', '--no-private', '--no-source', '--no-frames', '--inheritance=included', '-v', '-o %s' % doc_dir, base_dir]))
Make core thread pool size unbounded
package forklift.concurrent; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * Forklift core thread pool. * @author zdavep */ public final class Executors { // Base value for determining thread pool size. private static final int cpus = Runtime.getRuntime().availableProcessors(); /** * Disable instance creation. */ private Executors() {} /** * Allows us to create daemon threads with meaningful names. */ private static ThreadFactory daemonThreadFactory(final String name) { return new ThreadFactory() { private final AtomicInteger counter = new AtomicInteger(); @Override public Thread newThread(Runnable r) { final Thread thread = new Thread(r); thread.setName(name + "-" + counter.incrementAndGet()); thread.setDaemon(true); return thread; } }; } /** * A core thread pool factory method that returns a cached thread pool. */ public static ExecutorService newCoreThreadPool(final String name) { final ThreadPoolExecutor pool = new ThreadPoolExecutor( (2 * cpus), Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), daemonThreadFactory(name) ); pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); return pool; } }
package forklift.concurrent; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * Forklift core thread pool. * @author zdavep */ public final class Executors { // Base value for determining thread pool size. private static final int cpus = Runtime.getRuntime().availableProcessors(); /** * Disable instance creation. */ private Executors() {} /** * Allows us to create daemon threads with meaningful names. */ private static ThreadFactory daemonThreadFactory(final String name) { return new ThreadFactory() { private final AtomicInteger counter = new AtomicInteger(); @Override public Thread newThread(Runnable r) { final Thread thread = new Thread(r); thread.setName(name + "-" + counter.incrementAndGet()); thread.setDaemon(true); return thread; } }; } /** * A core thread pool factory method that returns a "better" alternative to a cached thread pool. */ public static ExecutorService newCoreThreadPool(final String name) { final ThreadPoolExecutor pool = new ThreadPoolExecutor( (2 * cpus), (6 * cpus), 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), daemonThreadFactory(name) ); pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); return pool; } }
Add a dev mode so that watching rebuilds is quick without minification
const path = require('path') const babelConfig = require('./babel.config') const bubleConfig = require('./buble.config') const BabelMinify = require("babel-minify-webpack-plugin"); let DEV = false // --watch option means dev mode if (process.argv.includes('--watch')) { DEV = true } module.exports = { entry: './src/index.js', output: { path: __dirname, filename: 'global.js', library: 'infamous', libraryTarget: 'var', // alternative: "window" }, module: { rules: [ { test: /\.js$/, include: [ path.resolve(__dirname, 'src'), path.resolve(__dirname, 'node_modules', 'custom-attributes'), // ES6+ ], use: [ { loader: 'buble-loader', options: bubleConfig, }, { loader: 'babel-loader', options: babelConfig, }, ], }, ], }, plugins: DEV ? [] : [ new BabelMinify({}, { comments: false, }) ], }
const path = require('path') const babelConfig = require('./babel.config') const bubleConfig = require('./buble.config') const BabelMinify = require("babel-minify-webpack-plugin"); module.exports = { entry: './src/index.js', output: { path: __dirname, filename: 'global.js', library: 'infamous', libraryTarget: 'var', // alternative: "window" }, module: { rules: [ { test: /\.js$/, include: [ path.resolve(__dirname, 'src'), path.resolve(__dirname, 'node_modules', 'custom-attributes'), // ES6+ ], use: [ { loader: 'buble-loader', options: bubleConfig, }, { loader: 'babel-loader', options: babelConfig, }, ], }, ], }, plugins: [ new BabelMinify({}, { comments: false, }) ], }
Add timestamp to url to force ng-src reload
spacialistApp.service('analysisService', ['httpGetFactory', function(httpGetFactory) { var analysis = {}; analysis.entries = []; analysis.activeAnalysis = { isActive: false }; analysis.getStoredQueries = function() { httpGetFactory('api/analysis/queries/getAll', function(queries) { analysis.storedQueries = queries; }); }; analysis.setAnalysisEntry = function(index) { var entry = analysis.entries[index]; for(var k in entry) { if(entry.hasOwnProperty(k)) { analysis.activeAnalysis[k] = entry[k]; } } analysis.activeAnalysis.url = analysis.activeAnalysis.url + '&ts=' + Date.now(); analysis.activeAnalysis.isActive = true; }; analysis.unsetAnalysisEntry = function() { for(var k in analysis.activeAnalysis) { if(analysis.activeAnalysis.hasOwnProperty(k)) { delete analysis.activeAnalysis[k]; } } }; function setEntries() { analysis.entries.push({ name: 'main.menu.new-data-analysis', url: 'db/?mode=query&navbar=off&padding=none' }); analysis.entries.push({ name: 'main.menu.browse-data-analysis', url: 'db/?mode=list&table=stored_queries&navbar=off' }); } setEntries(); return analysis; }]);
spacialistApp.service('analysisService', ['httpGetFactory', function(httpGetFactory) { var analysis = {}; analysis.entries = []; analysis.activeAnalysis = { isActive: false }; analysis.getStoredQueries = function() { httpGetFactory('api/analysis/queries/getAll', function(queries) { analysis.storedQueries = queries; }); }; analysis.setAnalysisEntry = function(index) { var entry = analysis.entries[index]; for(var k in entry) { if(entry.hasOwnProperty(k)) { analysis.activeAnalysis[k] = entry[k]; } } analysis.activeAnalysis.isActive = true; }; analysis.unsetAnalysisEntry = function() { for(var k in analysis.activeAnalysis) { if(analysis.activeAnalysis.hasOwnProperty(k)) { delete analysis.activeAnalysis[k]; } } }; function setEntries() { analysis.entries.push({ name: 'main.menu.new-data-analysis', url: 'db/?mode=query&navbar=off&padding=none' }); analysis.entries.push({ name: 'main.menu.browse-data-analysis', url: 'db/?mode=list&table=stored_queries&navbar=off' }); } setEntries(); return analysis; }]);
Allow plotting two types against one another.
#!/usr/bin/env python #Go through an OpenXC trace file and plot a time series graph using #matplotlib import json import sys import argparse from pylab import * def main(): #Set up the command line argument parser parser = argparse.ArgumentParser() parser.add_argument("input_file", help = "name of the input file") parser.add_argument("-y", help = "the key to use for the function being plotted") parser.add_argument("-x", help = "the key to use for the function being plotted", default=None) args = parser.parse_args() input_file_name = args.input_file y_key = str(args.y) x_key = args.x #initialize the x axis and function to be plotted x = [] y = [] with open(input_file_name, 'r') as input_file: for line in input_file: if not line.rstrip() : continue try: obj = json.loads(line) except ValueError: print("Skipping invalid JSON: %s" % line) continue #if the parsed JSON object has the key we're looking for, #add the key's value to the y graph and the timestamp #to the x list if obj['name'] == y_key: y.append(obj['value']) if x_key is None: x.append(obj['timestamp']) if obj['name'] == x_key: x.append(obj['value']) autoscale(True, 'both') xlabel(x_key or 'timestamp') ylabel(y_key) plot(x, y, 'ro') show() if __name__ == "__main__": main()
#!/usr/bin/env python #Go through an OpenXC trace file and plot a time series graph using #matplotlib import json import sys import argparse from pylab import * def main(): #Set up the command line argument parser parser = argparse.ArgumentParser() parser.add_argument("input_file", help = "name of the input file") parser.add_argument("-y", help = "the key to use for the function being plotted") args = parser.parse_args() input_file_name = args.input_file y_key = str(args.y) #initialize the x axis and function to be plotted x = [] y = [] with open(input_file_name, 'r') as input_file: for line in input_file: if not line.rstrip() : continue try: obj = json.loads(line) except ValueError: print("Skipping invalid JSON: %s" % line) continue #if the parsed JSON object has the key we're looking for, #add the key's value to the y graph and the timestamp #to the x list if obj['name'] == y_key: y.append(obj['value']) x.append(obj['timestamp']) autoscale(True, 'both') plot(x, y, label = y_key) legend(loc='upper left') show() if __name__ == "__main__": main()
Fix bug due to refacto
#-*- coding: utf-8 -*- from src.shell.parser.i_log_parser import ILogParser class TypeLogParser(ILogParser): """ Parser for type log file """ def __init__(self, *args, **kwargs): self.__fn = None super(TypeLogParser, self).__init__(*args, **kwargs) def get(self): if self.__fn is None: self.__fn = dict() with open(self.log_path, "r") as log: # Skip first line log.readline() for line in log.readlines(): l = line[:-1].split(":") name = ":".join(l[:3]) proto = l[-1].replace(" ", "").split(",") self.__fn[name] = proto yield name, proto else: for name, proto in self.__fn.items(): yield name, proto def get_proto(self, fname): if self.__fn is None: # parse log for f, g in self.get(): pass if fname in self.__fn.keys(): # Remove confidence rate before returning proto return [arg[:arg.index("(")] if arg.count("(") > 0 else arg for arg in self.__fn[fname]] else: # TODO create specific exception print "ERROR: {0} not found -- aborting".format(fname) raise Exception
#-*- coding: utf-8 -*- from src.shell.parser.i_log_parser import ILogParser class TypeLogParser(ILogParser): """ Parser for type log file """ def __init__(self, *args, **kwargs): self.__fn = None super(TypeLogParser, self).__init__(*args, **kwargs) def get(self): if self.__fn is None: self.__fn = dict() with open(self.log_path, "r") as log: # Skip first line f.readline() for line in log.readlines(): l = line[:-1].split(":") name = ":".join(l[:3]) proto = l[-1].replace(" ", "").split(",") self.__fn[name] = proto yield name, proto else: for name, proto in self.__fn.items(): yield name, proto def get_proto(self, fname): if self.__fn is None: # parse log for f, g in self.get(): pass if fname in self.__fn.keys(): # Remove confidence rate before returning proto return [arg[:arg.index("(")] if arg.count("(") > 0 else arg for arg in self.__fn[fname]] else: # TODO create specific exception print "ERROR: {0} not found -- aborting".format(fname) raise Exception
Convert Flask path variables to OpenAPI path parameters
"""OpenAPI core wrappers module""" import re from openapi_core.wrappers.base import BaseOpenAPIRequest, BaseOpenAPIResponse # http://flask.pocoo.org/docs/1.0/quickstart/#variable-rules PATH_PARAMETER_PATTERN = r'<(?:(?:string|int|float|path|uuid):)?(\w+)>' class FlaskOpenAPIRequest(BaseOpenAPIRequest): path_regex = re.compile(PATH_PARAMETER_PATTERN) def __init__(self, request): self.request = request @property def host_url(self): return self.request.host_url @property def path(self): return self.request.path @property def method(self): return self.request.method.lower() @property def path_pattern(self): if self.request.url_rule is None: return self.path return self.path_regex.sub(r'{\1}', self.request.url_rule.rule) @property def parameters(self): return { 'path': self.request.view_args, 'query': self.request.args, 'header': self.request.headers, 'cookie': self.request.cookies, } @property def body(self): return self.request.data @property def mimetype(self): return self.request.mimetype class FlaskOpenAPIResponse(BaseOpenAPIResponse): def __init__(self, response): self.response = response @property def data(self): return self.response.data @property def status_code(self): return self.response._status_code @property def mimetype(self): return self.response.mimetype
"""OpenAPI core wrappers module""" from openapi_core.wrappers.base import BaseOpenAPIRequest, BaseOpenAPIResponse class FlaskOpenAPIRequest(BaseOpenAPIRequest): def __init__(self, request): self.request = request @property def host_url(self): return self.request.host_url @property def path(self): return self.request.path @property def method(self): return self.request.method.lower() @property def path_pattern(self): if self.request.url_rule is None: return self.path return self.request.url_rule.rule @property def parameters(self): return { 'path': self.request.view_args, 'query': self.request.args, 'header': self.request.headers, 'cookie': self.request.cookies, } @property def body(self): return self.request.data @property def mimetype(self): return self.request.mimetype class FlaskOpenAPIResponse(BaseOpenAPIResponse): def __init__(self, response): self.response = response @property def data(self): return self.response.data @property def status_code(self): return self.response._status_code @property def mimetype(self): return self.response.mimetype
Order Aphabetical: Add listeners for at-rules Viewport was completely missing, but the others were also not reporting at the end of the rule scope
/* * Rule: All properties should be in alphabetical order.. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "order-alphabetical", name: "Alphabetical order", desc: "Assure properties are in alphabetical order", browsers: "All", //initialization init: function(parser, reporter){ "use strict"; var rule = this, properties; var startRule = function () { properties = []; }; var endRule = function(event){ var currentProperties = properties.join(","), expectedProperties = properties.sort().join(","); if (currentProperties !== expectedProperties){ reporter.report("Rule doesn't have all its properties in alphabetical ordered.", event.line, event.col, rule); } }; parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); parser.addListener("startpage", startRule); parser.addListener("startpagemargin", startRule); parser.addListener("startkeyframerule", startRule); parser.addListener("startviewport", startRule); parser.addListener("property", function(event){ var name = event.property.text, lowerCasePrefixLessName = name.toLowerCase().replace(/^-.*?-/, ""); properties.push(lowerCasePrefixLessName); }); parser.addListener("endrule", endRule); parser.addListener("endfontface", endRule); parser.addListener("endpage", endRule); parser.addListener("endpagemargin", endRule); parser.addListener("endkeyframerule", endRule); parser.addListener("endviewport", endRule); } });
/* * Rule: All properties should be in alphabetical order.. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "order-alphabetical", name: "Alphabetical order", desc: "Assure properties are in alphabetical order", browsers: "All", //initialization init: function(parser, reporter){ "use strict"; var rule = this, properties; var startRule = function () { properties = []; }; parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); parser.addListener("startpage", startRule); parser.addListener("startpagemargin", startRule); parser.addListener("startkeyframerule", startRule); parser.addListener("property", function(event){ var name = event.property.text, lowerCasePrefixLessName = name.toLowerCase().replace(/^-.*?-/, ""); properties.push(lowerCasePrefixLessName); }); parser.addListener("endrule", function(event){ var currentProperties = properties.join(","), expectedProperties = properties.sort().join(","); if (currentProperties !== expectedProperties){ reporter.report("Rule doesn't have all its properties in alphabetical ordered.", event.line, event.col, rule); } }); } });
Load database config depend on application name.
<?php defined('SYSPATH') or die('No direct script access.'); /** * Arag * * @package Arag * @author Armen Baghumian * @since Version 0.3 * @filesource */ // ------------------------------------------------------------------------ /** * Model Class * * @package Arag * @subpackage Libraries * @author Armen Baghumian * @category Model */ class Model extends Model_Core { // {{{ Constructor public function __construct($config = Null) { $session = new Session(); $appname = $session->get('appname', APPNAME); $config = ($appname === '_master_') ? 'default' : $config; $config = ($config == Null) ? Config::item('sites/'.$appname.'.database') : $config; // Load the database into the model if (Event::has_run('system.pre_controller')) { $this->db = isset(Kohana::instance()->db) ? Kohana::instance()->db : new Database($config); } else { $this->db = new Database($config); } } // }}} // {{{ load public static function load($model = False, $module = False) { if ($module == False) { $module = Router::$module; } // Change include_once to module path Config::set('core.include_paths', Array(APPPATH.'modules/'.$module)); $model = ucfirst(strtolower($model)).'_Model'; $model = new $model(); // Reset the include_paths Config::set('core.include_paths', Array(APPPATH.'modules/'.Router::$module)); return $model; } // }}} } ?>
<?php defined('SYSPATH') or die('No direct script access.'); /** * Arag * * @package Arag * @author Armen Baghumian * @since Version 0.3 * @filesource */ // ------------------------------------------------------------------------ /** * Model Class * * @package Arag * @subpackage Libraries * @author Armen Baghumian * @category Model */ class Model extends Model_Core { // {{{ Constructor public function __construct() { if (Event::has_run('system.pre_controller')) { // Load the database into the model $this->db = isset(Kohana::instance()->db) ? Kohana::instance()->db : new Database('default'); } else { $this->db = new Database('default'); } } // }}} // {{{ load public static function load($model = False, $module = False) { if ($module == False) { $module = Router::$module; } // Load the model Config::set('core.include_paths', Array(APPPATH.'modules/'.$module)); $model = ucfirst(strtolower($model)).'_Model'; $model = new $model(); // Reset the include_paths Config::set('core.include_paths', Array(APPPATH.'modules/'.Router::$module)); return $model; } // }}} } ?>
Fix limit bug in create Initiative method
Meteor.startup(function() { Meteor.methods({ addComment: function(initiativeId, input) { var userId = Meteor.userId(); Meteor.users.update(userId, { $addToSet: { commentedOn: initiativeId } }); Initiatives.update(initiativeId, {$addToSet: {comments: { createdBy: userId, message: input, createdAt: new Date() }}}); }, createInitiative: function(title, description, category) { var initiativeLimit = Meteor.settings.initiativeLimit; var existingInitiatives = Initiatives.find({createdBy: Meteor.userId()}); if(existingInitiatives && existingInitiatives.count() < initiativeLimit) { var slug = s.slugify(title); var categorySlug = s.slugify(category); var initiative = { title: title, description: description, votes: 0, createdBy: Meteor.userId(), createdAt: new Date(), category: category, imageUrl: "https://placeimg.com/300/250/arch", comments: [], slug: slug, categorySlug: categorySlug } Initiatives.insert(initiative); return slug; } else { throw new Meteor.Error(403, "You have reached the limit of " + initiativeLimit + " initiatives."); } } }); });
Meteor.startup(function() { Meteor.methods({ addComment: function(initiativeId, input) { var userId = Meteor.userId(); Meteor.users.update(userId, { $addToSet: { commentedOn: initiativeId } }); Initiatives.update(initiativeId, {$addToSet: {comments: { createdBy: userId, message: input, createdAt: new Date() }}}); }, createInitiative: function(title, description, category) { var initiativeLimit = Meteor.settings.initiativeLimit; var existingInitiatives = Initiatives.find({createdBy: Meteor.userId}); if(existingInitiatives && existingInitiatives.count() < initiativeLimit) { var slug = s.slugify(title); var categorySlug = s.slugify(category); var initiative = { title: title, description: description, votes: 0, createdBy: Meteor.userId(), createdAt: new Date(), category: category, imageUrl: "https://placeimg.com/300/250/arch", comments: [], slug: slug, categorySlug: categorySlug } Initiatives.insert(initiative); return slug; } else { throw new Meteor.Error(403, "You have reached the limit of " + initiativeLimit + " initiatives."); } } }); });
Return null if not found
"use strict"; var db = require("./db.json"), strictFormats = [ /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/, /^([0-9A-F]{2}[:-]){2}([0-9A-F]{2})$/, /^([0-9A-F]{4}[.]){2}([0-9A-F]{4})$/, /^[0-9A-F]{6}$/, /^[0-9A-F]{12}$/ ]; var oui = function oui(input, opts) { if (typeof input !== "string") throw new Error("Input not a string"); input = input.toUpperCase(); if (opts && opts.strict === true) { var isStrict = strictFormats.some(function (regex) { if (regex.test(input)) return true; }); if (!isStrict) throw new Error("Input not in strict format"); input = input.replace(/[.:-]/g, "").substring(0, 6); } else { input = input.replace(/[^0-9a-fA-F]/g, "").substring(0, 6); } if (input.length < 6) return null; return db[input] || null; }; oui.update = function (cb) { require("./update.js")(false, function (err, newdb) { if (err) return cb(err); db = newdb; if (cb) cb(null); }, true); }; module.exports = oui;
"use strict"; var db = require("./db.json"), strictFormats = [ /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/, /^([0-9A-F]{2}[:-]){2}([0-9A-F]{2})$/, /^([0-9A-F]{4}[.]){2}([0-9A-F]{4})$/, /^[0-9A-F]{6}$/, /^[0-9A-F]{12}$/ ]; var oui = function oui(input, opts) { if (typeof input !== "string") throw new Error("Input not a string"); input = input.toUpperCase(); if (opts && opts.strict === true) { var isStrict = strictFormats.some(function (regex) { if (regex.test(input)) return true; }); if (!isStrict) throw new Error("Input not in strict format"); input = input.replace(/[.:-]/g, "").substring(0, 6); } else { input = input.replace(/[^0-9a-fA-F]/g, "").substring(0, 6); } if (input.length < 6) return null; return db[input]; }; oui.update = function (cb) { require("./update.js")(false, function (err, newdb) { if (err) return cb(err); db = newdb; if (cb) cb(null); }, true); }; module.exports = oui;
engine: Delete vnic profiles when removing a network The patch removes vnic profiles when the network is being deleted from the system. Change-Id: I6472fb81262d7eb2cf6886a42ba17a637c804b22 Signed-off-by: Moti Asayag <[email protected]>
package org.ovirt.engine.core.bll.network.dc; import org.ovirt.engine.core.bll.validator.NetworkValidator; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.action.AddNetworkStoragePoolParameters; import org.ovirt.engine.core.common.errors.VdcBllMessages; public class RemoveNetworkCommand<T extends AddNetworkStoragePoolParameters> extends NetworkCommon<T> { public RemoveNetworkCommand(T parameters) { super(parameters); } @Override protected void executeCommand() { removeVnicProfiles(); getNetworkDAO().remove(getNetwork().getId()); setSucceeded(true); } @Override protected void setActionMessageParameters() { super.setActionMessageParameters(); addCanDoActionMessage(VdcBllMessages.VAR__ACTION__REMOVE); } @Override protected boolean canDoAction() { NetworkValidator validator = new NetworkValidator(getNetworkDAO().get(getNetwork().getId())); return validate(validator.networkIsSet()) && validate(validator.notManagementNetwork()) && validate(validator.networkNotUsedByVms()) && validate(validator.networkNotUsedByTemplates()); } @Override public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? AuditLogType.NETWORK_REMOVE_NETWORK : AuditLogType.NETWORK_REMOVE_NETWORK_FAILED; } }
package org.ovirt.engine.core.bll.network.dc; import org.ovirt.engine.core.bll.validator.NetworkValidator; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.action.AddNetworkStoragePoolParameters; import org.ovirt.engine.core.common.errors.VdcBllMessages; public class RemoveNetworkCommand<T extends AddNetworkStoragePoolParameters> extends NetworkCommon<T> { public RemoveNetworkCommand(T parameters) { super(parameters); } @Override protected void executeCommand() { getNetworkDAO().remove(getNetwork().getId()); setSucceeded(true); } @Override protected void setActionMessageParameters() { super.setActionMessageParameters(); addCanDoActionMessage(VdcBllMessages.VAR__ACTION__REMOVE); } @Override protected boolean canDoAction() { NetworkValidator validator = new NetworkValidator(getNetworkDAO().get(getNetwork().getId())); return validate(validator.networkIsSet()) && validate(validator.notManagementNetwork()) && validate(validator.networkNotUsedByVms()) && validate(validator.networkNotUsedByTemplates()); } @Override public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? AuditLogType.NETWORK_REMOVE_NETWORK : AuditLogType.NETWORK_REMOVE_NETWORK_FAILED; } }
Fix fail on javadoc task.
package com.github.kubode.rxproperty; import rx.Observable; import rx.Observer; import rx.Subscriber; /** * Read-only Observable property. * * @param <T> the type of this property. */ public class ReadOnlyObservableProperty<T> extends Observable<T> { /** * The state of {@link ReadOnlyObservableProperty}. * Generally, {@link #getObservable()} should emit the most recent value when subscribed. * * @param <T> the type of value property and item expected to be observed by the {@link #getObservable()}. */ public interface State<T> { /** * Returns {@link Observable} of this state. * * @return an {@link Observable} that emits the most recent value it has observed * and all subsequent observed items to each subscribed {@link Observer}. */ Observable<T> getObservable(); /** * Returns value of this state. * * @return a value of this state. */ T getValue(); } private final State<T> state; /** * Creates a ReadOnlyObservableProperty. * * @param state a state of this property. */ public ReadOnlyObservableProperty(final State<T> state) { super(new OnSubscribe<T>() { @Override public void call(Subscriber<? super T> subscriber) { subscriber.add(state.getObservable().subscribe(subscriber)); } }); this.state = state; } /** * Get value of this property. * * @return value of this property. */ public T getValue() { return state.getValue(); } }
package com.github.kubode.rxproperty; import rx.Observable; import rx.Observer; import rx.Subscriber; /** * Read-only Observable property. * * @param <T> the type of this property. */ public class ReadOnlyObservableProperty<T> extends Observable<T> { /** * The state of {@link ReadOnlyObservableProperty}. * Generally, {@link #getObservable()} should emit the most recent value when subscribed. * * @param <T> the type of value property and item expected to be observed by the {@link #getObservable()}. */ public interface State<T> { /** * Returns {@link Observable} of this state. * * @return an {@link Observable} that emits the most recent value it has observed * and all subsequent observed items to each subscribed {@link Observer}. */ Observable<T> getObservable(); /** * Returns value of this state. * * @return a value of this state. */ T getValue(); } private final State<T> state; /** * Creates a ReadOnlyObservableProperty. * * @param state a state of this property. */ public ReadOnlyObservableProperty(final State<T> state) { super(new OnSubscribe<T>() { @Override public void call(Subscriber<? super T> subscriber) { subscriber.add(state.getObservable().subscribe(subscriber)); } }); this.state = state; } /** * Get value of this property. * * @return value of {@link #state#getValue()}. */ public T getValue() { return state.getValue(); } }
Fix a Paste activate/archive status constant in rendering Summary: Fixes T11280. I extracted this at the last minute and got the constant flipped. Test Plan: Archived, then activated a paste. Observed correct timeline stories/icons/etc. Reviewers: chad Reviewed By: chad Maniphest Tasks: T11280 Differential Revision: https://secure.phabricator.com/D16240
<?php final class PhabricatorPasteStatusTransaction extends PhabricatorPasteTransactionType { const TRANSACTIONTYPE = 'paste.status'; public function generateOldValue($object) { return $object->getStatus(); } public function applyInternalEffects($object, $value) { $object->setStatus($value); } private function isActivate() { return ($this->getNewValue() == PhabricatorPaste::STATUS_ACTIVE); } public function getIcon() { if ($this->isActivate()) { return 'fa-check'; } else { return 'fa-ban'; } } public function getColor() { if ($this->isActivate()) { return 'green'; } else { return 'indigo'; } } public function getTitle() { if ($this->isActivate()) { return pht( '%s activated this paste.', $this->renderAuthor()); } else { return pht( '%s archived this paste.', $this->renderAuthor()); } } public function getTitleForFeed() { if ($this->isActivate()) { return pht( '%s activated %s.', $this->renderAuthor(), $this->renderObject()); } else { return pht( '%s archived %s.', $this->renderAuthor(), $this->renderObject()); } } }
<?php final class PhabricatorPasteStatusTransaction extends PhabricatorPasteTransactionType { const TRANSACTIONTYPE = 'paste.status'; public function generateOldValue($object) { return $object->getStatus(); } public function applyInternalEffects($object, $value) { $object->setStatus($value); } private function isActivate() { return ($this->getNewValue() == PhabricatorPaste::STATUS_ARCHIVED); } public function getIcon() { if ($this->isActivate()) { return 'fa-check'; } else { return 'fa-ban'; } } public function getColor() { if ($this->isActivate()) { return 'green'; } else { return 'indigo'; } } public function getTitle() { if ($this->isActivate()) { return pht( '%s activated this paste.', $this->renderAuthor()); } else { return pht( '%s archived this paste.', $this->renderAuthor()); } } public function getTitleForFeed() { if ($this->isActivate()) { return pht( '%s activated %s.', $this->renderAuthor(), $this->renderObject()); } else { return pht( '%s archived %s.', $this->renderAuthor(), $this->renderObject()); } } }
Add date_registered to node serializer [#OSF-7230]
import json from website.util.permissions import reduce_permissions from admin.users.serializers import serialize_simple_node def serialize_node(node): embargo = node.embargo if embargo is not None: embargo = node.embargo.end_date return { 'id': node._id, 'title': node.title, 'public': node.is_public, 'parent': node.parent_id, 'root': node.root._id, 'is_registration': node.is_registration, 'date_created': node.date_created, 'withdrawn': node.is_retracted, 'embargo': embargo, 'contributors': [serialize_simple_user_and_node_permissions(node, user) for user in node.contributors], 'children': map(serialize_simple_node, node.nodes), 'deleted': node.is_deleted, 'pending_registration': node.is_pending_registration, 'registered_date': node.registered_date, 'creator': node.creator._id, 'spam_status': node.spam_status, 'spam_pro_tip': node.spam_pro_tip, 'spam_data': json.dumps(node.spam_data, indent=4), 'is_public': node.is_public, } def serialize_simple_user_and_node_permissions(node, user): return { 'id': user._id, 'name': user.fullname, 'permission': reduce_permissions(node.get_permissions(user)) }
import json from website.util.permissions import reduce_permissions from admin.users.serializers import serialize_simple_node def serialize_node(node): embargo = node.embargo if embargo is not None: embargo = node.embargo.end_date return { 'id': node._id, 'title': node.title, 'public': node.is_public, 'parent': node.parent_id, 'root': node.root._id, 'is_registration': node.is_registration, 'date_created': node.date_created, 'withdrawn': node.is_retracted, 'embargo': embargo, 'contributors': [serialize_simple_user_and_node_permissions(node, user) for user in node.contributors], 'children': map(serialize_simple_node, node.nodes), 'deleted': node.is_deleted, 'pending_registration': node.is_pending_registration, 'creator': node.creator._id, 'spam_status': node.spam_status, 'spam_pro_tip': node.spam_pro_tip, 'spam_data': json.dumps(node.spam_data, indent=4), 'is_public': node.is_public, } def serialize_simple_user_and_node_permissions(node, user): return { 'id': user._id, 'name': user.fullname, 'permission': reduce_permissions(node.get_permissions(user)) }
Fix order of rendering for unit test
import Ember from 'ember'; import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent( 'sl-calendar-year', 'Unit - component: sl-calendar-year' ); test( 'Default state is not active, new, or old', function( assert ) { let component = this.subject(), $component = this.render(); assert.strictEqual( component.get( 'active' ), false, 'Default component is not active' ); assert.strictEqual( component.get( 'new' ), false, 'Default component is not in new state' ); assert.strictEqual( component.get( 'old' ), false, 'Default component is not in old state' ); assert.strictEqual( $component.hasClass( 'active' ), false, 'Default rendered component does not have class "active"' ); assert.strictEqual( $component.hasClass( 'new' ), false, 'Default rendered component does not have class "new"' ); assert.strictEqual( $component.hasClass( 'old' ), false, 'Default rendered component does not have class "old"' ); }); test( 'Click event sends action with year value', function( assert ) { let exampleYear = 2000, $component; assert.expect( 1 ); this.subject({ action: 'test', targetObject: { test: year => { assert.strictEqual( year, exampleYear, 'Received year' ); } }, year: exampleYear }); $component = this.render(); $component.trigger( 'click' ); });
import Ember from 'ember'; import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent( 'sl-calendar-year', 'Unit - component: sl-calendar-year' ); test( 'Default state is not active, new, or old', function( assert ) { let component = this.subject(), $component = this.render(); assert.strictEqual( component.get( 'active' ), false, 'Default component is not active' ); assert.strictEqual( component.get( 'new' ), false, 'Default component is not in new state' ); assert.strictEqual( component.get( 'old' ), false, 'Default component is not in old state' ); assert.strictEqual( $component.hasClass( 'active' ), false, 'Default rendered component does not have class "active"' ); assert.strictEqual( $component.hasClass( 'new' ), false, 'Default rendered component does not have class "new"' ); assert.strictEqual( $component.hasClass( 'old' ), false, 'Default rendered component does not have class "old"' ); }); test( 'Click event sends action with year value', function( assert ) { let exampleYear = 2000, $component = this.render(); this.subject({ action: 'test', targetObject: { test: year => { assert.strictEqual( year, exampleYear, 'Received year' ); } }, year: exampleYear }); assert.expect( 1 ); $component.trigger( 'click' ); });
Add main menu chat entry
<?php namespace Rooty\DefaultBundle\Menu; use Knp\Menu\FactoryInterface; use Symfony\Component\DependencyInjection\ContainerAware; class Builder extends ContainerAware { public function mainMenuAnonymous(FactoryInterface $factory) { $menu = $factory->createItem('root'); $menu->setCurrentUri($this->container->get('request')->getRequestUri()); $menu->setChildrenAttribute('class', 'nav'); $menu->addChild('Главная', array('route' => '_index')); $menu->addChild('Войти', array('route' => 'fos_user_security_login')); $menu->addChild('Регистрация', array('route' => 'fos_user_registration_register')); return $menu; } public function mainMenuUser(FactoryInterface $factory) { $menu = $factory->createItem('root'); $menu->setCurrentUri($this->container->get('request')->getRequestUri()); $menu->setChildrenAttribute('class', 'nav'); $menu->addChild('Главная', array('route' => '_index')); $menu->addChild('Профиль', array('route' => 'fos_user_profile_show')); $menu->addChild('Сообщения', array('route' => 'im')); $menu->addChild('Чат', array('route' => 'chat')); $menu->addChild('Скачать', array('route' => 'torrents')); $menu->addChild('Загрузить', array('route' => 'torrent_new')); $menu->addChild('Выйти', array('route' => 'fos_user_security_logout')); return $menu; } } ?>
<?php namespace Rooty\DefaultBundle\Menu; use Knp\Menu\FactoryInterface; use Symfony\Component\DependencyInjection\ContainerAware; class Builder extends ContainerAware { public function mainMenuAnonymous(FactoryInterface $factory) { $menu = $factory->createItem('root'); $menu->setCurrentUri($this->container->get('request')->getRequestUri()); $menu->setChildrenAttribute('class', 'nav'); $menu->addChild('Главная', array('route' => '_index')); $menu->addChild('Войти', array('route' => 'fos_user_security_login')); $menu->addChild('Регистрация', array('route' => 'fos_user_registration_register')); return $menu; } public function mainMenuUser(FactoryInterface $factory) { $menu = $factory->createItem('root'); $menu->setCurrentUri($this->container->get('request')->getRequestUri()); $menu->setChildrenAttribute('class', 'nav'); $menu->addChild('Главная', array('route' => '_index')); $menu->addChild('Профиль', array('route' => 'fos_user_profile_show')); $menu->addChild('Сообщения', array('route' => 'im')); $menu->addChild('Скачать', array('route' => 'torrents')); $menu->addChild('Загрузить', array('route' => 'torrent_new')); $menu->addChild('Выйти', array('route' => 'fos_user_security_logout')); return $menu; } } ?>
Use threading instead of multiprocessing.
from threading import Thread, Event try: from queue import Queue except ImportError: from Queue import Queue class Timer(Thread): def __init__(self, interval, function, args=[], kwargs={}): super(Timer, self).__init__() self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.finished = Event() def cancel(self): self.finished.set() def run(self): self.finished.wait(self.interval) if not self.finished.is_set(): self.function(*self.args, **self.kwargs) self.finished.set() class EventSpooler(object): def __init__(self, cooldown, callback): self.cooldown = cooldown self.callback = callback self.inbox = Queue() self.outbox = Queue() def enqueue(self, event): self.inbox.put(event) Timer(self.cooldown, self.process).start() def process(self): self.outbox.put(self.inbox.get()) if self.inbox.empty(): events = [] while not self.outbox.empty(): events.append(self.outbox.get()) self.callback(events)
# -*- coding: utf-8 from multiprocessing import Queue, Process, Event class Timer(Process): def __init__(self, interval, function, args=[], kwargs={}): super(Timer, self).__init__() self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.finished = Event() def cancel(self): self.finished.set() def run(self): self.finished.wait(self.interval) if not self.finished.is_set(): self.function(*self.args, **self.kwargs) self.finished.set() class EventSpooler(object): def __init__(self, cooldown, callback): self.cooldown = cooldown self.callback = callback self.inbox = Queue() self.outbox = Queue() def enqueue(self, event): self.inbox.put(event) Timer(self.cooldown, self.process).start() def process(self): self.outbox.put(self.inbox.get()) if self.inbox.empty(): events = [] while not self.outbox.empty(): events.append(self.outbox.get()) self.callback(events)
Simplify default equals function based on immutability
import { ReactiveVar } from 'meteor/reactive-var'; import { Promise } from 'meteor/promise'; function eqls(a, b) { // Because Apollo client data is immutable, we can simply check equality by using === return a === b; } export class ReactiveObserver { constructor(observer, { defaultValue = {}, equals = eqls, } = {}) { this.observer = observer; this._isReady = new ReactiveVar(false); this._errors = new ReactiveVar(); this._var = new ReactiveVar(defaultValue, equals); this.subscribe(); } isReady() { return this._isReady.get(); } get() { return this._var.get(); } getErrors() { return this._errors.get(); } unsubscribe() { return this._subscription && this._subscription.unsubscribe(); } subscribe() { if (this._subscription) { this.unsubscribe(); } this._subscription = this.observer.subscribe({ next: ({ errors, data } = {}) => { if (errors) { this._errors.set(errors); } else { this._errors.set(null); this._var.set(data); } this._isReady.set(true); }, error: (error) => { this._errors.set([].concat(error)); this._isReady.set(true); }, }); } then(func) { return this.observer .result() .then(({ data } = {}) => Promise.resolve(data).then(func)); } }
import { ReactiveVar } from 'meteor/reactive-var'; import { Promise } from 'meteor/promise'; function eqls(a, b) { return JSON.stringify(a) === JSON.stringify(b); } export class ReactiveObserver { constructor(observer, { defaultValue = {}, equals = eqls, } = {}) { this.observer = observer; this._isReady = new ReactiveVar(false); this._errors = new ReactiveVar(); this._var = new ReactiveVar(defaultValue, equals); this.subscribe(); } isReady() { return this._isReady.get(); } get() { return this._var.get(); } getErrors() { return this._errors.get(); } unsubscribe() { return this._subscription && this._subscription.unsubscribe(); } subscribe() { if (this._subscription) { this.unsubscribe(); } this._subscription = this.observer.subscribe({ next: ({ errors, data } = {}) => { if (errors) { this._errors.set(errors); } else { this._errors.set(null); this._var.set(data); } this._isReady.set(true); }, error: (error) => { this._errors.set([].concat(error)); this._isReady.set(true); }, }); } then(func) { return this.observer .result() .then(({ data } = {}) => Promise.resolve(data).then(func)); } }
Add marginTop on input fields when inside a label
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import Input from '../input'; import { TextBody, TextDisplay } from '../typography'; import theme from './theme.css'; import isComponentOfType from '../utils/is-component-of-type'; import cx from 'classnames'; export default class Label extends PureComponent { static propTypes = { className: PropTypes.string, children: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.array]), for: PropTypes.string, inverse: PropTypes.bool, size: PropTypes.oneOf(['small', 'medium', 'large']), }; static defaultProps = { inverse: false, size: 'medium', }; render() { const { children, className, inverse, size } = this.props; const childProps = { inverse, marginTop: 1, size, }; const classNames = cx( theme['label'], { [theme['is-inverse']]: inverse, }, className, ); const Element = size === 'large' ? TextDisplay : TextBody; return ( <Element color={inverse ? 'white' : 'teal'} element="label" htmlFor={this.props.for} marginBottom={3} className={classNames} > {React.Children.map(children, child => { if (isComponentOfType(Input, child)) { return React.cloneElement(child, childProps); } return child; })} </Element> ); } }
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import Input from '../input'; import { TextBody, TextDisplay } from '../typography'; import theme from './theme.css'; import isComponentOfType from '../utils/is-component-of-type'; import cx from 'classnames'; export default class Label extends PureComponent { static propTypes = { className: PropTypes.string, children: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.array]), for: PropTypes.string, inverse: PropTypes.bool, size: PropTypes.oneOf(['small', 'medium', 'large']), }; static defaultProps = { inverse: false, size: 'medium', }; render() { const { children, className, inverse, size } = this.props; const childProps = { inverse, size, }; const classNames = cx( theme['label'], { [theme['is-inverse']]: inverse, }, className, ); const Element = size === 'large' ? TextDisplay : TextBody; return ( <Element color={inverse ? 'white' : 'teal'} element="label" htmlFor={this.props.for} marginBottom={3} className={classNames} > {React.Children.map(children, child => { if (isComponentOfType(Input, child)) { return React.cloneElement(child, childProps); } return child; })} </Element> ); } }
Add support for `supported_transfer_countries` on CountrySpec
package stripe // Country is the list of supported countries type Country string // VerificationFieldsList lists the fields needed for an account verification. // For more details see https://stripe.com/docs/api#country_spec_object-verification_fields. type VerificationFieldsList struct { AdditionalFields []string `json:"additional"` Minimum []string `json:"minimum"` } // CountrySpec is the resource representing the rules required for a Stripe account. // For more details see https://stripe.com/docs/api/#country_specs. type CountrySpec struct { DefaultCurrency Currency `json:"default_currency"` ID string `json:"id"` SupportedBankAccountCurrencies map[Currency][]Country `json:"supported_bank_account_currencies"` SupportedPaymentCurrencies []Currency `json:"supported_payment_currencies"` SupportedPaymentMethods []string `json:"supported_payment_methods"` SupportedTransferCountries []string `json:"supported_transfer_countries"` VerificationFields map[LegalEntityType]*VerificationFieldsList `json:"verification_fields"` } // CountrySpecParams are the parameters allowed during CountrySpec retrieval. type CountrySpecParams struct { Params `form:"*"` } // CountrySpecList is a list of country specs as retrieved from a list endpoint. type CountrySpecList struct { ListMeta Data []*CountrySpec `json:"data"` } // CountrySpecListParams are the parameters allowed during CountrySpec listing. type CountrySpecListParams struct { ListParams `form:"*"` }
package stripe // Country is the list of supported countries type Country string // VerificationFieldsList lists the fields needed for an account verification. // For more details see https://stripe.com/docs/api#country_spec_object-verification_fields. type VerificationFieldsList struct { AdditionalFields []string `json:"additional"` Minimum []string `json:"minimum"` } // CountrySpec is the resource representing the rules required for a Stripe account. // For more details see https://stripe.com/docs/api/#country_specs. type CountrySpec struct { DefaultCurrency Currency `json:"default_currency"` ID string `json:"id"` SupportedBankAccountCurrencies map[Currency][]Country `json:"supported_bank_account_currencies"` SupportedPaymentCurrencies []Currency `json:"supported_payment_currencies"` SupportedPaymentMethods []string `json:"supported_payment_methods"` VerificationFields map[LegalEntityType]*VerificationFieldsList `json:"verification_fields"` } // CountrySpecParams are the parameters allowed during CountrySpec retrieval. type CountrySpecParams struct { Params `form:"*"` } // CountrySpecList is a list of country specs as retrieved from a list endpoint. type CountrySpecList struct { ListMeta Data []*CountrySpec `json:"data"` } // CountrySpecListParams are the parameters allowed during CountrySpec listing. type CountrySpecListParams struct { ListParams `form:"*"` }
Fix test runner for development Django
#!/usr/bin/env python import os import sys import django from django.conf import settings DEFAULT_SETTINGS = dict( INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sites", "badgekit_webhooks", "badgekit_webhooks.tests" ], DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } }, SITE_ID=1, ROOT_URLCONF="badgekit_webhooks.tests.urls", SECRET_KEY="notasecret", ) def runtests(*test_args): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, "setup"): django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) try: from django.test.simple import DjangoTestSuiteRunner as TestRunner if not test_args: test_args = ["tests"] except ImportError: from django.test.runner import DiscoverRunner as TestRunner if not test_args: test_args = ["badgekit_webhooks.tests"] failures = TestRunner( verbosity=1, interactive=True, failfast=False).run_tests(test_args) sys.exit(failures) if __name__ == "__main__": runtests(*sys.argv[1:])
#!/usr/bin/env python import os import sys import django from django.conf import settings DEFAULT_SETTINGS = dict( INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sites", "badgekit_webhooks", "badgekit_webhooks.tests" ], DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } }, SITE_ID=1, ROOT_URLCONF="badgekit_webhooks.tests.urls", SECRET_KEY="notasecret", ) def runtests(*test_args): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, "setup"): django.setup() if not test_args: test_args = ["tests"] parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) from django.test.simple import DjangoTestSuiteRunner failures = DjangoTestSuiteRunner( verbosity=1, interactive=True, failfast=False).run_tests(test_args) sys.exit(failures) if __name__ == "__main__": runtests(*sys.argv[1:])
Declare that cyrtranslit supports Python 3.7
from distutils.core import setup setup( name='cyrtranslit', packages=['cyrtranslit'], version='0.4', description='Bi-directional Cyrillic transliteration. Transliterate Cyrillic script text to Roman alphabet text and vice versa.', author='Open Data Kosovo', author_email='[email protected]', url='https://github.com/opendatakosovo/cyrillic-transliteration', download_url='https://github.com/opendatakosovo/cyrillic-transliteration/archive/v0.4.tar.gz', license='MIT', long_description='Transliteration is the conversion of a text from one script to another. Current version supports transliteration for Serbian, Macedonian, Montenegrin, and Russian.', keywords=['cyrillic', 'latin', 'transliteration', 'transliterate', 'cyrtranslit', 'serbian', 'macedonian', 'montenegrin', 'russian'], classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7'], )
from distutils.core import setup setup( name='cyrtranslit', packages=['cyrtranslit'], version='0.4', description='Bi-directional Cyrillic transliteration. Transliterate Cyrillic script text to Roman alphabet text and vice versa.', author='Open Data Kosovo', author_email='[email protected]', url='https://github.com/opendatakosovo/cyrillic-transliteration', download_url='https://github.com/opendatakosovo/cyrillic-transliteration/archive/v0.4.tar.gz', license='MIT', long_description='Transliteration is the conversion of a text from one script to another. Current version supports transliteration for Serbian, Macedonian, Montenegrin, and Russian.', keywords=['cyrillic', 'latin', 'transliteration', 'transliterate', 'cyrtranslit', 'serbian', 'macedonian', 'montenegrin', 'russian'], classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6'], )
Use any for concise code
import ctypes from ctypes import WinDLL, byref, WinError from ctypes.wintypes import MSG _user32 = WinDLL("user32") GetMessage = _user32.GetMessageA GetMessage.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_uint, ] TranslateMessage = _user32.TranslateMessage DispatchMessage = _user32.DispatchMessageA class _MessageLoop(object): def __init__(self): self._filters = [] def insert_filter(self, obj, index=-1): self._filters.insert(index, obj) def remove_filter(self, obj): self._filters.remove(obj) def run(self): msg = MSG() lpmsg = byref(msg) while 1: ret = GetMessage(lpmsg, 0, 0, 0) if ret == -1: raise WinError() elif ret == 0: return # got WM_QUIT if not self.filter_message(lpmsg): TranslateMessage(lpmsg) DispatchMessage(lpmsg) def filter_message(self, lpmsg): return any(filter(lpmsg) for filter in self._filters) _messageloop = _MessageLoop() run = _messageloop.run insert_filter = _messageloop.insert_filter remove_filter = _messageloop.remove_filter __all__ = ["run", "insert_filter", "remove_filter"]
import ctypes from ctypes import WinDLL, byref, WinError from ctypes.wintypes import MSG _user32 = WinDLL("user32") GetMessage = _user32.GetMessageA GetMessage.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_uint, ] TranslateMessage = _user32.TranslateMessage DispatchMessage = _user32.DispatchMessageA class _MessageLoop(object): def __init__(self): self._filters = [] def insert_filter(self, obj, index=-1): self._filters.insert(index, obj) def remove_filter(self, obj): self._filters.remove(obj) def run(self): msg = MSG() lpmsg = byref(msg) while 1: ret = GetMessage(lpmsg, 0, 0, 0) if ret == -1: raise WinError() elif ret == 0: return # got WM_QUIT if not self.filter_message(lpmsg): TranslateMessage(lpmsg) DispatchMessage(lpmsg) def filter_message(self, lpmsg): for filter in self._filters: if filter(lpmsg): return True return False _messageloop = _MessageLoop() run = _messageloop.run insert_filter = _messageloop.insert_filter remove_filter = _messageloop.remove_filter __all__ = ["run", "insert_filter", "remove_filter"]
Fix ordering on command line
#!/usr/bin/env node /*eslint-disable no-var */ var path = require('path'); var spawner = require('child_process'); exports.getFullPath = function(script){ return path.join(__dirname, script); }; // Respawn ensuring proper command switches exports.respawn = function respawn(script, requiredArgs, hostProcess) { if (!requiredArgs || requiredArgs.length === 0) { requiredArgs = ['--harmony']; } var args = hostProcess.execArgv.slice(); for (var i = 0; i < requiredArgs.length; i += 1) { if (args.indexOf(requiredArgs[i]) < 0) { args.push(requiredArgs[i]); } } var execScript = exports.getFullPath(script); spawner.spawn(hostProcess.execPath, args.concat(execScript, hostProcess.argv.slice(2)), { cwd: hostProcess.cwd(), stdio: 'inherit' }); }; /* istanbul ignore if */ if (require.main === module) { var argv = require('yargs') .usage('Usage: $0 <cfgFile> [options]') .demand(1, 1, 'A valid configuration file must be provided') .describe({ checkCfg: 'Check the validity of the configuration file without starting the bot' }) .argv; //respawn, ensuring required command switches exports.respawn('cli', ['--harmony', '--harmony_arrow_functions'], process); } /*eslint-enable no-var */
#!/usr/bin/env node /*eslint-disable no-var */ var path = require('path'); var spawner = require('child_process'); exports.getFullPath = function(script){ return path.join(__dirname, script); }; // Respawn ensuring proper command switches exports.respawn = function respawn(script, requiredArgs, hostProcess) { if (!requiredArgs || requiredArgs.length === 0) { requiredArgs = ['--harmony']; } var args = hostProcess.execArgv.slice(); for (var i = 0; i < requiredArgs.length; i += 1) { if (args.indexOf(requiredArgs[i]) < 0) { args.push(requiredArgs[i]); } } var execScript = exports.getFullPath(script); spawner.spawn(hostProcess.execPath, args.concat(execScript, hostProcess.argv.slice(2)), { cwd: hostProcess.cwd(), stdio: 'inherit' }); }; /* istanbul ignore if */ if (require.main === module) { var argv = require('yargs') .usage('Usage: $0 [options] <cfgFile>') .demand(1, 1, 'A valid configuration file must be provided') .describe({ checkCfg: 'Check the validity of the configuration file without starting the bot' }) .argv; //respawn, ensuring required command switches exports.respawn('cli', ['--harmony', '--harmony_arrow_functions'], process); } /*eslint-enable no-var */
Remove v3.0 requirement for now
try: from setuptools.core import setup except ImportError: from distutils.core import setup import sys svem_flag = '--single-version-externally-managed' if svem_flag in sys.argv: # Die, setuptools, die. sys.argv.remove(svem_flag) with open('jupyter_kernel/__init__.py', 'rb') as fid: for line in fid: line = line.decode('utf-8') if line.startswith('__version__'): version = line.strip().split()[-1][1:-1] break setup(name='jupyter_kernel', version=version, description='Jupyter Kernel Tools', long_description="Jupyter Kernel Tools using kernel wrappers", author='Steven Silvester', author_email='[email protected]', url="https://github.com/blink1073/jupyter_kernel", install_requires=['IPython'], packages=['jupyter_kernel', 'jupyter_kernel.magics', 'jupyter_kernel.tests'], classifiers=[ 'Framework :: IPython', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 2', 'Programming Language :: Scheme', 'Topic :: System :: Shells', ] )
try: from setuptools.core import setup except ImportError: from distutils.core import setup import sys svem_flag = '--single-version-externally-managed' if svem_flag in sys.argv: # Die, setuptools, die. sys.argv.remove(svem_flag) with open('jupyter_kernel/__init__.py', 'rb') as fid: for line in fid: line = line.decode('utf-8') if line.startswith('__version__'): version = line.strip().split()[-1][1:-1] break setup(name='jupyter_kernel', version=version, description='Jupyter Kernel Tools', long_description="Jupyter Kernel Tools using kernel wrappers", author='Steven Silvester', author_email='[email protected]', url="https://github.com/blink1073/jupyter_kernel", install_requires=['IPython >= 3.0'], packages=['jupyter_kernel', 'jupyter_kernel.magics', 'jupyter_kernel.tests'], classifiers=[ 'Framework :: IPython', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 2', 'Programming Language :: Scheme', 'Topic :: System :: Shells', ] )
Use transaction.atomic in batch uploader.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.db import transaction from django.utils.translation import ugettext_lazy as _ from pyaavso.formats.visual import VisualFormatReader from .models import Observation from stars.models import Star from observers.models import Observer class BatchUploadForm(forms.Form): aavso_file = forms.FileField(label=_("Observations file")) def process_file(self): fp = self.cleaned_data['aavso_file'] reader = VisualFormatReader(fp) observer = Observer.objects.get(aavso_code=reader.observer_code) with transaction.atomic(): for row in reader: try: star = Star.objects.get(name=row['name']) fainter_than = '<' in row['magnitude'] magnitude = float(row['magnitude'].replace('<', '')) jd = float(row['date']) try: observation = Observation.objects.get( observer=observer, star=star, jd=jd, ) except Observation.DoesNotExist: observation = Observation( observer=observer, star=star, jd=jd, ) observation.magnitude = magnitude observation.fainter_than = fainter_than observation.comp1 = row['comp1'] observation.comp2 = row['comp2'] observation.chart = row['chart'] observation.comment_code = row['comment_code'] observation.notes = row['notes'] observation.save() except Exception as e: print row print e continue
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from pyaavso.formats.visual import VisualFormatReader from .models import Observation from stars.models import Star from observers.models import Observer class BatchUploadForm(forms.Form): aavso_file = forms.FileField(label=_("Observations file")) def process_file(self): fp = self.cleaned_data['aavso_file'] reader = VisualFormatReader(fp) observer = Observer.objects.get(aavso_code=reader.observer_code) for row in reader: try: star = Star.objects.get(name=row['name']) fainter_than = '<' in row['magnitude'] magnitude = float(row['magnitude'].replace('<', '')) jd = float(row['date']) try: observation = Observation.objects.get( observer=observer, star=star, jd=jd, ) except Observation.DoesNotExist: observation = Observation( observer=observer, star=star, jd=jd, ) observation.magnitude = magnitude observation.fainter_than = fainter_than observation.comp1 = row['comp1'] observation.comp2 = row['comp2'] observation.chart = row['chart'] observation.comment_code = row['comment_code'] observation.notes = row['notes'] observation.save() except Exception as e: print row print e continue
Improve local import detection in `BaseParser.process_imports`
import abc import os import typing import urllib.parse if typing.TYPE_CHECKING: from ..ontology import Ontology class BaseParser(abc.ABC): def __init__(self, ont: 'Ontology'): self.ont = ont @classmethod @abc.abstractmethod def can_parse(cls, path: str, buffer: bytes): """Return `True` if this parser type can parse the given handle. """ return NotImplemented @abc.abstractmethod def parse_from(self, handle: typing.BinaryIO): return NotImplemented def process_imports(self): basepath = os.path.dirname(self.ont.path or "") if self.ont.import_depth != 0: for ref in self.ont.metadata.imports: s = urllib.parse.urlparse(ref).scheme if s in {"ftp", "http", "https"} or os.path.exists(ref): url = ref else: for ext in ["", ".obo", ".json", ".owl"]: if os.path.exists(os.path.join(basepath, f"{ref}{ext}")): url = os.path.join(basepath, f"{ref}{ext}") break else: if not os.path.splitext(ref)[1]: ref = f"{ref}.obo" url = f"http://purl.obolibrary.org/obo/{ref}" self.ont.imports[ref] = type(self.ont)( url, max(self.ont.import_depth-1, 0), self.ont.timeout, )
import abc import os import typing import urllib.parse if typing.TYPE_CHECKING: from ..ontology import Ontology class BaseParser(abc.ABC): def __init__(self, ont: 'Ontology'): self.ont = ont @classmethod @abc.abstractmethod def can_parse(cls, path: str, buffer: bytes): """Return `True` if this parser type can parse the given handle. """ return NotImplemented @abc.abstractmethod def parse_from(self, handle: typing.BinaryIO): return NotImplemented def process_imports(self): if self.ont.import_depth != 0: for ref in self.ont.metadata.imports: s = urllib.parse.urlparse(ref).scheme if s in {"ftp", "http", "https"} or os.path.exists(ref): url = ref elif os.path.exists(f"{ref}.obo"): url = f"{ref}.obo" elif os.path.exists(f"{ref}.json"): url = f"{ref}.json" else: url = f"http://purl.obolibrary.org/obo/{ref}.obo" self.ont.imports[ref] = type(self.ont)( url, max(self.ont.import_depth-1, 0), self.ont.timeout, )
Add python_requires to help pip
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup import restless setup( name='restless', version=restless.VERSION, description='A lightweight REST miniframework for Python.', author='Daniel Lindsley', author_email='[email protected]', url='http://github.com/toastdriven/restless/', long_description=open('README.rst', 'r').read(), packages=[ 'restless', ], requires=[ 'six(>=1.4.0)', ], install_requires=[ 'six>=1.4.0', ], tests_require=[ 'mock', 'tox', ], python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Flask', 'Framework :: Pyramid', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Utilities' ], )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup import restless setup( name='restless', version=restless.VERSION, description='A lightweight REST miniframework for Python.', author='Daniel Lindsley', author_email='[email protected]', url='http://github.com/toastdriven/restless/', long_description=open('README.rst', 'r').read(), packages=[ 'restless', ], requires=[ 'six(>=1.4.0)', ], install_requires=[ 'six>=1.4.0', ], tests_require=[ 'mock', 'tox', ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Flask', 'Framework :: Pyramid', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Utilities' ], )
Reduce size of chart with query
'use strict'; var ChartsController = function($scope, $rootScope) { $scope.drawChart = function() { if ($scope.geoAggData && $scope.geoAggData.length > 0) { var length = $scope.geoAggData.length; var height = 320; var width = 370; var margin = '-40px 10px 0px 0px'; if (length == 1) { height = 300; width = 350; margin = '40px 0px 0px 30px'; } // instantiate d3plus d3plus.viz() .container('#viz') // container DIV to hold the visualization .data($scope.geoAggData) // data to use with the visualization .type('bubbles') // visualization type .id(['group', 'name']) // nesting keys .depth(1) // 0-based depth .size('value') // key name to size bubbles .color('name') // color by each group .legend({value: false}) .margin(margin) .width({value: width}) .height({value: height}) .draw() // finally, draw the visualization! if (window._gaq) { _gaq.push(['_trackEvent', 'police-uk', 'chart']); } } } };
'use strict'; var ChartsController = function($scope, $rootScope) { $scope.drawChart = function() { if ($scope.geoAggData && $scope.geoAggData.length > 0) { console.log('$scope.geoAggData', $scope.geoAggData, 'length', $scope.geoAggData); // instantiate d3plus d3plus.viz() .container('#viz') // container DIV to hold the visualization .data($scope.geoAggData) // data to use with the visualization .type('bubbles') // visualization type .id(['group', 'name']) // nesting keys .depth(1) // 0-based depth .size('value') // key name to size bubbles .color('name') // color by each group .legend({value: false}) .margin('-40px 10px 0px 0px') .width({value: 370}) .height({value: 320}) .draw() // finally, draw the visualization! if (window._gaq) { _gaq.push(['_trackEvent', 'police-uk', 'chart']); } } } };
Update BuiltIn library reference for RF 2.9 compatibility
# -*- coding: utf-8 -*- import os import sys from robot.libraries.BuiltIn import BuiltIn from robot.api import logger from keywordgroup import KeywordGroup class _LoggingKeywords(KeywordGroup): # Private def _debug(self, message): logger.debug(message) def _get_log_dir(self): variables = BuiltIn().get_variables() logfile = variables['${LOG FILE}'] if logfile != 'NONE': return os.path.dirname(logfile) return variables['${OUTPUTDIR}'] def _html(self, message): logger.info(message, True, False) def _info(self, message): logger.info(message) def _log(self, message, level='INFO'): level = level.upper() if (level == 'INFO'): self._info(message) elif (level == 'DEBUG'): self._debug(message) elif (level == 'WARN'): self._warn(message) elif (level == 'HTML'): self._html(message) def _log_list(self, items, what='item'): msg = ['Altogether %d %s%s.' % (len(items), what, ['s',''][len(items)==1])] for index, item in enumerate(items): msg.append('%d: %s' % (index+1, item)) self._info('\n'.join(msg)) return items def _warn(self, message): logger.warn(message)
# -*- coding: utf-8 -*- import os import sys from robot.variables import GLOBAL_VARIABLES from robot.api import logger from keywordgroup import KeywordGroup class _LoggingKeywords(KeywordGroup): # Private def _debug(self, message): logger.debug(message) def _get_log_dir(self): logfile = GLOBAL_VARIABLES['${LOG FILE}'] if logfile != 'NONE': return os.path.dirname(logfile) return GLOBAL_VARIABLES['${OUTPUTDIR}'] def _html(self, message): logger.info(message, True, False) def _info(self, message): logger.info(message) def _log(self, message, level='INFO'): level = level.upper() if (level == 'INFO'): self._info(message) elif (level == 'DEBUG'): self._debug(message) elif (level == 'WARN'): self._warn(message) elif (level == 'HTML'): self._html(message) def _log_list(self, items, what='item'): msg = ['Altogether %d %s%s.' % (len(items), what, ['s',''][len(items)==1])] for index, item in enumerate(items): msg.append('%d: %s' % (index+1, item)) self._info('\n'.join(msg)) return items def _warn(self, message): logger.warn(message)
Create directory, if necessary, before preprocessing files as well
#!/usr/bin/env python import errno import os import ctk_cli import keras.models as M from tubetk.vseg.cnn import deploy, utils script_params = utils.script_params def main(args): utils.set_params_path(args.params) if (args.resampled is None) ^ (script_params['RESAMPLE_SPACING'] is None or args.preprocessed is None): raise ValueError("A resampled image should be supplied iff resampling is" " enabled in the parameters file and a preprocessed" " image is given.") try: os.mkdir(args.outputDir) except OSError as e: if e.errno != errno.EEXIST: raise if args.preprocessed is None: args.resampled, args.preprocessed = deploy.prep(args.inputImage, args.outputDir) elif args.resampled is None: args.resampled = args.inputImage model = M.load_model(args.model) prefix = os.path.join(args.outputDir, os.path.splitext(os.path.basename(args.inputImage))[0]) deploy.generate_seed_points(model, args.preprocessed, prefix) deploy.segmentTubes(args.resampled, args.vascularModelFile, prefix, script_params['VESSEL_SEED_PROBABILITY'], script_params['VESSEL_SCALE']) if __name__ == '__main__': main(ctk_cli.CLIArgumentParser().parse_args())
#!/usr/bin/env python import errno import os import ctk_cli import keras.models as M from tubetk.vseg.cnn import deploy, utils script_params = utils.script_params def main(args): utils.set_params_path(args.params) if (args.resampled is None) ^ (script_params['RESAMPLE_SPACING'] is None or args.preprocessed is None): raise ValueError("A resampled image should be supplied iff resampling is" " enabled in the parameters file and a preprocessed" " image is given.") if args.preprocessed is None: args.resampled, args.preprocessed = deploy.prep(args.inputImage, args.outputDir) elif args.resampled is None: args.resampled = args.inputImage try: os.mkdir(args.outputDir) except OSError as e: if e.errno != errno.EEXIST: raise model = M.load_model(args.model) prefix = os.path.join(args.outputDir, os.path.splitext(os.path.basename(args.inputImage))[0]) deploy.generate_seed_points(model, args.preprocessed, prefix) deploy.segmentTubes(args.resampled, args.vascularModelFile, prefix, script_params['VESSEL_SEED_PROBABILITY'], script_params['VESSEL_SCALE']) if __name__ == '__main__': main(ctk_cli.CLIArgumentParser().parse_args())
Revert 232677 "Revert 232670 "Fix script after r232641"" False alarm, tests we failing due to PDT switch. > Revert 232670 "Fix script after r232641" > > Needs to be out to speculatively revert r232641. > > > Fix script after r232641 > > > > BUG=314253 > > [email protected] > > > > Review URL: https://codereview.chromium.org/49753004 > > [email protected] > > Review URL: https://codereview.chromium.org/57293002 [email protected] Review URL: https://codereview.chromium.org/57323002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@232682 0039d316-1c4b-4281-b951-d872f2087c98
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A wrapper script that invokes test-webkitpy.""" import optparse import os import sys from common import chromium_utils from slave import build_directory from slave import slave_utils def main(): option_parser = optparse.OptionParser() option_parser.add_option('--build-dir', help='ignored') # Note that --target isn't needed for --lint-test-files, but the # RunPythonCommandInBuildDir() will get upset if we don't say something. option_parser.add_option('', '--target', default='release', help='DumpRenderTree build configuration (Release or Debug)') options, _ = option_parser.parse_args() options.build_dir = build_directory.GetBuildOutputDirectory() build_dir = os.path.abspath(options.build_dir) webkit_tests_dir = chromium_utils.FindUpward(build_dir, 'third_party', 'WebKit', 'Tools', 'Scripts') command = [os.path.join(webkit_tests_dir, 'test-webkitpy')] return slave_utils.RunPythonCommandInBuildDir(build_dir, options.target, command) if '__main__' == __name__: sys.exit(main())
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A wrapper script that invokes test-webkitpy.""" import optparse import os import sys from common import chromium_utils from slave import build_directory from slave import slave_utils def main(): option_parser = optparse.OptionParser() option_parser.add_option('--build-dir', help='ignored') # Note that --target isn't needed for --lint-test-files, but the # RunPythonCommandInBuildDir() will get upset if we don't say something. option_parser.add_option('', '--target', default='release', help='DumpRenderTree build configuration (Release or Debug)') options, _ = option_parser.parse_args() options.build_dir, _ = build_directory.GetBuildOutputDirectory() build_dir = os.path.abspath(options.build_dir) webkit_tests_dir = chromium_utils.FindUpward(build_dir, 'third_party', 'WebKit', 'Tools', 'Scripts') command = [os.path.join(webkit_tests_dir, 'test-webkitpy')] return slave_utils.RunPythonCommandInBuildDir(build_dir, options.target, command) if '__main__' == __name__: sys.exit(main())
Enable Isosurface class by default
#!/usr/bin/env python from __future__ import print_function from setuptools import setup, find_packages entry_points = """ [glue.plugins] vispy_volume=glue_vispy_viewers.volume:setup vispy_scatter=glue_vispy_viewers.scatter:setup vispy_isosurface=glue_vispy_viewers.isosurface:setup """ # Add the following to the above entry points to enable the isosurface viewer # vispy_isosurface=glue_vispy_viewers.isosurface:setup try: import pypandoc LONG_DESCRIPTION = pypandoc.convert('README.md', 'rst') except (IOError, ImportError): with open('README.md') as infile: LONG_DESCRIPTION = infile.read() setup(name='glue-vispy-viewers', version="0.2.dev0", description='Vispy-based viewers for Glue', long_description=LONG_DESCRIPTION, url="https://github.com/glue-viz/glue-3d-viewer", author='Penny Qian, Maxwell Tsai, and Thomas Robitaille', author_email='[email protected]', packages = find_packages(), package_data={'glue_vispy_viewers.volume': ['*.ui'], 'glue_vispy_viewers.common': ['*.ui'], 'glue_vispy_viewers.isosurface': ['*.ui'], 'glue_vispy_viewers.scatter': ['*.ui']}, entry_points=entry_points )
#!/usr/bin/env python from __future__ import print_function from setuptools import setup, find_packages entry_points = """ [glue.plugins] vispy_volume=glue_vispy_viewers.volume:setup vispy_scatter=glue_vispy_viewers.scatter:setup """ # Add the following to the above entry points to enable the isosurface viewer # vispy_isosurface=glue_vispy_viewers.isosurface:setup try: import pypandoc LONG_DESCRIPTION = pypandoc.convert('README.md', 'rst') except (IOError, ImportError): with open('README.md') as infile: LONG_DESCRIPTION = infile.read() setup(name='glue-vispy-viewers', version="0.2.dev0", description='Vispy-based viewers for Glue', long_description=LONG_DESCRIPTION, url="https://github.com/glue-viz/glue-3d-viewer", author='Penny Qian, Maxwell Tsai, and Thomas Robitaille', author_email='[email protected]', packages = find_packages(), package_data={'glue_vispy_viewers.volume': ['*.ui'], 'glue_vispy_viewers.common': ['*.ui'], 'glue_vispy_viewers.isosurface': ['*.ui'], 'glue_vispy_viewers.scatter': ['*.ui']}, entry_points=entry_points )
Fix params with period not being passed to callback
(function(win){ 'use strict'; var paramRe = /:([^\/.\\]+)/g; function Router(){ if(!(this instanceof Router)){ return new Router(); } this.routes = []; } Router.prototype.route = function(path, fn){ paramRe.lastIndex = 0; var regexp = path + '', match; while(match = paramRe.exec(path)){ regexp = regexp.replace(match[0], '([^/\\\\]+)'); } this.routes.push({ regexp: new RegExp('^' + regexp + '$'), callback: fn }); return this; }; Router.prototype.dispatch = function(path){ path = path || win.location.pathname; for(var i = 0, len = this.routes.length, route, matches; i < len; i++){ route = this.routes[i]; matches = route.regexp.exec(path); if(matches && matches[0]){ route.callback.apply(null, matches.slice(1)); return this; } } return this; }; win.Router = Router; })(this);
(function(win){ 'use strict'; var paramRe = /:([^\/.\\]+)/g; function Router(){ if(!(this instanceof Router)){ return new Router(); } this.routes = []; } Router.prototype.route = function(path, fn){ paramRe.lastIndex = 0; var regexp = path + '', match; while(match = paramRe.exec(path)){ regexp = regexp.replace(match[0], '([^/.\\\\]+)'); } this.routes.push({ regexp: new RegExp('^' + regexp + '$'), callback: fn }); return this; }; Router.prototype.dispatch = function(path){ path = path || win.location.pathname; for(var i = 0, len = this.routes.length, route, matches; i < len; i++){ route = this.routes[i]; matches = route.regexp.exec(path); if(matches && matches[0]){ route.callback.apply(null, matches.slice(1)); return this; } } return this; }; win.Router = Router; })(this);
Add Filter option for order amd order group
from django.contrib import admin from digikey.models import Components, Orders, Order_Details, Groups class ComponentInline(admin.TabularInline): model = Order_Details extra = 1 class OrderInline(admin.TabularInline): model = Orders extra = 1 fieldsets = [ ('Payment information', {'fields': ['paid', 'paid_account', 'paid_date']}), ('Additional Shipping information', {'fields': ['receiver', 'shipping_address', 'phone_number']}), ] @admin.register(Orders) class OrderAdmin(admin.ModelAdmin): list_filter = ['sent', 'paid', 'sent_date'] list_display = ('pk', 'group_id','paid', 'sent') fieldsets = [ (None, {'fields': ['Orderer', 'group_id']}), ('Payment information', {'fields': ['paid', 'paid_account', 'paid_date']}), ('Uplink information', {'fields': ['sent', 'sent_date']}), ('Additional Shipping information', {'fields': ['receiver', 'shipping_address', 'phone_number']}), ] inlines = [ComponentInline] @admin.register(Groups) class GroupAdmin(admin.ModelAdmin): list_filter = ['ordered', 'orderdate'] fieldsets = [ (None, {'fields': ['ordered', 'orderdate']}), ] inlines = [OrderInline] @admin.register(Components) class ComponentAdmin(admin.ModelAdmin): list_display = ('part_number','unit_price')
from django.contrib import admin from digikey.models import Components, Orders, Order_Details, Groups class ComponentInline(admin.TabularInline): model = Order_Details extra = 1 class OrderInline(admin.TabularInline): model = Orders extra = 1 fieldsets = [ ('Payment information', {'fields': ['paid', 'paid_account', 'paid_date']}), ('Additional Shipping information', {'fields': ['receiver', 'shipping_address', 'phone_number']}), ] @admin.register(Orders) class OrderAdmin(admin.ModelAdmin): list_display = ('pk', 'group_id','paid', 'sent') fieldsets = [ (None, {'fields': ['Orderer', 'group_id']}), ('Payment information', {'fields': ['paid', 'paid_account', 'paid_date']}), ('Uplink information', {'fields': ['sent', 'sent_date']}), ('Additional Shipping information', {'fields': ['receiver', 'shipping_address', 'phone_number']}), ] inlines = [ComponentInline] @admin.register(Groups) class GroupAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['ordered', 'orderdate']}), ] inlines = [OrderInline] @admin.register(Components) class ComponentAdmin(admin.ModelAdmin): list_display = ('part_number','unit_price')
Refactor matrix creation to use values slice
function Matrix(options) { options = options || {}; var values; if (options.values) { values = options.values.slice(); for (var k = 0; k < values.length; k++) values[k] = values[k].slice(); } if (options.rows && options.columns && !values) { values = []; for (var k = 0; k < options.rows; k++) { var row = []; for (var j = 0; j < options.columns; j++) row[j] = 0; values.push(row); } } this.nrows = function () { if (!values) return 0; return values.length; }; this.ncolumns = function () { if (!values) return 0; return values[0].length; }; this.element = function (r, c) { if (!values) return 0; var row = values[r]; if (!row) return 0; var element = values[r][c]; return element == null ? 0 : element; }; } Matrix.prototype.isMatrix = function () { return true; } Matrix.prototype.isVector = function () { return false; } function createMatrix(options) { return new Matrix(options); } module.exports = { createMatrix: createMatrix }
function Matrix(options) { options = options || {}; var values; if (options.values) values = options.values; if (options.rows && options.columns && !values) { values = []; for (var k = 0; k < options.rows; k++) { var row = []; for (var j = 0; j < options.columns; j++) row[j] = 0; values.push(row); } } this.nrows = function () { if (!values) return 0; return values.length; }; this.ncolumns = function () { if (!values) return 0; return values[0].length; }; this.element = function (r, c) { if (!values) return 0; var row = values[r]; if (!row) return 0; var element = values[r][c]; return element == null ? 0 : element; }; } Matrix.prototype.isMatrix = function () { return true; } Matrix.prototype.isVector = function () { return false; } function createMatrix(options) { return new Matrix(options); } module.exports = { createMatrix: createMatrix }
Exclude missing annotations from coverage
<?php declare(strict_types=1); namespace Overblog\GraphQLBundle\Config\Parser; use Doctrine\Common\Annotations\AnnotationReader; use Doctrine\Common\Annotations\AnnotationRegistry; use Overblog\GraphQLBundle\Config\Parser\MetadataParser\MetadataParser; use ReflectionClass; use ReflectionMethod; use ReflectionProperty; use Reflector; use RuntimeException; class AnnotationParser extends MetadataParser { const METADATA_FORMAT = '@%s'; protected static ?AnnotationReader $annotationReader = null; protected static function getMetadatas(Reflector $reflector): array { $reader = self::getAnnotationReader(); switch (true) { case $reflector instanceof ReflectionClass: return $reader->getClassAnnotations($reflector); case $reflector instanceof ReflectionMethod: return $reader->getMethodAnnotations($reflector); case $reflector instanceof ReflectionProperty: return $reader->getPropertyAnnotations($reflector); } return []; } protected static function getAnnotationReader(): AnnotationReader { if (null === self::$annotationReader) { if (!class_exists(AnnotationReader::class) || !class_exists(AnnotationRegistry::class)) { // @codeCoverageIgnoreStart throw new RuntimeException('In order to use graphql annotation, you need to require doctrine annotations'); // @codeCoverageIgnoreEnd } AnnotationRegistry::registerLoader('class_exists'); self::$annotationReader = new AnnotationReader(); } return self::$annotationReader; } }
<?php declare(strict_types=1); namespace Overblog\GraphQLBundle\Config\Parser; use Doctrine\Common\Annotations\AnnotationReader; use Doctrine\Common\Annotations\AnnotationRegistry; use Overblog\GraphQLBundle\Config\Parser\MetadataParser\MetadataParser; use ReflectionClass; use ReflectionMethod; use ReflectionProperty; use Reflector; use RuntimeException; class AnnotationParser extends MetadataParser { const METADATA_FORMAT = '@%s'; protected static ?AnnotationReader $annotationReader = null; protected static function getMetadatas(Reflector $reflector): array { $reader = self::getAnnotationReader(); switch (true) { case $reflector instanceof ReflectionClass: return $reader->getClassAnnotations($reflector); case $reflector instanceof ReflectionMethod: return $reader->getMethodAnnotations($reflector); case $reflector instanceof ReflectionProperty: return $reader->getPropertyAnnotations($reflector); } return []; } protected static function getAnnotationReader(): AnnotationReader { if (null === self::$annotationReader) { if (!class_exists(AnnotationReader::class) || !class_exists(AnnotationRegistry::class)) { throw new RuntimeException('In order to use graphql annotation, you need to require doctrine annotations'); } AnnotationRegistry::registerLoader('class_exists'); self::$annotationReader = new AnnotationReader(); } return self::$annotationReader; } }
Check to make sure created file actually exists.
package com.miguelgaeta.media_picker; import android.os.Environment; import java.io.File; import java.io.IOException; import java.util.UUID; @SuppressWarnings("UnusedDeclaration") public class MediaPickerFile { /** * Create a file in the devices external storage. * * @param directory Target directory. * @param name Target file name. * @param suffix Target file suffix. * * @return Created file. * * @throws IOException */ public static File create(final String directory, final String name, final String suffix) throws IOException { final File dir = new File(Environment.getExternalStorageDirectory() + File.separator + directory); if (!dir.exists()) { boolean result = dir.mkdirs(); if (!result) { throw new IOException("Unable to create directory."); } } final File file = File.createTempFile(name, suffix, dir); if (!file.exists()) { throw new IOException("Unable to create temporary file, does not exist."); } return File.createTempFile(name, suffix, dir); } /** * @see #create(String, String, String) */ public static File create(final String directory, final String name) throws IOException { return create(directory, name, null); } /** * @see #create(String, String) */ public static File create(final String directory) throws IOException { return create(directory, UUID.randomUUID().toString()); } /** * @see #create(String) */ public static File create() throws IOException { return create("media_picker"); } }
package com.miguelgaeta.media_picker; import android.os.Environment; import java.io.File; import java.io.IOException; import java.util.UUID; @SuppressWarnings("UnusedDeclaration") public class MediaPickerFile { /** * Create a file in the devices external storage. * * @param directory Target directory. * @param name Target file name. * @param suffix Target file suffix. * * @return Created file. * * @throws IOException */ public static File create(final String directory, final String name, final String suffix) throws IOException { final File dir = new File(Environment.getExternalStorageDirectory() + File.separator + directory); if (!dir.exists()) { boolean result = dir.mkdirs(); if (!result) { throw new IOException("Unable to create directory."); } } return File.createTempFile(name, suffix, dir); } /** * @see #create(String, String, String) */ public static File create(final String directory, final String name) throws IOException { return create(directory, name, null); } /** * @see #create(String, String) */ public static File create(final String directory) throws IOException { return create(directory, UUID.randomUUID().toString()); } /** * @see #create(String) */ public static File create() throws IOException { return create("media_picker"); } }
Fix checking apikey outside runserver
from django.contrib.auth.models import AnonymousUser from rest_framework import authentication from rest_framework import exceptions from events.models import DataSource from django.utils.translation import ugettext_lazy as _ class ApiKeyAuthentication(authentication.BaseAuthentication): def authenticate(self, request): # django converts 'apikey' to 'HTTP_APIKEY' outside runserver api_key = request.META.get('apikey') or request.META.get('HTTP_APIKEY') if not api_key: return None data_source = self.get_data_source(api_key=api_key) return ApiKeyUser(), ApiKeyAuth(data_source) def authenticate_header(self, request): """ Return a string to be used as the value of the `WWW-Authenticate` header in a `401 Unauthenticated` response, or `None` if the authentication scheme should return `403 Permission Denied` responses. """ return "Api key authentication failed." @staticmethod def get_data_source(api_key): try: data_source = DataSource.objects.get(api_key=api_key) except DataSource.DoesNotExist: raise exceptions.AuthenticationFailed(_( "Provided API key does not match any organization on record. " "Please contact the API support staff to obtain a valid API key " "and organization identifier for POSTing your events.")) return data_source class ApiKeyUser(AnonymousUser): def is_authenticated(self): return True class ApiKeyAuth(object): def __init__(self, data_source): self.data_source = data_source def get_authenticated_data_source(self): return self.data_source
from django.contrib.auth.models import AnonymousUser from rest_framework import authentication from rest_framework import exceptions from events.models import DataSource from django.utils.translation import ugettext_lazy as _ class ApiKeyAuthentication(authentication.BaseAuthentication): def authenticate(self, request): api_key = request.META.get('apikey') if not api_key: return None data_source = self.get_data_source(api_key=api_key) return ApiKeyUser(), ApiKeyAuth(data_source) def authenticate_header(self, request): """ Return a string to be used as the value of the `WWW-Authenticate` header in a `401 Unauthenticated` response, or `None` if the authentication scheme should return `403 Permission Denied` responses. """ return "Api key authentication failed." @staticmethod def get_data_source(api_key): try: data_source = DataSource.objects.get(api_key=api_key) except DataSource.DoesNotExist: raise exceptions.AuthenticationFailed(_( "Provided API key does not match any organization on record. " "Please contact the API support staff to obtain a valid API key " "and organization identifier for POSTing your events.")) return data_source class ApiKeyUser(AnonymousUser): def is_authenticated(self): return True class ApiKeyAuth(object): def __init__(self, data_source): self.data_source = data_source def get_authenticated_data_source(self): return self.data_source
Fix serializer test with proper argument to FTLSerializer
'use strict'; import fs from 'fs'; import path from 'path'; import assert from 'assert'; import FTLParser from '../../../../src/lib/format/ftl/ast/parser'; import FTLSerializer from '../../../../src/lib/format/ftl/ast/serializer'; var parse = FTLParser.parseResource; function readFile(path) { return new Promise(function(resolve, reject) { fs.readFile(path, 'utf8', (err, data) => { resolve(data); }); }); } function testSerialize(path1) { return Promise.all([ readFile(path1), ]).then(([source1]) => { let ftl = parse(source1); let out = FTLSerializer.serialize(ftl.body); let ftl2 = parse(out); assert.deepEqual(ftl.body, ftl2.body, `Serialized output for ${path1} should be the same`); }); } var basePath = './test/lib/fixtures/parser/ftl'; describe('FTL Serializer', function() { it('fixtures work', function(done) { fs.readdir(basePath, (err, paths) => { let tests = []; paths.forEach(fileName => { if (!fileName.endsWith('.ftl') || fileName.indexOf('error') !== -1) { return; } let ftlPath = path.join(basePath, fileName); tests.push(testSerialize(ftlPath)); }); Promise.all(tests).then(() => { done() }, (err) => { done(err) }); }); }); });
'use strict'; import fs from 'fs'; import path from 'path'; import assert from 'assert'; import FTLParser from '../../../../src/lib/format/ftl/ast/parser'; import FTLSerializer from '../../../../src/lib/format/ftl/ast/serializer'; var parse = FTLParser.parseResource; function readFile(path) { return new Promise(function(resolve, reject) { fs.readFile(path, 'utf8', (err, data) => { resolve(data); }); }); } function testSerialize(path1) { return Promise.all([ readFile(path1), ]).then(([source1]) => { let ftl = parse(source1); let out = FTLSerializer.serialize(ftl); let ftl2 = parse(out); assert.deepEqual(ftl.body, ftl2.body, `Serialized output for ${path1} should be the same`); }); } var basePath = './test/lib/fixtures/parser/ftl'; describe('FTL Serializer', function() { it('fixtures work', function(done) { fs.readdir(basePath, (err, paths) => { let tests = []; paths.forEach(fileName => { if (!fileName.endsWith('.ftl') || fileName.indexOf('error') !== -1) { return; } let ftlPath = path.join(basePath, fileName); tests.push(testSerialize(ftlPath)); }); Promise.all(tests).then(() => { done() }, (err) => { done(err) }); }); }); });
Support debug logging for gocd
var path = require('path'); var yaml_config = require('node-yaml-config'); var _ = require('lodash'); function ymlHerokuConfigModule() { var HEROKU_VARS_SUPPORT = [ 'user', 'password', 'url', 'pipeline', 'jobs', 'key', 'secret', 'account', 'debug' ]; var create = function (configKey) { var config; var id = configKey; init(); var get = function () { return config[id]; }; function init() { try { config = yaml_config.load('config.yml'); } catch (err) { console.log('could not read yml, trying Heroku vars', err); config = {}; config[id] = {}; _.each(HEROKU_VARS_SUPPORT, function(varName) { config[id][varName] = process.env[id.toUpperCase() + '_' + varName.toUpperCase()]; }); if(config[id].jobs) { config[id].jobs = config[id].jobs.split(','); } if (!config[id].user || !config[id].password || !config[id].url) { console.log('ERROR: Not enough values in ' + id + ' config, cannot get data'); } } config[id] = config[id] || { sample: true }; } return { get: get }; }; return { create: create }; } exports.create = ymlHerokuConfigModule().create;
var path = require('path'); var yaml_config = require('node-yaml-config'); var _ = require('lodash'); function ymlHerokuConfigModule() { var HEROKU_VARS_SUPPORT = [ 'user', 'password', 'url', 'pipeline', 'jobs', 'key', 'secret', 'account' ]; var create = function (configKey) { var config; var id = configKey; init(); var get = function () { return config[id]; }; function init() { try { config = yaml_config.load('config.yml'); } catch (err) { console.log('could not read yml, trying Heroku vars', err); config = {}; config[id] = {}; _.each(HEROKU_VARS_SUPPORT, function(varName) { config[id][varName] = process.env[id.toUpperCase() + '_' + varName.toUpperCase()]; }); if(config[id].jobs) { config[id].jobs = config[id].jobs.split(','); } if (!config[id].user || !config[id].password || !config[id].url) { console.log('ERROR: Not enough values in ' + id + ' config, cannot get data'); } } config[id] = config[id] || { sample: true }; } return { get: get }; }; return { create: create }; } exports.create = ymlHerokuConfigModule().create;
Change host name to ml.jaseg.net
package de.cketti.matelight; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; public class MateLight { private static final String HOST = "ml.jaseg.net"; private static final int PORT = 1337; private static final String SUCCESS = "KTHXBYE!"; private static final int TIMEOUT = 60 * 1000; private Socket mSocket; public void sendMessage(String message) throws IOException { mSocket = new Socket(); mSocket.connect(new InetSocketAddress(HOST, PORT)); try { OutputStream out = mSocket.getOutputStream(); try { mSocket.setSoTimeout(TIMEOUT); out.write(message.getBytes()); out.write('\n'); out.flush(); InputStream in = mSocket.getInputStream(); try { BufferedReader buf = new BufferedReader(new InputStreamReader(in)); String response = buf.readLine(); if (!SUCCESS.equals(response)) { throw new RuntimeException("No success message from server"); } } finally { in.close(); } } finally { out.close(); } } finally { mSocket.close(); } } public void cancel() { try { mSocket.close(); } catch (Exception e) { // ignore } } }
package de.cketti.matelight; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; public class MateLight { private static final String HOST = "matelight.cbrp3.c-base.org"; private static final int PORT = 1337; private static final String SUCCESS = "KTHXBYE!"; private static final int TIMEOUT = 60 * 1000; private Socket mSocket; public void sendMessage(String message) throws IOException { mSocket = new Socket(); mSocket.connect(new InetSocketAddress(HOST, PORT)); try { OutputStream out = mSocket.getOutputStream(); try { mSocket.setSoTimeout(TIMEOUT); out.write(message.getBytes()); out.write('\n'); out.flush(); InputStream in = mSocket.getInputStream(); try { BufferedReader buf = new BufferedReader(new InputStreamReader(in)); String response = buf.readLine(); if (!SUCCESS.equals(response)) { throw new RuntimeException("No success message from server"); } } finally { in.close(); } } finally { out.close(); } } finally { mSocket.close(); } } public void cancel() { try { mSocket.close(); } catch (Exception e) { // ignore } } }
Join template on related content query
<?php namespace Opifer\CmsBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; /** * Template Controller */ class TemplateController extends Controller { /** * Remove a template * * @param int $id * * @return Response */ public function deleteAction($id) { $em = $this->getDoctrine()->getManager(); $template = $this->get('opifer.eav.template_manager')->getRepository()->find($id); $slug = 'templates'; if (!$template) { return $this->createNotFoundException(); } $relatedContent = $em->getRepository('OpiferCmsBundle:Content') ->createValuedQueryBuilder('c') ->innerJoin('vs.template', 't') ->select('COUNT(c)') ->where('t.id = :template') ->setParameter('template', $id) ->getQuery() ->getSingleScalarResult(); if ($relatedContent > 0) { $this->addFlash('error', 'template.delete.warning'); return $this->redirectToRoute('opifer.crud.index', [ 'slug' => $slug ]); } return $this->forward('OpiferCrudBundle:Crud:delete',[ 'entity' => $template, 'slug' => $slug, 'id' => $id ]); } }
<?php namespace Opifer\CmsBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; /** * Template Controller */ class TemplateController extends Controller { /** * Remove a template * * @param int $id * * @return Response */ public function deleteAction($id) { $em = $this->getDoctrine()->getManager(); $template = $this->get('opifer.eav.template_manager')->getRepository()->find($id); $slug = 'templates'; if (!$template) { return $this->createNotFoundException(); } $relatedContent = $em->getRepository('OpiferCmsBundle:Content') ->createValuedQueryBuilder('c') ->select('COUNT(c)') ->where('t.id = :template') ->setParameter('template', $id) ->getQuery() ->getSingleScalarResult(); if ($relatedContent > 0) { $this->addFlash('error', 'template.delete.warning'); return $this->redirectToRoute('opifer.crud.index', [ 'slug' => $slug ]); } return $this->forward('OpiferCrudBundle:Crud:delete',[ 'entity' => $template, 'slug' => $slug, 'id' => $id ]); } }
Use the materialize CSS markup
<?php namespace fieldwork\components; class TextField extends Field { const ON_ENTER_NEXT = 'next'; const ON_ENTER_SUBMIT = 'submit'; private $onEnter = '', $mask = null; public function getAttributes () { //$att = array('placeholder' => $this->label); $att = array(); if (!empty($this->onEnter)) $att['data-input-action-on-enter'] = $this->onEnter; if ($this->mask !== null) $att['data-input-mask'] = $this->mask; return array_merge(parent::getAttributes(), $att); } public function onEnter ($action = '') { $this->onEnter = $action; return $this; } /** * Sets input mask for this field * * @param string $mask * * @return static */ public function setMask ($mask) { $this->mask = $mask; return $this; } public function getClasses () { return array_merge( parent::getClasses(), array('textfield', 'fieldwork-inputfield') ); } public function getHTML ($showLabel = true) { return sprintf("<div class=\"input-field\"><input type='text' %s><label for=\"%s\">%s</label></div>", $this->getAttributesString(), $this->getId(), $this->label); } }
<?php namespace fieldwork\components; class TextField extends Field { const ON_ENTER_NEXT = 'next'; const ON_ENTER_SUBMIT = 'submit'; private $onEnter = '', $mask = null; public function getAttributes () { $att = array('placeholder' => $this->label); if (!empty($this->onEnter)) $att['data-input-action-on-enter'] = $this->onEnter; if ($this->mask !== null) $att['data-input-mask'] = $this->mask; return array_merge(parent::getAttributes(), $att); } public function onEnter ($action = '') { $this->onEnter = $action; return $this; } /** * Sets input mask for this field * * @param string $mask * * @return static */ public function setMask ($mask) { $this->mask = $mask; return $this; } public function getClasses () { return array_merge( parent::getClasses(), array('textfield', 'fieldwork-inputfield') ); } public function getHTML ($showLabel = true) { return "<input type='text'" . $this->getAttributesString() . ">"; } }
Convert user to array on successful login
<?php namespace Lavoaster\LightBlog\User\Controllers; use Lavoaster\LightBlog\User\Repositories\UserRepositoryInterface; class UserController extends \BaseController { protected $user; public function __construct(UserRepositoryInterface $user) { $this->user = $user; } public function login() { // Login form } public function authenticate() { $validation = \Validator::make(\Input::input(), [ 'email' => 'required|email', 'password' => 'required' ]); if($validation->fails()) { return [ 'success' => false, 'errors' => $validation->errors()->toArray() ]; } if(\Auth::attempt(['email' => \Input::input('email'), 'password' => \Input::input('password')])) { return [ 'success' => true, 'user' => \Auth::getUser()->toArray() ]; } return [ 'success' => false, 'errors' => [ 'wrong' => ['Whoops, looks like you\'ve a wrong email or password :('] ] ]; } }
<?php namespace Lavoaster\LightBlog\User\Controllers; use Lavoaster\LightBlog\User\Repositories\UserRepositoryInterface; class UserController extends \BaseController { protected $user; public function __construct(UserRepositoryInterface $user) { $this->user = $user; } public function login() { // Login form } public function authenticate() { $validation = \Validator::make(\Input::input(), [ 'email' => 'required|email', 'password' => 'required' ]); if($validation->fails()) { return [ 'success' => false, 'errors' => $validation->errors()->toArray() ]; } if(\Auth::attempt(['email' => \Input::input('email'), 'password' => \Input::input('password')])) { return [ 'success' => true, 'user' => \Auth::getUser() ]; } return [ 'success' => false, 'errors' => [ 'wrong' => ['Whoops, looks like you\'ve a wrong email or password :('] ] ]; } }
Remove unnecessary middleware for now
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array */ protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, ]; /** * The application's route middleware groups. * * @var array */ protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, //\App\Http\Middleware\VerifyCsrfToken::class, ], 'api' => [ 'throttle:60,1', ], ]; /** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'roles' => \App\Http\Middleware\Roles::class, ]; }
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array */ protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, ]; /** * The application's route middleware groups. * * @var array */ protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, // Disabled to make POST man requests ], 'api' => [ 'throttle:60,1', ], ]; /** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'roles' => \App\Http\Middleware\Roles::class, ]; }
Update maxValues for fps anf cps
const series = { fps: { label: "FPS", maxValue: 125, color: "#F78900" }, fpsMin: { label: "FPS Min", maxValue: 125, color: "#800000" }, cps: { label: "CPS", maxValue: 125, color: "#E5E500" }, playerCount: { label: "Players", maxValue: 400, color: "#3EB2F2" }, localAiCount: { label: "Local AI", maxValue: 1000, color: "#8ECFFF" }, remoteAiCount: { label: "Remote AI", maxValue: 1000, color: "#C9E3FF" }, entityCount: { label: "Entities", maxValue: 1000, color: "#03CC20" } }; const seriesAxes = Object.getOwnPropertyNames(series); module.exports = { seriesAxes: seriesAxes, series: series, graph: { margin: { top: 20, right: 20, bottom: 0, left: 20 }, xLengthInSeconds: 20 * 60, width: 700, height: 260 } }
const series = { fps: { label: "FPS", maxValue: 65, color: "#F78900" }, fpsMin: { label: "FPS Min", maxValue: 65, color: "#800000" }, cps: { label: "CPS", maxValue: 65, color: "#E5E500" }, playerCount: { label: "Players", maxValue: 400, color: "#3EB2F2" }, localAiCount: { label: "Local AI", maxValue: 1000, color: "#8ECFFF" }, remoteAiCount: { label: "Remote AI", maxValue: 1000, color: "#C9E3FF" }, entityCount: { label: "Entities", maxValue: 1000, color: "#03CC20" } }; const seriesAxes = Object.getOwnPropertyNames(series); module.exports = { seriesAxes: seriesAxes, series: series, graph: { margin: { top: 20, right: 20, bottom: 0, left: 20 }, xLengthInSeconds: 20 * 60, width: 700, height: 260 } }
Add a "--force" argument to "bin/config done" Summary: Ref T11922. When we deploy on Saturday I need to rebuild all the cluster indexes, but some instances won't have anything indexed so they won't actually trigger the activity. Add a `--force` flag that just clears an activity even if the activity is not required. Test Plan: Ran `bin/config done reindex --force` several times. Reviewers: chad Reviewed By: chad Maniphest Tasks: T11922 Differential Revision: https://secure.phabricator.com/D16970
<?php final class PhabricatorConfigManagementDoneWorkflow extends PhabricatorConfigManagementWorkflow { protected function didConstruct() { $this ->setName('done') ->setExamples('**done** __activity__') ->setSynopsis(pht('Mark a manual upgrade activity as complete.')) ->setArguments( array( array( 'name' => 'force', 'short' => 'f', 'help' => pht( 'Mark activities complete even if there is no outstanding '. 'need to complete them.'), ), array( 'name' => 'activities', 'wildcard' => true, ), )); } public function execute(PhutilArgumentParser $args) { $is_force = $args->getArg('force'); $activities = $args->getArg('activities'); if (!$activities) { throw new PhutilArgumentUsageException( pht('Specify an activity to mark as completed.')); } foreach ($activities as $type) { $activity = id(new PhabricatorConfigManualActivity())->loadOneWhere( 'activityType = %s', $type); if (!$activity) { if ($is_force) { echo tsprintf( "%s\n", pht( 'Activity "%s" did not need to be marked as complete.', $type)); } else { throw new PhutilArgumentUsageException( pht( 'Activity "%s" is not currently marked as required, so there '. 'is no need to complete it.', $type)); } } else { $activity->delete(); echo tsprintf( "%s\n", pht( 'Marked activity "%s" as completed.', $type)); } } echo tsprintf( "%s\n", pht('Done.')); return 0; } }
<?php final class PhabricatorConfigManagementDoneWorkflow extends PhabricatorConfigManagementWorkflow { protected function didConstruct() { $this ->setName('done') ->setExamples('**done** __activity__') ->setSynopsis(pht('Mark a manual upgrade activity as complete.')) ->setArguments( array( array( 'name' => 'activities', 'wildcard' => true, ), )); } public function execute(PhutilArgumentParser $args) { $activities = $args->getArg('activities'); if (!$activities) { throw new PhutilArgumentUsageException( pht('Specify an activity to mark as completed.')); } foreach ($activities as $type) { $activity = id(new PhabricatorConfigManualActivity())->loadOneWhere( 'activityType = %s', $type); if (!$activity) { throw new PhutilArgumentUsageException( pht( 'Activity "%s" is not currently marked as required, so there '. 'is no need to complete it.', $type)); } else { $activity->delete(); echo tsprintf( "%s\n", pht( 'Marked activity "%s" as completed.', $type)); } } echo tsprintf( "%s\n", pht('Done.')); return 0; } }
Adjust rasa shell help test to changes.
from typing import Callable from _pytest.pytester import RunResult def test_shell_help(run: Callable[..., RunResult]): output = run("shell", "--help") help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet] [--conversation-id CONVERSATION_ID] [-m MODEL] [--log-file LOG_FILE] [--endpoints ENDPOINTS] [-p PORT] [-t AUTH_TOKEN] [--cors [CORS [CORS ...]]] [--enable-api] [--remote-storage REMOTE_STORAGE] [--ssl-certificate SSL_CERTIFICATE] [--ssl-keyfile SSL_KEYFILE] [--ssl-ca-file SSL_CA_FILE] [--ssl-password SSL_PASSWORD] [--credentials CREDENTIALS] [--connector CONNECTOR] [--jwt-secret JWT_SECRET] [--jwt-method JWT_METHOD] {nlu} ... [model-as-positional-argument]""" lines = help_text.split("\n") for i, line in enumerate(lines): assert output.outlines[i] == line def test_shell_nlu_help(run: Callable[..., RunResult]): output = run("shell", "nlu", "--help") help_text = """usage: rasa shell nlu [-h] [-v] [-vv] [--quiet] [-m MODEL] [model-as-positional-argument]""" lines = help_text.split("\n") for i, line in enumerate(lines): assert output.outlines[i] == line
from typing import Callable from _pytest.pytester import RunResult def test_shell_help(run: Callable[..., RunResult]): output = run("shell", "--help") help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet] [-m MODEL] [--log-file LOG_FILE] [--endpoints ENDPOINTS] [-p PORT] [-t AUTH_TOKEN] [--cors [CORS [CORS ...]]] [--enable-api] [--remote-storage REMOTE_STORAGE] [--ssl-certificate SSL_CERTIFICATE] [--ssl-keyfile SSL_KEYFILE] [--ssl-ca-file SSL_CA_FILE] [--ssl-password SSL_PASSWORD] [--credentials CREDENTIALS] [--connector CONNECTOR] [--jwt-secret JWT_SECRET] [--jwt-method JWT_METHOD] {nlu} ... [model-as-positional-argument]""" lines = help_text.split("\n") for i, line in enumerate(lines): assert output.outlines[i] == line def test_shell_nlu_help(run: Callable[..., RunResult]): output = run("shell", "nlu", "--help") help_text = """usage: rasa shell nlu [-h] [-v] [-vv] [--quiet] [-m MODEL] [model-as-positional-argument]""" lines = help_text.split("\n") for i, line in enumerate(lines): assert output.outlines[i] == line
Use destructuring to access this.props.route properties
import React, {Component} from 'react'; import CourseList from './CourseList'; import GpaList from './GpaList'; import { loadSchedule, loadGpa } from '../../data-source'; export default class Schedule extends Component { constructor(props, context) { super(props, context); this.state = { schedule: null, gpa: null }; } componentDidMount() { const { studentsDcid, yearId } = this.props.route; Promise.all([loadSchedule(studentsDcid, yearId), loadGpa(studentsDcid, yearId)]) .then(([schedule, gpa]) => { this.setState({ schedule: schedule, gpa: gpa }); }); } render() { if (this.state.schedule || this.state.gpa) { return ( <div> <h3>Courses</h3> {this.state.schedule && <CourseList courses={this.state.schedule} /> } <h3>GPA</h3> {this.state.gpa && <GpaList gpa={this.state.gpa} /> } </div> ); } else { const refreshClass = 'fa fa-refresh fa-spin fa-3x fa-fw'; return ( <i className={refreshClass}></i> ); } } } Schedule.propTypes = { route: React.PropTypes.shape({studentsDcid: React.PropTypes.string, yearId: React.PropTypes.number}) };
import React, {Component} from 'react'; import CourseList from './CourseList'; import GpaList from './GpaList'; import { loadSchedule, loadGpa } from '../../data-source'; export default class Schedule extends Component { constructor(props, context) { super(props, context); this.state = { schedule: null, gpa: null }; } componentDidMount() { const studentsDcid = this.props.route.studentsDcid; const yearId = this.props.route.yearId; Promise.all([loadSchedule(studentsDcid, yearId), loadGpa(studentsDcid, yearId)]) .then(([schedule, gpa]) => { this.setState({ schedule: schedule, gpa: gpa }); }); } render() { if (this.state.schedule || this.state.gpa) { return ( <div> <h3>Courses</h3> {this.state.schedule && <CourseList courses={this.state.schedule} /> } <h3>GPA</h3> {this.state.gpa && <GpaList gpa={this.state.gpa} /> } </div> ); } else { const refreshClass = 'fa fa-refresh fa-spin fa-3x fa-fw'; return ( <i className={refreshClass}></i> ); } } } Schedule.propTypes = { route: React.PropTypes.shape({studentsDcid: React.PropTypes.string, yearId: React.PropTypes.number}) };