content
stringlengths
128
6.74k
<commit_msg>Address review comment: Better function name. <commit_before>from __future__ import unicode_literals import sys import requests from eliot import Logger, to_file, start_action to_file(sys.stdout) logger = Logger() def request(x, y): with start_action(logger, "http_request", x=x, y=y) as action: task_id = action.serialize_task_id() response = requests.get( "http://localhost:5000/?x={}&y={}".format(x, y), headers={"x-eliot-task-id": task_id}) response.raise_for_status() # ensure this is a successful response result = float(response.text) action.add_success_fields(result=result) return result if __name__ == '__main__': with start_action(logger, "main"): request(int(sys.argv[1]), int(sys.argv[2])) <commit_after>from __future__ import unicode_literals import sys import requests from eliot import Logger, to_file, start_action to_file(sys.stdout) logger = Logger() def remote_divide(x, y): with start_action(logger, "http_request", x=x, y=y) as action: task_id = action.serialize_task_id() response = requests.get( "http://localhost:5000/?x={}&y={}".format(x, y), headers={"x-eliot-task-id": task_id}) response.raise_for_status() # ensure this is a successful response result = float(response.text) action.add_success_fields(result=result) return result if __name__ == '__main__': with start_action(logger, "main"): remote_divide(int(sys.argv[1]), int(sys.argv[2]))
<commit_msg>Add command-line option to set port. <commit_before> import random from twisted.protocols import amp port = 1234 _rand = random.Random() class RollDice(amp.Command): arguments = [('sides', amp.Integer())] response = [('result', amp.Integer())] class Dice(amp.AMP): def roll(self, sides=6): """Return a random integer from 1 to sides""" result = _rand.randint(1, sides) return {'result': result} RollDice.responder(roll) def main(): from twisted.internet import reactor from twisted.internet.protocol import Factory pf = Factory() pf.protocol = Dice reactor.listenTCP(port, pf) reactor.run() if __name__ == '__main__': main() <commit_after> import random from twisted.protocols import amp from twisted.internet import reactor from twisted.internet.protocol import Factory from twisted.python import usage port = 1234 _rand = random.Random() class Options(usage.Options): optParameters = [ ["port", "p", port, "server port"], ] class RollDice(amp.Command): arguments = [('sides', amp.Integer())] response = [('result', amp.Integer())] class Dice(amp.AMP): def roll(self, sides=6): """Return a random integer from 1 to sides""" result = _rand.randint(1, sides) return {'result': result} RollDice.responder(roll) def main(): options = Options() try: options.parseOptions() except usage.UsageError, err: print "%s: %s" % (sys.argv[0], err) print "%s: Try --help for usage details" % sys.argv[0] sys.exit(1) port = int(options["port"]) pf = Factory() pf.protocol = Dice reactor.listenTCP(port, pf) reactor.run() if __name__ == '__main__': main()
<commit_msg>Add information about disabled javascript and how to enable it <commit_before>package com.joshmcarthur.android.web_view_sample; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.webkit.WebView; public class MainActivity extends Activity { WebView browser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); browser = (WebView)findViewById(R.id.webkit); browser.loadUrl("http://joshmcarthur.com"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } <commit_after>package com.joshmcarthur.android.web_view_sample; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.webkit.WebView; public class MainActivity extends Activity { WebView browser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); browser = (WebView)findViewById(R.id.webkit); // Javascript is disabled by default - uncomment this line if you // want to enable it. //browser.getSettings().setJavaScriptEnabled(true); browser.loadUrl("http://joshmcarthur.com"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
<commit_msg>Add raven to the dependancy list.<commit_before>from cms import VERSION from setuptools import setup, find_packages EXCLUDE_FROM_PACKAGES = ['cms.bin'] setup( name="onespacemedia-cms", version=".".join(str(n) for n in VERSION), url="https://github.com/onespacemedia/cms", author="Daniel Samuels", author_email="daniel@onespacemedia.com", license="BSD", packages=find_packages(exclude=EXCLUDE_FROM_PACKAGES), include_package_data=True, scripts=['cms/bin/start_cms_project.py'], zip_safe=False, entry_points={ "console_scripts": [ "start_cms_project.py = cms.bin.start_cms_project:main", ], }, description='CMS used by Onespacemedia', install_requires=[ 'django', 'psycopg2', 'django-suit', 'django-optimizations', 'Pillow', 'django-reversion', 'django-usertools', 'django-historylinks', 'django-watson', 'django-extensions', 'Werkzeug' ], ) <commit_after>from cms import VERSION from setuptools import setup, find_packages EXCLUDE_FROM_PACKAGES = ['cms.bin'] setup( name="onespacemedia-cms", version=".".join(str(n) for n in VERSION), url="https://github.com/onespacemedia/cms", author="Daniel Samuels", author_email="daniel@onespacemedia.com", license="BSD", packages=find_packages(exclude=EXCLUDE_FROM_PACKAGES), include_package_data=True, scripts=['cms/bin/start_cms_project.py'], zip_safe=False, entry_points={ "console_scripts": [ "start_cms_project.py = cms.bin.start_cms_project:main", ], }, description='CMS used by Onespacemedia', install_requires=[ 'django', 'psycopg2', 'django-suit', 'django-optimizations', 'Pillow', 'django-reversion', 'django-usertools', 'django-historylinks', 'django-watson', 'django-extensions', 'Werkzeug', 'raven' ], )
<commit_msg>Remove unnecessary full class qualification <commit_before>package org.codeswarm.lipsum; import org.stringtemplate.v4.ST; import org.stringtemplate.v4.STGroup; /** * A {@link org.codeswarm.lipsum.Lipsum.ParagraphGenerator} implementation backed by an {@link STGroup}. */ class STGroupParagraphGenerator implements Lipsum.ParagraphGenerator { interface TemplateNames { int getMinIndex(); int getMaxIndex(); String getTemplateName(int index); } private final STGroup stg; private final TemplateNames templateNames; STGroupParagraphGenerator(STGroup stg, TemplateNames templateNames) { this.stg = stg; this.templateNames = templateNames; } @Override public String paragraph(long key) { int index = templateNames.getMinIndex() + Lipsum.remainder( Math.abs(key - templateNames.getMinIndex()), templateNames.getMaxIndex()); String tplName = templateNames.getTemplateName(index); ST tpl = stg.getInstanceOf(tplName); return tpl.render(); } } <commit_after>package org.codeswarm.lipsum; import org.stringtemplate.v4.ST; import org.stringtemplate.v4.STGroup; /** * A {@link Lipsum.ParagraphGenerator} implementation backed by an {@link STGroup}. */ class STGroupParagraphGenerator implements Lipsum.ParagraphGenerator { interface TemplateNames { int getMinIndex(); int getMaxIndex(); String getTemplateName(int index); } private final STGroup stg; private final TemplateNames templateNames; STGroupParagraphGenerator(STGroup stg, TemplateNames templateNames) { this.stg = stg; this.templateNames = templateNames; } @Override public String paragraph(long key) { int index = templateNames.getMinIndex() + Lipsum.remainder( Math.abs(key - templateNames.getMinIndex()), templateNames.getMaxIndex()); String tplName = templateNames.getTemplateName(index); ST tpl = stg.getInstanceOf(tplName); return tpl.render(); } }
<commit_msg>Enable interrupts before initializing GDT <commit_before> void entry(void) { pic_remap(IRQ0, IRQ8); pic_set_masks(0, 0); idt_init((struct IDT *)(0x500)); gdt_init((struct GDT *)(0x500 + sizeof(struct IDT))); __asm__ __volatile__ ("sti"); screen_init(); __asm__ __volatile__ ("int $0x50"); for(;;) { __asm__ __volatile__ ("hlt"); } } <commit_after> void entry(void) { struct IDT *idt = (struct IDT *)0x500; struct GDT *gdt = (struct GDT *)(0x500 + sizeof(struct GDT)); pic_remap(IRQ0, IRQ8); pic_set_masks(0, 0); idt_init(idt); __asm__ __volatile__ ("sti"); gdt_init(gdt); screen_init(); __asm__ __volatile__ ("int $0x50"); for(;;) { __asm__ __volatile__ ("hlt"); } }
<commit_msg>Fix an issue with submission selection by just using the index of the selected submission. <commit_before>package edu.pdx.cs410J.grader.poa.ui; import com.google.inject.Singleton; import edu.pdx.cs410J.grader.poa.POASubmissionsView; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import java.awt.*; import java.util.List; import java.util.Vector; @Singleton public class POASubmissionsPanel extends JPanel implements POASubmissionsView { private final JList<String> submissions; public POASubmissionsPanel() { submissions = new JList<>(); submissions.setVisibleRowCount(10); this.setLayout(new BorderLayout()); this.add(new JScrollPane(submissions), BorderLayout.CENTER); this.add(new JLabel("Hello??"), BorderLayout.SOUTH); } @Override public void setPOASubmissionsDescriptions(List<String> strings) { submissions.setListData(new Vector<>(strings)); } @Override public void addSubmissionSelectedListener(POASubmissionSelectedListener listener) { submissions.addListSelectionListener(e -> { if (isFinalEventInUserSelection(e)) { listener.submissionSelected(e.getFirstIndex()); } }); } private boolean isFinalEventInUserSelection(ListSelectionEvent e) { return !e.getValueIsAdjusting(); } } <commit_after>package edu.pdx.cs410J.grader.poa.ui; import com.google.inject.Singleton; import edu.pdx.cs410J.grader.poa.POASubmissionsView; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import java.awt.*; import java.util.List; import java.util.Vector; @Singleton public class POASubmissionsPanel extends JPanel implements POASubmissionsView { private final JList<String> submissions; public POASubmissionsPanel() { submissions = new JList<>(); submissions.setVisibleRowCount(10); this.setLayout(new BorderLayout()); this.add(new JScrollPane(submissions), BorderLayout.CENTER); this.add(new JLabel("Hello??"), BorderLayout.SOUTH); } @Override public void setPOASubmissionsDescriptions(List<String> strings) { submissions.setListData(new Vector<>(strings)); } @Override public void addSubmissionSelectedListener(POASubmissionSelectedListener listener) { submissions.addListSelectionListener(e -> { if (isFinalEventInUserSelection(e)) { listener.submissionSelected(submissions.getSelectedIndex()); } }); } private boolean isFinalEventInUserSelection(ListSelectionEvent e) { return !e.getValueIsAdjusting(); } }
<commit_msg>tests: Rewrite test to check intent instead of implementation. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@107024 91177308-0d34-0410-b5e6-96231b3b80d8 <commit_before>// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -emit-llvm -o - %s | FileCheck %s // PR7490 int main() { // CHECK: {{for.cond:|:4}} // CHECK: %{{.*}} = icmp ult i64 %{{.*}}, 1133 // CHECK: {{for.body:|:6}} // CHECK: store i8 0 // CHECK: br label %{{for.inc|7}} // CHECK: {{for.inc:|:7}} // CHECK: %{{.*}} = add i64 %{{.*}}, 1 // CHECK: store i64 %{{.*}} // CHECK: br label %{{for.cond|4}} // CHECK: {{for.end:|:12}} volatile char *buckets = new char[1133](); } <commit_after>// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -O3 -emit-llvm -o - %s | FileCheck %s // PR7490 // CHECK: define signext i8 @_Z2f0v // CHECK: ret i8 0 // CHECK: } inline void* operator new[](unsigned long, void* __p) { return __p; } static void f0_a(char *a) { new (a) char[4](); } char f0() { char a[4]; f0_a(a); return a[0] + a[1] + a[2] + a[3]; }
<commit_msg>Include <stdint.h> for MS Visual Studio 2010 and above <commit_before> //#if defined(_MSC_VER) && (_MSC_VER <= 1600) // sufficient #if defined(_MSC_VER) // better? typedef unsigned __int32 uint32_t; #elif defined(__linux__) || defined(__GLIBC__) || defined(__WIN32__) || defined(__APPLE__) #include <stdint.h> #elif defined(__osf__) #include <inttypes.h> #else #include <sys/types.h> #endif enum { N = 624, M = 397 }; struct mt { uint32_t mt[N]; int mti; uint32_t seed; }; struct mt *mt_init(void); void mt_free(struct mt *self); uint32_t mt_get_seed(struct mt *self); void mt_init_seed(struct mt *self, uint32_t seed); void mt_setup_array(struct mt *self, uint32_t *array, int n); double mt_genrand(struct mt *self); #endif <commit_after>typedef unsigned __int32 uint32_t; #elif defined(__linux__) || defined(__GLIBC__) || defined(__WIN32__) || defined(_MSC_VER) || defined(__APPLE__) #include <stdint.h> #elif defined(__osf__) #include <inttypes.h> #else #include <sys/types.h> #endif enum { N = 624, M = 397 }; struct mt { uint32_t mt[N]; int mti; uint32_t seed; }; struct mt *mt_init(void); void mt_free(struct mt *self); uint32_t mt_get_seed(struct mt *self); void mt_init_seed(struct mt *self, uint32_t seed); void mt_setup_array(struct mt *self, uint32_t *array, int n); double mt_genrand(struct mt *self); #endif
<commit_msg>Adjust test for concurrent environment <commit_before>package com.edulify.modules.geolocation; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import static org.mockito.Mockito.*; /** * @deprecated Deprecated as of 2.2.0. Source should be removed. */ @Deprecated public class GeolocationServiceTest { @Test public void shouldGetAGeolocationForAGivenIp() throws Exception { final GeolocationProvider provider = mock(GeolocationProvider.class); String ipAddress = "192.30.252.129"; String countryCode = "BR"; final Geolocation geolocation = new Geolocation(ipAddress, countryCode); when(provider.get(ipAddress)).thenReturn(CompletableFuture.completedFuture(geolocation)); final GeolocationCache cache = mock(GeolocationCache.class); GeolocationService service = new GeolocationService(provider, cache); Geolocation target = service.getGeolocation(ipAddress).toCompletableFuture().get(1, TimeUnit.SECONDS); verify(cache).set(geolocation); Assert.assertSame(target, geolocation); } } <commit_after>package com.edulify.modules.geolocation; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import static org.mockito.Mockito.*; /** * @deprecated Deprecated as of 2.2.0. Source should be removed. */ @Deprecated public class GeolocationServiceTest { @Test public void shouldGetAGeolocationForAGivenIp() throws Exception { final GeolocationProvider provider = mock(GeolocationProvider.class); String ipAddress = "192.30.252.129"; String countryCode = "BR"; final Geolocation geolocation = new Geolocation(ipAddress, countryCode); when(provider.get(ipAddress)).thenReturn(CompletableFuture.completedFuture(geolocation)); final GeolocationCache cache = mock(GeolocationCache.class); GeolocationService service = new GeolocationService(provider, cache); Geolocation target = service.getGeolocation(ipAddress).toCompletableFuture().get(1, TimeUnit.SECONDS); verify(cache, timeout(100).times(1)).set(geolocation); Assert.assertSame(target, geolocation); } }
<commit_msg>Increase and fuzz sleep time <commit_before>from listing import Listing, session from scraper import Scraper from slack import Slack import sys import traceback import time slack = Slack() def scrape(): results = 0 duplicates = 0 for result in Scraper().results(): results += 1 listing = Listing(result).process() if listing is None: duplicates += 1 continue session.add(listing) session.commit() if listing.transit_stop is None: continue post = ( ':house: {0} :moneybag: ${1} :round_pushpin: {2} :station: {3} ' ':link: <{4}>' .format(listing.name, listing.price, listing.area, listing.transit_stop, listing.link) ) slack.post(post) print("%s: processed %s listings, %s were duplicates." % (time.ctime(), results, duplicates) ) if __name__ == '__main__': while True: try: scrape() except KeyboardInterrupt: sys.exit(0) except Exception as e: print("Error:", sys.exc_info()[0]) traceback.print_exc() time.sleep(3600) <commit_after>from listing import Listing, session from scraper import Scraper from slack import Slack from random import randint import sys import traceback import time slack = Slack() def scrape(): results = 0 duplicates = 0 for result in Scraper().results(): results += 1 listing = Listing(result).process() if listing is None: duplicates += 1 continue session.add(listing) session.commit() if listing.transit_stop is None: continue post = ( ':house: {0} :moneybag: ${1} :round_pushpin: {2} :station: {3} ' ':link: <{4}>' .format(listing.name, listing.price, listing.area, listing.transit_stop, listing.link) ) slack.post(post) print("%s: processed %s listings, %s were duplicates." % (time.ctime(), results, duplicates) ) if __name__ == '__main__': while True: try: scrape() except KeyboardInterrupt: sys.exit(0) except Exception as e: print("Error:", sys.exc_info()[0]) traceback.print_exc() time.sleep(14400 + randint(-600, 600))
<commit_msg>Add support for retrieving a Checkout Session <commit_before>from __future__ import absolute_import, division, print_function import stripe TEST_RESOURCE_ID = "loc_123" class TestSession(object): def test_is_creatable(self, request_mock): resource = stripe.checkout.Session.create( cancel_url="https://stripe.com/cancel", client_reference_id="1234", line_items=[ { "amount": 123, "currency": "usd", "description": "item 1", "images": ["https://stripe.com/img1"], "name": "name", "quantity": 2, } ], payment_intent_data={"receipt_email": "test@stripe.com"}, payment_method_types=["card"], success_url="https://stripe.com/success", ) request_mock.assert_requested("post", "/v1/checkout/sessions") assert isinstance(resource, stripe.checkout.Session) <commit_after>from __future__ import absolute_import, division, print_function import stripe TEST_RESOURCE_ID = "cs_123" class TestSession(object): def test_is_creatable(self, request_mock): resource = stripe.checkout.Session.create( cancel_url="https://stripe.com/cancel", client_reference_id="1234", line_items=[ { "amount": 123, "currency": "usd", "description": "item 1", "images": ["https://stripe.com/img1"], "name": "name", "quantity": 2, } ], payment_intent_data={"receipt_email": "test@stripe.com"}, payment_method_types=["card"], success_url="https://stripe.com/success", ) request_mock.assert_requested("post", "/v1/checkout/sessions") assert isinstance(resource, stripe.checkout.Session) def test_is_retrievable(self, request_mock): resource = stripe.checkout.Session.retrieve(TEST_RESOURCE_ID) request_mock.assert_requested( "get", "/v1/checkout/sessions/%s" % TEST_RESOURCE_ID ) assert isinstance(resource, stripe.checkout.Session)
<commit_msg>[FIX] Rename save method for database to a more descriptive name <commit_before>import logging from app import db logger = logging.getLogger(__name__) def save_data(data): try: db.session.add(data) db.session.commit() except Exception as err: logger.error(err) <commit_after>import logging from app import db logger = logging.getLogger(__name__) def save_record(record): try: db.session.add(record) db.session.commit() except Exception as err: logger.error(err) def delete_record(record): try: db.session.delete(record) db.session.commit() except Exception as err: logger.error(err)
<commit_msg>Fix the bad jobboard path. Change-Id: I3281babfa835d7d4b76f7f299887959fa5342e85 <commit_before> from taskflow.jobs import backends as job_backends from taskflow.persistence import backends as persistence_backends # Default host/port of ZooKeeper service. ZK_HOST = '104.197.150.171:2181' # Default jobboard configuration. JB_CONF = { 'hosts': ZK_HOST, 'board': 'zookeeper', 'path': '/taskflow/99-bottles-demo', } # Default persistence configuration. PERSISTENCE_CONF = { 'connection': 'zookeeper', 'hosts': ZK_HOST, 'path': '/taskflow/persistence', } def default_persistence_backend(): return persistence_backends.fetch(PERSISTENCE_CONF) def default_jobboard_backend(name): return job_backends.fetch(name, JB_CONF, persistence=default_persistence_backend()) <commit_after> from taskflow.jobs import backends as job_backends from taskflow.persistence import backends as persistence_backends # Default host/port of ZooKeeper service. ZK_HOST = '104.197.150.171:2181' # Default jobboard configuration. JB_CONF = { 'hosts': ZK_HOST, 'board': 'zookeeper', 'path': '/taskflow/dev', } # Default persistence configuration. PERSISTENCE_CONF = { 'connection': 'zookeeper', 'hosts': ZK_HOST, 'path': '/taskflow/persistence', } def default_persistence_backend(): return persistence_backends.fetch(PERSISTENCE_CONF) def default_jobboard_backend(name): return job_backends.fetch(name, JB_CONF, persistence=default_persistence_backend())
<commit_msg>Fix near-zero plot values handling. <commit_before>package common import ( "encoding/json" "math" ) // PlotValue represents a graph plot value. type PlotValue float64 // MarshalJSON handles JSON marshaling of the PlotValue type. func (value PlotValue) MarshalJSON() ([]byte, error) { if math.IsNaN(float64(value)) || math.Floor(float64(value)) == 0 { return json.Marshal(nil) } return json.Marshal(float64(value)) } <commit_after>package common import ( "encoding/json" "math" ) // PlotValue represents a graph plot value. type PlotValue float64 // MarshalJSON handles JSON marshaling of the PlotValue type. func (value PlotValue) MarshalJSON() ([]byte, error) { // Make NaN and very small values null if math.IsNaN(float64(value)) || math.Exp(float64(value)) == 1 { return json.Marshal(nil) } return json.Marshal(float64(value)) }
<commit_msg>Implement BacktraceFormatter for Win32 (NOT tested) <commit_before> namespace lms { namespace extra { void BacktraceFormatter::print(){ std::cerr << "BacktraceFormatter::print not implemented on Win32" << std::endl; } } // namespace extra } // namespace lms <commit_after> namespace lms { namespace extra { void printStacktrace() { // http://stackoverflow.com/questions/5693192/win32-backtrace-from-c-code // https://msdn.microsoft.com/en-us/library/windows/desktop/bb204633(v=vs.85).aspx unsigned int i; void * stack[ 100 ]; unsigned short frames; SYMBOL_INFO * symbol; HANDLE process; process = GetCurrentProcess(); SymInitialize( process, NULL, TRUE ); frames = CaptureStackBackTrace( 0, 100, stack, NULL ); symbol = ( SYMBOL_INFO * )calloc( sizeof( SYMBOL_INFO ) + 256 * sizeof( char ), 1 ); symbol->MaxNameLen = 255; symbol->SizeOfStruct = sizeof( SYMBOL_INFO ); printf("\nStacktrace\n"); for( i = 0; i < frames; i++ ) { SymFromAddr( process, ( DWORD64 )( stack[ i ] ), 0, symbol ); printf( "%i: %s - 0x%0X\n", frames - i - 1, symbol->Name, symbol->Address ); } free( symbol ); } } // namespace extra } // namespace lms
<commit_msg>Add functions to set fields in the node class <commit_before>{-# LANGUAGE JavaScriptFFI #-} module Famous.Core.Node where import GHCJS.Foreign import GHCJS.Types data Node_ a type Node a = JSRef (Node_ a) <commit_after>{-# LANGUAGE JavaScriptFFI #-} module Famous.Core.Node where import GHCJS.Foreign import GHCJS.Types data Node_ a type Node a = JSRef (Node_ a) -- | APIs for a Node object -- | show a node foreign import javascript unsafe "($1).show()" fms_showNode :: Node a -> IO () showNode = fms_showNode -- | hide a node foreign import javascript unsafe "($1).hide()" fms_hideNode :: Node a -> IO () hideNode = fms_hideNode -- | add a child node foreign import javascript unsafe "($2).addChild($1)" fms_addChild :: Node a -> Node b -> IO () addChild = fms_addChild -- | remove a child node foreign import javascript unsafe "($2).removeChild($1)" fms_removeChild :: Node a -> Node b -> IO () removeChild = fms_removeChild -- | set the align value of a node foreign import javascript unsafe "($4).setAlign($1, $2, $3)" fms_setAlign :: Int -> Int -> Int -> Node a -> IO () setAlign = fms_setAlign -- | Sets the mount point value of the node. Will call onMountPointChange on all of the node's components. foreign import javascript unsafe "($4).setMountPoint($1, $2, $3)" fms_setMountPoint :: Int -> Int -> Int -> Node a -> IO () setMountPoint = fms_setMountPoint -- | Sets the origin value of the node. Will call onOriginChange on all of the node's components. foreign import javascript unsafe "($4).setOrigin($1, $2, $3)" fms_setOrigin :: Int -> Int -> Int -> Node a -> IO () setOrigin = fms_setOrigin -- | Sets the position of the node. Will call onPositionChange on all of the node's components. foreign import javascript unsafe "($4).setPosition($1, $2, $3)" fms_setPosition :: Int -> Int -> Int -> Node a -> IO () setPosition = fms_setPosition -- | Sets the scale of the node. The default value is 1 in all dimensions. -- The node's components will have onScaleChanged called on them. foreign import javascript unsafe "($4).setScale($1, $2, $3)" fms_setScale :: Double -> Double -> Double -> Node a -> IO () setScale = fms_setScale -- | Sets the value of the opacity of this node. All of the node's components will have -- onOpacityChange called on them foreign import javascript unsafe "($2).setOpacity($1)" fms_setOpacity :: Double -> Node a -> IO () setOpacity = fms_setOpacity
<commit_msg>Refactor the initialization a bit to make configuration easier. <commit_before>import json import requests class TemperatureWatch(object): thermostat_url = None alert_high = 80 alert_low = 60 _last_response = None def get_info(self): r = requests.get(self.thermostat_url + '/tstat') self._last_response = json.loads(r.text) return r.text def check_temp(self): if not self._last_response: self.get_info() if self._last_response['temp'] > self.alert_high: self.alert('Temperature max of %s exceeded. Currently %s' % (self.alert_high, self._last_response['temp'])) if self._last_response['temp'] < self.alert_low: self.alert('Temperature min of %s exceeded. Currently %s' % (self.alert_low, self._last_response['temp'])) def alert(self, message): print(message) if __name__ == '__main__': tw = TemperatureWatch() tw.thermostat_url = 'http://10.0.1.52' tw.check_temp() <commit_after>import json import requests class TemperatureWatch(object): thermostat_url = None alert_high = 80 alert_low = 60 _last_response = None def get_info(self): r = requests.get(self.thermostat_url + '/tstat') self._last_response = json.loads(r.text) return r.text def check_temp(self): if not self._last_response: self.get_info() if self._last_response['temp'] > self.alert_high: self.alert('Temperature max of %s exceeded. Currently %s' % (self.alert_high, self._last_response['temp'])) if self._last_response['temp'] < self.alert_low: self.alert('Temperature min of %s exceeded. Currently %s' % (self.alert_low, self._last_response['temp'])) def alert(self, message): print(message) if __name__ == '__main__': thermostat_ip = '10.0.1.53' # simple configuration - set the IP, nothing else. Print the alerts when they occur to stdout. Not very useful though... tw = TemperatureWatch() tw.thermostat_url = 'http://%s' % thermostat_ip tw.check_temp()
<commit_msg>Create the Account Detail Page - Part II > Edit Account - Create URL Conf <commit_before>from django.conf.urls import patterns, url account_urls = patterns('', url(r'^$', 'crmapp.accounts.views.account_detail', name='account_detail' ), ) <commit_after>from django.conf.urls import patterns, url account_urls = patterns('', url(r'^$', 'crmapp.accounts.views.account_detail', name='account_detail' ), url(r'^edit/$', 'crmapp.accounts.views.account_cru', name='account_update' ), )
<commit_msg>Add mode for querying multiple times <commit_before>{-# LANGUAGE DeriveDataTypeable, RecordWildCards #-} module Main where import Data.Aeson import System.Console.CmdArgs.Implicit import qualified Data.ByteString.Lazy.Char8 as B import StratumClient data Args = Args { server :: String , port :: Int , command :: String , params :: [String] } deriving (Show, Data, Typeable) synopsis = Args { server = "electrum.bittiraha.fi" &= help "Electrum server address (default: electrum.bittiraha.fi)" , port = 50001 &= help "Electrum port (default: 50001)" , command = def &= argPos 0 &= typ "COMMAND" , params = def &= args &= typ "PARAMS" } &= program "stratumtool" &= summary "StratumTool v0.0.1" &= help ("Connect to Electrum server via Stratum protocol and " ++ "allows querying wallet balances etc.") main = do Args{..} <- cmdArgs synopsis stratumConn <- connectStratum server $ fromIntegral port ans <- queryStratum stratumConn command params B.putStrLn $ encode (ans::Value) <commit_after>{-# LANGUAGE DeriveDataTypeable, RecordWildCards #-} module Main where import Control.Applicative import Data.Aeson import System.Console.CmdArgs.Implicit import qualified Data.ByteString.Lazy.Char8 as B import StratumClient data Args = Args { server :: String , port :: Int , command :: String , params :: [String] , multi :: Bool } deriving (Show, Data, Typeable) synopsis = Args { server = "electrum.bittiraha.fi" &= help "Electrum server address (default: electrum.bittiraha.fi)" , port = 50001 &= help "Electrum port (default: 50001)" , command = def &= argPos 0 &= typ "COMMAND" , params = def &= args &= typ "PARAMS" , multi = def &= help "Instead of passing multiple parameters for \ \a single command, repeat command for each \ \argument (default: false)" } &= program "stratumtool" &= summary "StratumTool v0.0.1" &= help ("Connect to Electrum server via Stratum protocol and " ++ "allows querying wallet balances etc.") main = do Args{..} <- cmdArgs synopsis stratumConn <- connectStratum server $ fromIntegral port ans <- if multi then toJSON <$> mapM (queryStratumValue stratumConn command . pure) params else queryStratumValue stratumConn command params B.putStrLn $ encode ans
<commit_msg>Remove .ds_store.. not sure why it was there <commit_before>let assert = require('assert'); import projectCatalogService = require('../../services/project-catalog-service'); describe('GetProjectrs', function() { describe('#indexOf()', function() { it('should return -1 when the value is not present', function() { assert.equal(-1, [1,2,3].indexOf(4)); }); }); });<commit_after>let assert = require('assert'); import projectCatalogService = require('../../services/project-catalog-service'); describe('ProjectCatalogTest', function() { describe('#indexOf()', function() { it('should return -1 when the value is not present', function() { assert.equal(-1, [1,2,3].indexOf(4)); }); }); });
<commit_msg>Fix compile errors on Linux <commit_before> namespace Reg { namespace Internal { boost::optional<FilterModeTranslator::external_type> FilterModeTranslator::get_value(internal_type const sval) { if (sval.empty()) return boost::none; if (sval == "Bilinear") { return Filter::Mode::Bilinear; } if (sval == "Nearest") { return Filter::Mode::NearestNeighbor; } if (sval == "Lanczos3") { return Filter::Mode::Lanczos3; } switch (FromAString<int>(sval)) { case 1: return Filter::Mode::NearestNeighbor; case 2: return Filter::Mode::Bilinear; case 3: return Filter::Mode::Lanczos3; } return boost::none; } boost::optional<FilterModeTranslator::internal_type> FilterModeTranslator::put_value(external_type const& val) { switch (val) { case Filter::Mode::NearestNeighbor: return "Nearest"; case Filter::Mode::Bilinear: return "Bilinear"; case Filter::Mode::Lanczos3: return "Lanczos3"; } return boost::none; } } }<commit_after> namespace Reg { namespace Internal { boost::optional<FilterModeTranslator::external_type> FilterModeTranslator::get_value(internal_type const sval) { if (sval.empty()) return boost::none; if (sval == "Bilinear") { return Filter::Mode::Bilinear; } if (sval == "Nearest") { return Filter::Mode::NearestNeighbor; } if (sval == "Lanczos3") { return Filter::Mode::Lanczos3; } switch (FromAString<int>(sval)) { case 1: return Filter::Mode::NearestNeighbor; case 2: return Filter::Mode::Bilinear; case 3: return Filter::Mode::Lanczos3; } return boost::none; } boost::optional<FilterModeTranslator::internal_type> FilterModeTranslator::put_value(external_type const& val) { switch (val) { case Filter::Mode::NearestNeighbor: return std::string("Nearest"); case Filter::Mode::Bilinear: return std::string("Bilinear"); case Filter::Mode::Lanczos3: return std::string("Lanczos3"); } return boost::none; } } }
<commit_msg>Improve station-sensor link field addition to reading model migration using a paging system to prevent the migration being killed automatically. <commit_before>from __future__ import unicode_literals from django.db import migrations # noinspection PyUnusedLocal def add_station_sensor_link_to_reading(apps, schema_editor): # noinspection PyPep8Naming Reading = apps.get_model('climate_data', 'Reading') # noinspection PyPep8Naming StationSensorLink = apps.get_model('climate_data', 'StationSensorLink') for reading in Reading.objects.all(): reading.station_sensor_link = StationSensorLink.objects.filter(station=reading.station, sensor=reading.sensor)\ .first() reading.save() class Migration(migrations.Migration): dependencies = [ ('climate_data', '0023_reading_station_sensor_link'), ] operations = [ migrations.RunPython(add_station_sensor_link_to_reading), ] <commit_after>from __future__ import unicode_literals from django.db import migrations # noinspection PyUnusedLocal def add_station_sensor_link_to_reading(apps, schema_editor): # noinspection PyPep8Naming Reading = apps.get_model('climate_data', 'Reading') # noinspection PyPep8Naming StationSensorLink = apps.get_model('climate_data', 'StationSensorLink') offset = 0 pagesize = 5000 count = Reading.objects.all().count() while offset < count: for reading in Reading.objects.all()[offset:offset+pagesize].iterator(): reading.station_sensor_link = StationSensorLink.objects.filter( station=reading.station, sensor=reading.sensor ).first() reading.save() offset += pagesize class Migration(migrations.Migration): dependencies = [ ('climate_data', '0023_reading_station_sensor_link'), ] operations = [ migrations.RunPython(add_station_sensor_link_to_reading), ]
<commit_msg>Clean up main class and show JSON and XML output<commit_before>package com.codeski.nbt; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; public class Main { public static void main(String[] args) throws FileNotFoundException, IOException { File f = new File(args[0]); System.out.println("Start reading " + f.getAbsolutePath() + "..."); System.out.println(new NBTReader(f).read()); System.out.println("Finished reading " + f.getAbsolutePath() + "..."); } } <commit_after>package com.codeski.nbt; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import com.codeski.nbt.tags.NBTCompound; public class Main { public static void main(String[] args) throws FileNotFoundException, IOException { File f = new File(args[0]); System.out.println("Start reading " + f.getAbsolutePath() + "..."); NBTCompound root = (NBTCompound) new NBTReader(f).read(); System.out.println("Finished reading " + f.getAbsolutePath() + "..."); System.out.println(); System.out.println("{ " + root.toJSON() + " }"); System.out.println(); System.out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + root.toXML()); System.out.println(); System.out.println("Done!"); } }
<commit_msg>Make sure FeatureExtractor returns array2i <commit_before>from typing import List, Union, Callable, Tuple from ..types import Ints2d, Doc from ..model import Model from ..config import registry InT = List[Doc] OutT = List[Ints2d] @registry.layers("FeatureExtractor.v1") def FeatureExtractor(columns: List[Union[int, str]]) -> Model[InT, OutT]: return Model("extract_features", forward, attrs={"columns": columns}) def forward(model: Model[InT, OutT], docs, is_train: bool) -> Tuple[OutT, Callable]: columns = model.attrs["columns"] features: OutT = [] for doc in docs: if hasattr(doc, "to_array"): attrs = doc.to_array(columns) else: attrs = doc.doc.to_array(columns)[doc.start : doc.end] features.append(model.ops.asarray2i(attrs, dtype="uint64")) backprop: Callable[[OutT], List] = lambda d_features: [] return features, backprop <commit_after>from typing import List, Union, Callable, Tuple from ..types import Ints2d, Doc from ..model import Model from ..config import registry InT = List[Doc] OutT = List[Ints2d] @registry.layers("FeatureExtractor.v1") def FeatureExtractor(columns: List[Union[int, str]]) -> Model[InT, OutT]: return Model("extract_features", forward, attrs={"columns": columns}) def forward(model: Model[InT, OutT], docs, is_train: bool) -> Tuple[OutT, Callable]: columns = model.attrs["columns"] features: OutT = [] for doc in docs: if hasattr(doc, "to_array"): attrs = doc.to_array(columns) else: attrs = doc.doc.to_array(columns)[doc.start : doc.end] if attrs.ndim == 1: attrs = attrs.reshape((attrs.shape[0], 1)) features.append(model.ops.asarray2i(attrs, dtype="uint64")) backprop: Callable[[OutT], List] = lambda d_features: [] return features, backprop
<commit_msg>Use dict for dump data format <commit_before> import os import sys from gwv import version from validator import validate def main(args=None): if args is None: args = sys.argv[1:] import argparse parser = argparse.ArgumentParser(description="GlyphWiki data validator") parser.add_argument("dumpfile") parser.add_argument("-o", "--out", help="File to write the output JSON to") parser.add_argument("-n", "--names", nargs="*", help="Names of validators") parser.add_argument("-v", "--version", action="store_true", help="Names of validators") opts = parser.parse_args(args) if opts.version: print(version) return outpath = opts.out or os.path.join(os.path.dirname(opts.dumpfile), "gwv_result.json") dumpfile = open(opts.dumpfile) result = validate(dumpfile, opts.names or None) with open(outpath, "w") as outfile: outfile.write(result) if __name__ == '__main__': main() <commit_after> import os import sys from gwv import version from validator import validate def open_dump(filename): dump = {} with open(filename) as f: if filename[-4:] == ".csv": for l in f: row = l.rstrip("\n").split(",") if len(row) != 3: continue dump[row[0]] = (row[1], row[2]) else: # dump_newest_only.txt line = f.readline() # header line = f.readline() # ------ while line: l = [x.strip() for x in line.split("|")] if len(l) != 3: line = f.readline() continue dump[row[0]] = (row[1], row[2]) line = f.readline() return dump def main(args=None): if args is None: args = sys.argv[1:] import argparse parser = argparse.ArgumentParser(description="GlyphWiki data validator") parser.add_argument("dumpfile") parser.add_argument("-o", "--out", help="File to write the output JSON to") parser.add_argument("-n", "--names", nargs="*", help="Names of validators") parser.add_argument("-v", "--version", action="store_true", help="Names of validators") opts = parser.parse_args(args) if opts.version: print(version) return outpath = opts.out or os.path.join( os.path.dirname(opts.dumpfile), "gwv_result.json") dump = open_dump(opts.dumpfile) result = validate(dump, opts.names or None) with open(outpath, "w") as outfile: outfile.write(result) if __name__ == '__main__': main()
<commit_msg>Make main do something useful `runhaskell Main.hs fib.ja' now outputs the AST for the program. <commit_before> import Jana.Ast import Jana.Parser fib :: Program fib = ( ProcMain [] [] , [ Proc { procname = "fib" , params = [ (Int, "x1"), (Int, "x2"), (Int, "n") ] , body = [ If (BinOp Eq (LV $ Var "n") (Number 0)) [ Assign AddEq (Var "x1") (Number 1) , Assign AddEq (Var "x2") (Number 1) ] [ Call "fib" [ "x1", "x2", "n" ] , Assign AddEq (Var "x1") (LV $ Var "x2") , Swap "x1" "x2" ] (BinOp Eq (LV $ Var "x1") (LV $ Var "x2")) ] } , Proc { procname = "fib_fwd" , params = [ (Int, "x1"), (Int, "x2"), (Int, "n") ] , body = [ Assign AddEq (Var "n") (Number 4) , Call "fib" [ "x1", "x2", "n" ] ] } , Proc { procname = "fib_bwd" , params = [ (Int, "x1"), (Int, "x2"), (Int, "n") ] , body = [ Assign AddEq (Var "x1") (Number 5) , Assign AddEq (Var "x2") (Number 8) , Uncall "fib" [ "x1", "x2", "n" ] ] } ] ) main :: IO () main = print fib <commit_after> import System.Environment import Jana.Parser main :: IO () main = do args <- getArgs case args of [file] -> parseFile (args !! 0) >>= print _ -> putStrLn "usage: jana <file>"
<commit_msg>Print debug-friendly repr of APIAccessCredential <commit_before>from __future__ import print_function from __future__ import unicode_literals from __future__ import division import uuid import base64 import os from django.contrib.gis.db import models from treemap.models import User class APIAccessCredential(models.Model): access_key = models.CharField(max_length=100, null=False, blank=False) secret_key = models.CharField(max_length=256, null=False, blank=False) # If a user is specified then this credential # is always authorized as the given user # # If user is None this credential can access # any user's data if that user's username # and password are also provided user = models.ForeignKey(User, null=True) enabled = models.BooleanField(default=True) @classmethod def create(clz, user=None): secret_key = base64.urlsafe_b64encode(os.urandom(64)) access_key = base64.urlsafe_b64encode(uuid.uuid4().bytes)\ .replace('=', '') return APIAccessCredential.objects.create( user=user, access_key=access_key, secret_key=secret_key) <commit_after>from __future__ import print_function from __future__ import unicode_literals from __future__ import division import uuid import base64 import os from django.contrib.gis.db import models from treemap.models import User class APIAccessCredential(models.Model): access_key = models.CharField(max_length=100, null=False, blank=False) secret_key = models.CharField(max_length=256, null=False, blank=False) # If a user is specified then this credential # is always authorized as the given user # # If user is None this credential can access # any user's data if that user's username # and password are also provided user = models.ForeignKey(User, null=True) enabled = models.BooleanField(default=True) def __unicode__(self): return self.access_key @classmethod def create(clz, user=None): secret_key = base64.urlsafe_b64encode(os.urandom(64)) access_key = base64.urlsafe_b64encode(uuid.uuid4().bytes)\ .replace('=', '') return APIAccessCredential.objects.create( user=user, access_key=access_key, secret_key=secret_key)
<commit_msg>Enable flow control in Greentea Flow control is enabled in Greentea for targets that has console-uart-flow-control set. <commit_before> SingletonPtr<GreenteaSerial> greentea_serial; GreenteaSerial::GreenteaSerial() : mbed::RawSerial(USBTX, USBRX, MBED_CONF_PLATFORM_STDIO_BAUD_RATE) {}; <commit_after> /** * Macros for setting console flow control. */ #define CONSOLE_FLOWCONTROL_RTS 1 #define CONSOLE_FLOWCONTROL_CTS 2 #define CONSOLE_FLOWCONTROL_RTSCTS 3 #define mbed_console_concat_(x) CONSOLE_FLOWCONTROL_##x #define mbed_console_concat(x) mbed_console_concat_(x) #define CONSOLE_FLOWCONTROL mbed_console_concat(MBED_CONF_TARGET_CONSOLE_UART_FLOW_CONTROL) SingletonPtr<GreenteaSerial> greentea_serial; GreenteaSerial::GreenteaSerial() : mbed::RawSerial(USBTX, USBRX, MBED_CONF_PLATFORM_STDIO_BAUD_RATE) { #if CONSOLE_FLOWCONTROL == CONSOLE_FLOWCONTROL_RTS set_flow_control(SerialBase::RTS, STDIO_UART_RTS, NC); #elif CONSOLE_FLOWCONTROL == CONSOLE_FLOWCONTROL_CTS set_flow_control(SerialBase::CTS, NC, STDIO_UART_CTS); #elif CONSOLE_FLOWCONTROL == CONSOLE_FLOWCONTROL_RTSCTS set_flow_control(SerialBase::RTSCTS, STDIO_UART_RTS, STDIO_UART_CTS); #endif }
<commit_msg>Update alembic order for merging <commit_before> # revision identifiers, used by Alembic. revision = '538eeb160af6' down_revision = '1727fb4309d8' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('user', sa.Column('role', sa.String(length=30), nullable=True)) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_column('user', 'role') ### end Alembic commands ### <commit_after> # revision identifiers, used by Alembic. revision = '538eeb160af6' down_revision = '6b9d673d8e30' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('user', sa.Column('role', sa.String(length=30), nullable=True)) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_column('user', 'role') ### end Alembic commands ###
<commit_msg>Use lru_cache instead of a dict cache in FunctionDispatch This has no affect on the microbenchmark, but seems appropriate for consistency with the previous commit. <commit_before>import attr @attr.s(slots=True) class FunctionDispatch(object): """ FunctionDispatch is similar to functools.singledispatch, but instead dispatches based on functions that take the type of the first argument in the method, and return True or False. objects that help determine dispatch should be instantiated objects. """ _handler_pairs = attr.ib(init=False, default=attr.Factory(list)) _cache = attr.ib(init=False, default=attr.Factory(dict)) def register(self, can_handle, func): self._handler_pairs.insert(0, (can_handle, func)) self._cache.clear() def dispatch(self, typ): """ returns the appropriate handler, for the object passed. """ try: return self._cache[typ] except KeyError: self._cache[typ] = self._dispatch(typ) return self._cache[typ] def _dispatch(self, typ): for can_handle, handler in self._handler_pairs: # can handle could raise an exception here # such as issubclass being called on an instance. # it's easier to just ignore that case. try: if can_handle(typ): return handler except Exception: pass raise KeyError("unable to find handler for {0}".format(typ)) <commit_after>from ._compat import lru_cache class FunctionDispatch(object): """ FunctionDispatch is similar to functools.singledispatch, but instead dispatches based on functions that take the type of the first argument in the method, and return True or False. objects that help determine dispatch should be instantiated objects. """ __slots__ = ('_handler_pairs', 'dispatch') def __init__(self): self._handler_pairs = [] self.dispatch = lru_cache(64)(self._dispatch) def register(self, can_handle, func): self._handler_pairs.insert(0, (can_handle, func)) self.dispatch.cache_clear() def _dispatch(self, typ): """ returns the appropriate handler, for the object passed. """ for can_handle, handler in self._handler_pairs: # can handle could raise an exception here # such as issubclass being called on an instance. # it's easier to just ignore that case. try: if can_handle(typ): return handler except Exception: pass raise KeyError("unable to find handler for {0}".format(typ))
<commit_msg>Delete *.pyc files from dials/extensions when doing libtbx.refresh<commit_before>from __future__ import division def run(): from dials.util.config import CompletionGenerator gen = CompletionGenerator() gen.generate() try: run() except Exception, e: pass <commit_after>from __future__ import division def run(): from dials.util.config import CompletionGenerator gen = CompletionGenerator() gen.generate() try: run() except Exception, e: pass try: from glob import glob import os filenames = glob("extensions/*.pyc") if len(filenames) > 0: print "Cleaning up 'dials/extensions':" for filename in glob("extensions/*.pyc"): print " Deleting %s" % filename os.remove(filename) except Exception, e: pass
<commit_msg>Add test for extract listings that asserts each listing is a bs4.element.Tag <commit_before>from scraper import search_CL from scraper import read_search_results def test_search_CL(): test_body, test_encoding = search_CL(minAsk=100) assert "<span class=\"desktop\">craigslist</span>" in test_body assert test_encoding == 'utf-8' def test_read_search_result(): test_body, test_encoding = read_search_results() assert "<span class=\"desktop\">craigslist</span>" in test_body assert test_encoding == 'utf-8' <commit_after>from scraper import search_CL from scraper import read_search_results from scraper import parse_source from scraper import extract_listings import bs4 def test_search_CL(): test_body, test_encoding = search_CL(minAsk=100, maxAsk=100) assert "<span class=\"desktop\">craigslist</span>" in test_body assert test_encoding == 'utf-8' def test_read_search_result(): test_body, test_encoding = read_search_results() assert "<span class=\"desktop\">craigslist</span>" in test_body assert test_encoding == 'utf-8' def test_parse_source(): test_body, test_encoding = read_search_results() test_parse = parse_source(test_body, test_encoding) assert isinstance(test_parse, bs4.BeautifulSoup) def test_extract_listings(): test_body, test_encoding = read_search_results() test_parse = parse_source(test_body, test_encoding) for row in extract_listings(test_parse): print type(row) assert isinstance(row, bs4.element.Tag)
<commit_msg>Test fail not to deploy <commit_before>from django.test import TestCase from django.urls import reverse from .models import Post # Create your tests here. class PostModelTest(TestCase): def test_render_markdown(self): p = Post(content='aa') self.assertEqual(p.html_content, '<p>aa</p>\n') class PostViewTest(TestCase): def test_post_view(self): p = Post( slug='first-blog', title='First blog', content='I am hhb', ) p.save() url = reverse('blog:post', args=(p.slug,)) resp = self.client.get(url) self.assertContains(resp, 'I am hhb') <commit_after>from django.test import TestCase from django.urls import reverse from .models import Post # Create your tests here. class PostModelTest(TestCase): def test_render_markdown(self): p = Post(content='aa') self.assertEqual(p.html_content, '<p>aa</p>\n') class PostViewTest(TestCase): def test_post_view(self): p = Post( slug='first-blog', title='First blog', content='I am hhb', ) p.save() url = reverse('blog:post', args=(p.slug,)) resp = self.client.get(url) self.assertContains(resp, 'I am hhb, i will fail')
<commit_msg>Improve handling negative test expression (reuse the positive expression).<commit_before>/******************************************************************************* * This file is part of Pebble. * * Copyright (c) 2014 by Mitchell Bösecke * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ******************************************************************************/ package com.mitchellbosecke.pebble.node.expression; import java.util.Map; import com.mitchellbosecke.pebble.error.PebbleException; import com.mitchellbosecke.pebble.extension.LocaleAware; import com.mitchellbosecke.pebble.extension.Test; import com.mitchellbosecke.pebble.node.ArgumentsNode; import com.mitchellbosecke.pebble.node.TestInvocationExpression; import com.mitchellbosecke.pebble.template.EvaluationContext; import com.mitchellbosecke.pebble.template.PebbleTemplateImpl; public class NegativeTestExpression extends BinaryExpression<Object> { @Override public Object evaluate(PebbleTemplateImpl self, EvaluationContext context) throws PebbleException { TestInvocationExpression testInvocation = (TestInvocationExpression) getRightExpression(); ArgumentsNode args = testInvocation.getArgs(); String testName = testInvocation.getTestName(); Map<String, Test> tests = context.getTests(); Test test = tests.get(testInvocation.getTestName()); if (test == null) { throw new PebbleException(null, String.format("Test [%s] does not exist.", testName)); } if (test instanceof LocaleAware) { ((LocaleAware) test).setLocale(context.getLocale()); } Map<String, Object> namedArguments = args.getArgumentMap(self, context, test); return !test.apply(getLeftExpression().evaluate(self, context), namedArguments); } } <commit_after>/******************************************************************************* * This file is part of Pebble. * * Copyright (c) 2014 by Mitchell Bösecke * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ******************************************************************************/ package com.mitchellbosecke.pebble.node.expression; import com.mitchellbosecke.pebble.error.PebbleException; import com.mitchellbosecke.pebble.template.EvaluationContext; import com.mitchellbosecke.pebble.template.PebbleTemplateImpl; public class NegativeTestExpression extends PositiveTestExpression { @Override public Object evaluate(PebbleTemplateImpl self, EvaluationContext context) throws PebbleException { return !((Boolean) super.evaluate(self, context)); } }
<commit_msg>Modify Clear Command success message <commit_before>package seedu.address.logic.commands; import seedu.address.model.TaskList; /** * Clears the address book. */ public class ClearCommand extends Command { public static final String COMMAND_WORD = "clear"; public static final String MESSAGE_SUCCESS = "Address book has been cleared!"; public ClearCommand() {} @Override public CommandResult execute() { assert model != null; model.resetData(TaskList.getEmptyAddressBook()); return new CommandResult(MESSAGE_SUCCESS); } } <commit_after>package seedu.address.logic.commands; import seedu.address.model.TaskList; /** * Clears the address book. */ public class ClearCommand extends Command { public static final String COMMAND_WORD = "clear"; public static final String MESSAGE_SUCCESS = "Your to-do list has been cleared!"; public ClearCommand() {} @Override public CommandResult execute() { assert model != null; model.resetData(TaskList.getEmptyAddressBook()); return new CommandResult(MESSAGE_SUCCESS); } }
<commit_msg>CONFIG: Correct development URL to use port 3000 for api <commit_before>let API_URL: string; API_URL = "http://localhost:3000/api"; export default API_URL; <commit_after>let API_URL: string; API_URL = `${window.location.protocol}//${window.location.hostname}:3000/api`; export default API_URL;
<commit_msg>Add very basic testing for Coap request. <commit_before>from ..code_registry import MethodCode, MessageType from ..coap import Coap def test_build_message(): c = Coap('coap.me') result = c.get('hello') print str(bytearray(result.server_reply_list[0].payload)) c.destroy() <commit_after>from ..code_registry import MethodCode, MessageType from ..coap import Coap import binascii def test_build_message(): c = Coap('coap.me') result1 = c.get('hello') assert str(bytearray(result1.server_reply_list[0].payload)) == '\xffworld' result2 = c.get('separate') assert str(bytearray(result2.server_reply_list[0].payload)) == '\xffThat took a long time' c.destroy()
<commit_msg>Add POSIX as supported OS type <commit_before>from setuptools import setup def read(f): try: with open(f) as file: return file.read() except: return "" setup(name='shellvars-py', version='0.1.2', description='Read environment variables defined in a shell script into Python.', author_email='aneil.mallavar@gmail.com', license='Apache2', py_modules=['shellvars'], long_description = read('README.md'), url="http://github.com/aneilbaboo/shellvars-py", author="Aneil Mallavarapu", include_package_data = True, classifiers = [ 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: Apache Software License', 'Operating System :: MacOS :: MacOS X', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) <commit_after>from setuptools import setup def read(f): try: with open(f) as file: return file.read() except: return "" setup(name='shellvars-py', version='0.1.2', description='Read environment variables defined in a shell script into Python.', author_email='aneil.mallavar@gmail.com', license='Apache2', py_modules=['shellvars'], long_description = read('README.md'), url="http://github.com/aneilbaboo/shellvars-py", author="Aneil Mallavarapu", include_package_data = True, classifiers = [ 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: Apache Software License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
<commit_msg>Add emit for variable declaration <commit_before>import { FunctionLikeDeclaration, Identifier, TypeReferenceNode } from 'typescript'; import { Context } from '../contexts'; import { EmitResult, emit } from './'; const emitFunctionDeclaration = (node: FunctionLikeDeclaration, context: Context): string => { const return_type = emit(node.type, context).emitted_string; const function_name = emit(node.name, context).emitted_string; const parameters = node.parameters .map(p => ({ name: emit(p.name, context).emitted_string, type: emit(p.type, context).emitted_string})) .map(({ name, type }) => `${type} ${name}`) .join(', '); const body = emit(node.body, context).emitted_string; const declaration = `${return_type} ${function_name}(${parameters}) ${body}`; return declaration; }; export const emitFunctionLikeDeclaration = (node: FunctionLikeDeclaration, context: Context): EmitResult => { return { context, emitted_string: emitFunctionDeclaration(node, context) }; } <commit_after>import { FunctionLikeDeclaration, Identifier, TypeReferenceNode, VariableDeclaration } from 'typescript'; import { Context } from '../contexts'; import { EmitResult, emit, emitString } from './'; const emitFunctionDeclaration = (node: FunctionLikeDeclaration, context: Context): string => { const return_type = emit(node.type, context).emitted_string; const function_name = emit(node.name, context).emitted_string; const parameters = node.parameters .map(p => ({ name: emit(p.name, context).emitted_string, type: emit(p.type, context).emitted_string})) .map(({ name, type }) => `${type} ${name}`) .join(', '); const body = emit(node.body, context).emitted_string; const declaration = `${return_type} ${function_name}(${parameters}) ${body}`; return declaration; }; export const emitFunctionLikeDeclaration = (node: FunctionLikeDeclaration, context: Context): EmitResult => { return { context, emitted_string: emitFunctionDeclaration(node, context) }; } export const emitVariableDeclaration = ({ type, name, initializer }: VariableDeclaration, context: Context): EmitResult => { return { context, emitted_string: `${emitString(type, context)} ${emitString(name, context)} = ${emitString(initializer, context)}` } };
<commit_msg>Fix empty object instead of no body for default audience The ticket seemed to indicate that if there is no audience specified, then the request was to have an empty body. However, that leads to a 500 from the API. Reading the associated plugin show that an empty object is expected in that case. <commit_before>package api import ( "errors" "fmt" ) var ErrAudienceTooLong = errors.New("the API only supports at most one element in the audience") type OidcToken struct { Token string `json:"token"` } func (c *Client) OidcToken(jobId string, audience ...string) (*OidcToken, *Response, error) { type oidcTokenRequest struct { Audience string `json:"audience"` } var m *oidcTokenRequest switch len(audience) { case 0: m = nil case 1: m = &oidcTokenRequest{Audience: audience[0]} default: // While the spec supports multiple audiences in an Id JWT, our API does // not support issuing them. // See: https://openid.net/specs/openid-connect-core-1_0.html#IDToken. return nil, nil, ErrAudienceTooLong } u := fmt.Sprintf("jobs/%s/oidc/tokens", jobId) req, err := c.newRequest("POST", u, m) if err != nil { return nil, nil, err } t := &OidcToken{} resp, err := c.doRequest(req, t) return t, resp, err } <commit_after>package api import ( "errors" "fmt" ) var ErrAudienceTooLong = errors.New("the API only supports at most one element in the audience") type OidcToken struct { Token string `json:"token"` } func (c *Client) OidcToken(jobId string, audience ...string) (*OidcToken, *Response, error) { type oidcTokenRequest struct { Audience string `json:"audience,omitempty"` } m := &oidcTokenRequest{} switch len(audience) { case 0: case 1: m.Audience = audience[0] default: // While the spec supports multiple audiences in an Id JWT, our API does // not support issuing them. // See: https://openid.net/specs/openid-connect-core-1_0.html#IDToken. return nil, nil, ErrAudienceTooLong } u := fmt.Sprintf("jobs/%s/oidc/tokens", jobId) req, err := c.newRequest("POST", u, m) if err != nil { return nil, nil, err } t := &OidcToken{} resp, err := c.doRequest(req, t) return t, resp, err }
<commit_msg>Fix passing invalid None to multiprocessing Process class. <commit_before> import multiprocessing from .base import Processor class BackgroundProcessor(Processor): '''Local background processor.''' def process(self, command, args=None, kw=None): '''Process *command* with *args* and *kw*.''' process = multiprocessing.Process(target=command, args=args, kwargs=kw) process.start() process.join() <commit_after> import multiprocessing from .base import Processor class BackgroundProcessor(Processor): '''Local background processor.''' def process(self, command, args=None, kw=None): '''Process *command* with *args* and *kw*.''' if args is None: args = () if kw is None: kw = {} process = multiprocessing.Process(target=command, args=args, kwargs=kw) process.start() process.join()
<commit_msg>Tweak left count text in Footer component <commit_before>import Component from 'inferno-component' import h from 'inferno-hyperscript' interface Props { clearCompleted: () => void clearAll: () => void leftCount: number } interface State {} export default class Footer extends Component<Props, State> { render() { return h('div', [ h('span', `${this.props.leftCount} items left`), h('button', { onClick: this.props.clearCompleted }, 'Clear completed'), h('button', { onClick: this.props.clearAll }, 'Clear lll') ]) } } <commit_after>import Component from 'inferno-component' import h from 'inferno-hyperscript' interface Props { clearCompleted: () => void clearAll: () => void leftCount: number } interface State {} export default class Footer extends Component<Props, State> { leftCountText(count: number): string { if (count === 1) { return `${count} item left` } else { return `${count} items left` } } render() { return h('div', [ h('span', this.leftCountText(this.props.leftCount)), h('button', { onClick: this.props.clearCompleted }, 'Clear completed'), h('button', { onClick: this.props.clearAll }, 'Clear lll') ]) } }
<commit_msg>Remove Nullable annotation to avoid build warning <commit_before>package com.danielflower.apprunner.runners; import com.danielflower.apprunner.Config; import org.apache.commons.exec.CommandLine; import org.apache.maven.shared.invoker.InvocationRequest; import javax.annotation.Nullable; import java.util.Map; public interface HomeProvider extends CommandLineProvider { HomeProvider default_java_home = new HomeProvider() { public InvocationRequest mungeMavenInvocationRequest(InvocationRequest request) { return request; } public CommandLine commandLine(@Nullable Map<String, String> envVarsForApp) { return new CommandLine(Config.javaExecutableName()); } }; InvocationRequest mungeMavenInvocationRequest(InvocationRequest request); } <commit_after>package com.danielflower.apprunner.runners; import com.danielflower.apprunner.Config; import org.apache.commons.exec.CommandLine; import org.apache.maven.shared.invoker.InvocationRequest; import javax.annotation.Nullable; import java.util.Map; public interface HomeProvider extends CommandLineProvider { HomeProvider default_java_home = new HomeProvider() { public InvocationRequest mungeMavenInvocationRequest(InvocationRequest request) { return request; } public CommandLine commandLine(Map<String, String> envVarsForApp) { return new CommandLine(Config.javaExecutableName()); } }; InvocationRequest mungeMavenInvocationRequest(InvocationRequest request); }
<commit_msg>Set an initial size and disallow resizing <commit_before>from gi.repository import Gtk, GdkPixbuf, GLib import cv2 class View(Gtk.Window): def __init__(self, title, camera, interval=200): Gtk.Window.__init__(self) self.set_title(title) self.cam = camera self.img = Gtk.Image() self.add(self.img) GLib.timeout_add(interval, self.update) def update(self): if self.cam.isReady(): frame = cv2.cvtColor(self.cam.getFrame(), cv2.COLOR_BGR2RGB) self.img.set_from_pixbuf(GdkPixbuf.Pixbuf.new_from_data(frame.data, GdkPixbuf.Colorspace.RGB, False, 8, frame.shape[1], frame.shape[0], frame.strides[0], None, None)) else: print('not ready') <commit_after>from gi.repository import Gtk, GdkPixbuf, GLib import cv2 class View(Gtk.Window): def __init__(self, title, camera, interval=200): Gtk.Window.__init__(self) self.set_title(title) self.set_size_request(640, 480) self.set_resizable(False) self.cam = camera self.img = Gtk.Image() self.add(self.img) GLib.timeout_add(interval, self.update) def update(self): if self.cam.isReady(): frame = cv2.cvtColor(self.cam.getFrame(), cv2.COLOR_BGR2RGB) self.img.set_from_pixbuf(GdkPixbuf.Pixbuf.new_from_data(frame.data, GdkPixbuf.Colorspace.RGB, False, 8, frame.shape[1], frame.shape[0], frame.strides[0], None, None)) else: print('not ready')
<commit_msg>Adjust code style to reduce lines of code :bear: <commit_before>import datetime from django.utils.timezone import utc from .models import Ticket class TicketServices(): def edit_ticket_once(self, **kwargs): id_list = kwargs.get('id_list') edit_tags = kwargs.get('edit_tags') edit_requester = kwargs.get('edit_requester') edit_subject = kwargs.get('edit_subject') edit_due_at = kwargs.get('edit_due_at') edit_assignee = kwargs.get('edit_assignee') if edit_tags: Ticket.objects.filter( pk__in=id_list ).update(tags=edit_tags) if edit_subject: Ticket.objects.filter( pk__in=id_list ).update(subject=edit_subject) if edit_requester: Ticket.objects.filter( pk__in=id_list ).update(requester=edit_requester) if edit_due_at: Ticket.objects.filter( pk__in=id_list ).update( due_at=datetime.datetime.strptime( edit_due_at, "%m/%d/%Y" ).replace(tzinfo=utc) ) if edit_assignee: Ticket.objects.filter( pk__in=id_list ).update(assignee=edit_assignee) <commit_after>import datetime from django.utils.timezone import utc from .models import Ticket class TicketServices(): def edit_ticket_once(self, **kwargs): id_list = kwargs.get('id_list') edit_tags = kwargs.get('edit_tags') edit_requester = kwargs.get('edit_requester') edit_subject = kwargs.get('edit_subject') edit_due_at = kwargs.get('edit_due_at') edit_assignee = kwargs.get('edit_assignee') if edit_tags: Ticket.objects.filter(pk__in=id_list).update(tags=edit_tags) if edit_subject: Ticket.objects.filter(pk__in=id_list).update(subject=edit_subject) if edit_requester: Ticket.objects.filter(pk__in=id_list).update( requester=edit_requester ) if edit_due_at: Ticket.objects.filter(pk__in=id_list).update( due_at=datetime.datetime.strptime( edit_due_at, '%m/%d/%Y' ).replace(tzinfo=utc) ) if edit_assignee: Ticket.objects.filter(pk__in=id_list).update( assignee=edit_assignee )
<commit_msg>Add method to extract parameters from command line args. <commit_before>package com.maddenabbott.jenny; /** * The main entry point for Jenny. */ public class Application { private static final String defaultCommand = "help"; public static void main(String[] args) { String commandName = getCommandName(args, defaultCommand); } private static String getCommandName(final String[] args, final String defaultCommandName) { if (args.length > 0 && args[0] != null) { return args[0]; } else { return defaultCommandName; } } } <commit_after>package com.maddenabbott.jenny; import java.util.Arrays; /** * The main entry point for Jenny. */ public class Application { private static final String defaultCommand = "help"; public static void main(String[] args) { String commandName = getCommandName(args, defaultCommand); String[] parameters = getParameters(args); } private static String getCommandName(final String[] args, final String defaultCommandName) { if (args.length > 0 && args[0] != null) { return args[0]; } else { return defaultCommandName; } } private static String[] getParameters(final String[] args) { if (args.length > 1) { return Arrays.copyOfRange(args, 1, args.length); } return new String[]{ }; } }
<commit_msg>Update url to point / to the contractions app <commit_before>from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() import contractions.views urlpatterns = patterns('', # Examples: # url(r'^$', 'pregnancy.views.home', name='home'), # url(r'^pregnancy/', include('pregnancy.foo.urls')), url(r'^contractions/$', contractions.views.ContractionList.as_view(), name='ContractionList'), url(r'^update_intensity/(?P<pk>\d+)/$', contractions.views.UpdateIntensity.as_view(), name='UpdateIntensity'), url(r'^update_intensity2/(?P<pk>\d+)/$', contractions.views.UpdateIntensity2.as_view(), name='UpdateIntensity2'), url(r'^ContractionListTable/$', contractions.views.ContractionListTable.as_view(), name='ContractionListTable'), url(r'^StartContraction/$', contractions.views.StartContraction.as_view(), name='StartContraction'), url(r'^StopContraction/(?P<pk>\d+)/$', contractions.views.StopContraction.as_view(), name='StopContraction'), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), ) <commit_after>from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() import contractions.views urlpatterns = patterns('', # Examples: # url(r'^$', 'pregnancy.views.home', name='home'), # url(r'^pregnancy/', include('pregnancy.foo.urls')), url(r'^$', contractions.views.ContractionList.as_view(), name='ContractionList'), url(r'^contractions/$', contractions.views.ContractionList.as_view(), name='ContractionList'), url(r'^update_intensity/(?P<pk>\d+)/$', contractions.views.UpdateIntensity.as_view(), name='UpdateIntensity'), url(r'^update_intensity2/(?P<pk>\d+)/$', contractions.views.UpdateIntensity2.as_view(), name='UpdateIntensity2'), url(r'^ContractionListTable/$', contractions.views.ContractionListTable.as_view(), name='ContractionListTable'), url(r'^StartContraction/$', contractions.views.StartContraction.as_view(), name='StartContraction'), url(r'^StopContraction/(?P<pk>\d+)/$', contractions.views.StopContraction.as_view(), name='StopContraction'), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), )
<commit_msg>Fix exit code on errors in SAWScript. A previous change resulted in "success" exit codes even when errors had occurred.<commit_before>module Main where import Control.Exception import Data.List import System.IO import System.Console.GetOpt import System.Environment import SAWScript.Options import SAWScript.ProcessFile (processFile) import qualified SAWScript.REPL as REPL main :: IO () main = do argv <- getArgs case getOpt Permute options argv of (opts, files, []) -> do let opts' = foldl' (flip id) defaultOptions opts opts'' <- processEnv opts' {- We have two modes of operation: batch processing, handled in 'SAWScript.ProcessFile', and a REPL, defined in 'SAWScript.REPL'. -} case (runInteractively opts'', files) of (True, []) -> REPL.run opts'' (False, [file]) -> processFile opts'' file `catch` (\(ErrorCall msg) -> hPutStr stderr msg) (False, _:_) -> hPutStrLn stderr "Running multiple files not yet supported." (True, _:_) -> hPutStrLn stderr ("Unable to handle files in interactive mode" ++ usageInfo header options) (False, []) -> putStrLn (usageInfo header options) (_, _, errs) -> hPutStrLn stderr (concat errs ++ usageInfo header options) where header = "Usage: saw [OPTION...] [-I | files...]" <commit_after>module Main where import Control.Exception import Data.List import System.Exit import System.IO import System.Console.GetOpt import System.Environment import SAWScript.Options import SAWScript.ProcessFile (processFile) import qualified SAWScript.REPL as REPL main :: IO () main = do argv <- getArgs case getOpt Permute options argv of (opts, files, []) -> do let opts' = foldl' (flip id) defaultOptions opts opts'' <- processEnv opts' {- We have two modes of operation: batch processing, handled in 'SAWScript.ProcessFile', and a REPL, defined in 'SAWScript.REPL'. -} case (runInteractively opts'', files) of (True, []) -> REPL.run opts'' (False, [file]) -> processFile opts'' file `catch` (\(ErrorCall msg) -> err msg) (False, _:_) -> err "Running multiple files not yet supported." (True, _:_) -> err ("Unable to handle files in interactive mode" ++ usageInfo header options) (False, []) -> putStrLn (usageInfo header options) (_, _, errs) -> err (concat errs ++ usageInfo header options) where header = "Usage: saw [OPTION...] [-I | files...]" err msg = hPutStrLn stderr msg >> exitFailure
<commit_msg>Test iter_zones instead of get_zones <commit_before>import os from unittest import TestCase from yoconfigurator.base import read_config from yoconfig import configure_services from pycloudflare.services import CloudFlareService app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) conf = read_config(app_dir) class ZonesTest(TestCase): def setUp(self): configure_services('cloudflare', ['cloudflare'], conf.common) self.cloudflare = CloudFlareService() def test_get_all_zones(self): zones = self.cloudflare.get_zones() self.assertIsInstance(zones, list) def test_get_zone(self): zone_id = self.cloudflare.get_zones()[0]['id'] zone = self.cloudflare.get_zone(zone_id) self.assertIsInstance(zone, dict) <commit_after>import os import types from unittest import TestCase from yoconfigurator.base import read_config from yoconfig import configure_services from pycloudflare.services import CloudFlareService app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) conf = read_config(app_dir) class ZonesTest(TestCase): def setUp(self): configure_services('cloudflare', ['cloudflare'], conf.common) self.cloudflare = CloudFlareService() def test_get_all_zones(self): zones = self.cloudflare.iter_zones() self.assertIsInstance(zones, types.GeneratorType) def test_get_zone(self): zone_id = self.cloudflare.get_zones()[0]['id'] zone = self.cloudflare.get_zone(zone_id) self.assertIsInstance(zone, dict)
<commit_msg>Use some actual content types <commit_before>import AdhHttp = require("../Http/Http"); import AdhConfig = require("../Config/Config"); import AdhTopLevelState = require("../TopLevelState/TopLevelState"); var notFoundTemplate = "<h1>404 - not Found</h1>"; interface IResourceRouterScope extends ng.IScope { template : string; } export var resourceRouter = ( adhHttp : AdhHttp.Service<any>, adhConfig : AdhConfig.Type, adhTopLevelState : AdhTopLevelState.TopLevelState, $routeParams : ng.route.IRouteParamsService, $scope : IResourceRouterScope ) => { var resourceUrl = adhConfig.rest_url + "/" + $routeParams["path"]; adhHttp.get(resourceUrl).then((resource) => { switch (resource.content_type) { case "adhocracy_core.resources.sample_proposal.IProposal": $scope.template = "<adh-document-workbench></adh-document-workbench>"; break; default: $scope.template = notFoundTemplate; } }, (reason) => { $scope.template = notFoundTemplate; }); }; <commit_after>import AdhHttp = require("../Http/Http"); import AdhConfig = require("../Config/Config"); import AdhTopLevelState = require("../TopLevelState/TopLevelState"); import RIBasicPool = require("Resources_/adhocracy_core/resources/pool/IBasicPool"); import RIMercatorProposal = require("Resources_/adhocracy_core/resources/mercator/IMercatorProposal"); import RIUser = require("Resources_/adhocracy_core/resources/principal/IUser"); import RIUsersService = require("Resources_/adhocracy_core/resources/principal/IUsersService"); var notFoundTemplate = "<h1>404 - not Found</h1>"; interface IResourceRouterScope extends ng.IScope { template : string; } export var resourceRouter = ( adhHttp : AdhHttp.Service<any>, adhConfig : AdhConfig.Type, adhTopLevelState : AdhTopLevelState.TopLevelState, $routeParams : ng.route.IRouteParamsService, $scope : IResourceRouterScope ) => { var resourceUrl = adhConfig.rest_url + "/" + $routeParams["path"]; adhHttp.get(resourceUrl).then((resource) => { switch (resource.content_type) { case RIBasicPool.content_type: $scope.template = "<adh-document-workbench></adh-document-workbench>"; break; case RIMercatorProposal.content_type: $scope.template = "<adh-document-workbench></adh-document-workbench>"; break; case RIUser.content_type: $scope.template = "<h1>User</h1>"; break; case RIUsersService.content_type: $scope.template = "<h1>User List</h1>"; break; default: $scope.template = notFoundTemplate; } }, (reason) => { $scope.template = notFoundTemplate; }); };
<commit_msg>Include junit.jar in the final EGG package installation <commit_before> from distutils.core import setup setup(name='lattice', version='0.8', description='Java Build tool in Python', author='Zhenlei Cai', author_email='jpenguin@gmail.com', url='http://www.python.org/sigs/distutils-sig/', include_package_data = True, packages=['lattice'] ) <commit_after>from setuptools import setup, find_packages setup(name='lattice', version='0.9', description='Java Build tool in Python', author='Zhenlei Cai', author_email='jpenguin@gmail.com', url='http://www.python.org/sigs/distutils-sig/', include_package_data = True, packages=['lattice'], package_data = { '': ['*.jar'], } )
<commit_msg>Add readyToLogin.py and clear-passphrases.py to setup.py script. <commit_before>from distutils.core import setup import py2exe import sys setup(console=['..\src\omni-configure.py'], name="omni-configure", py_modules=['sfa','ConfigParser','logging','optparse', 'os','sys','string', 're','platform','shutil','zipfile','logging','subprocess'], # options={ # 'py2exe':{ # 'includes':'sfa.trust.certificate,ConfigParser,logging,optparse\ # ,os,sys,string,re,platform,shutil,zipfile,logging' # } # } ) <commit_after>from distutils.core import setup import py2exe import sys setup(console=['..\src\omni-configure.py', '..\examples/readyToLogin.py', '..\src\clear-passphrases.py'], name="omni-configure", py_modules=['sfa','ConfigParser','logging','optparse', 'os','sys','string', 're','platform','shutil','zipfile','logging','subprocess'], # options={ # 'py2exe':{ # 'includes':'sfa.trust.certificate,ConfigParser,logging,optparse\ # ,os,sys,string,re,platform,shutil,zipfile,logging' # } # } )
<commit_msg>[Bitbay] Use compact JSON instead of replacing whitespaces in String <commit_before>package org.knowm.xchange.bitbay.v3.service; import java.io.IOException; import java.util.UUID; import java.util.regex.Pattern; import org.knowm.xchange.Exchange; import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTrades; import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTradesQuery; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.utils.ObjectMapperHelper; /** @author walec51 */ public class BitbayTradeServiceRaw extends BitbayBaseService { private static final Pattern WHITESPACES = Pattern.compile("\\s\\s"); BitbayTradeServiceRaw(Exchange exchange) { super(exchange); } public BitbayUserTrades getBitbayTransactions(BitbayUserTradesQuery query) throws IOException, ExchangeException { String jsonQuery = ObjectMapperHelper.toJSON(query); jsonQuery = WHITESPACES.matcher(jsonQuery).replaceAll(""); BitbayUserTrades response = bitbayAuthenticated.getTransactionHistory( apiKey, sign, exchange.getNonceFactory(), UUID.randomUUID(), jsonQuery); checkError(response); return response; } } <commit_after>package org.knowm.xchange.bitbay.v3.service; import java.io.IOException; import java.util.UUID; import org.knowm.xchange.Exchange; import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTrades; import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTradesQuery; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.utils.ObjectMapperHelper; /** @author walec51 */ public class BitbayTradeServiceRaw extends BitbayBaseService { BitbayTradeServiceRaw(Exchange exchange) { super(exchange); } public BitbayUserTrades getBitbayTransactions(BitbayUserTradesQuery query) throws IOException, ExchangeException { final String jsonQuery = ObjectMapperHelper.toCompactJSON(query); final BitbayUserTrades response = bitbayAuthenticated.getTransactionHistory( apiKey, sign, exchange.getNonceFactory(), UUID.randomUUID(), jsonQuery); checkError(response); return response; } }
<commit_msg>Use the same name for the field in frontend and backend <commit_before>from django.db import models class Picture(models.Model): """ This is a small demo using just two fields. ImageField depends on PIL or pillow (where Pillow is easily installable in a virtualenv. If you have problems installing pillow, use a more generic FileField instead. """ picture_file = models.ImageField(upload_to="pictures") def __unicode__(self): return self.picture_file.name <commit_after>from django.db import models class Picture(models.Model): """ This is a small demo using just two fields. ImageField depends on PIL or pillow (where Pillow is easily installable in a virtualenv. If you have problems installing pillow, use a more generic FileField instead. """ file = models.ImageField(upload_to="pictures") def __unicode__(self): return self.file.name
<commit_msg>Correct mistaken assertTrue() -> assertEquals() <commit_before>from core.models import Category from django.test.testcases import TestCase from django.urls import reverse class ExportViewMixinTest(TestCase): def setUp(self): self.url = reverse('export-category') self.cat1 = Category.objects.create(name='Cat 1') self.cat2 = Category.objects.create(name='Cat 2') def test_get(self): response = self.client.get(self.url) self.assertContains(response, self.cat1.name, status_code=200) self.assertTrue(response['Content-Type'], 'text/html') def test_post(self): data = { 'file_format': '0', } response = self.client.post(self.url, data) self.assertContains(response, self.cat1.name, status_code=200) self.assertTrue(response.has_header("Content-Disposition")) self.assertTrue(response['Content-Type'], 'text/csv') <commit_after>from core.models import Category from django.test.testcases import TestCase from django.urls import reverse class ExportViewMixinTest(TestCase): def setUp(self): self.url = reverse('export-category') self.cat1 = Category.objects.create(name='Cat 1') self.cat2 = Category.objects.create(name='Cat 2') def test_get(self): response = self.client.get(self.url) self.assertContains(response, self.cat1.name, status_code=200) self.assertEquals(response['Content-Type'], 'text/html; charset=utf-8') def test_post(self): data = { 'file_format': '0', } response = self.client.post(self.url, data) self.assertContains(response, self.cat1.name, status_code=200) self.assertTrue(response.has_header("Content-Disposition")) self.assertEquals(response['Content-Type'], 'text/csv')
<commit_msg>Call the c functions instead of passing a pointer <commit_before> int Cget_personality(void) { unsigned long int persona = 0xffffffff; return personality(persona); } static PyObject* get_personality(PyObject* self) { return Py_BuildValue("i", Cget_personality); } int Cset_personality(void) { unsigned long int persona = READ_IMPLIES_EXEC; return personality(persona); } static PyObject* set_personality(PyObject* self) { return Py_BuildValue("i", Cset_personality); } static PyMethodDef personality_methods[] = { {"get_personality", (PyCFunction)get_personality, METH_NOARGS, "Returns the personality value"}, {"set_personality", (PyCFunction)set_personality, METH_NOARGS, "Sets the personality value"}, /* {"version", (PyCFunction)version, METH_NOARGS, "Returns the version number"}, */ {NULL, NULL, 0, NULL} }; static struct PyModuleDef pypersonality = { PyModuleDef_HEAD_INIT, "personality", "Module to manipulate process execution domain", -1, personality_methods }; PyMODINIT_FUNC PyInit_pypersonality(void) { return PyModule_Create(&pypersonality); } <commit_after> int Cget_personality(void) { unsigned long persona = 0xffffffffUL; return personality(persona); } static PyObject* get_personality(PyObject* self) { return Py_BuildValue("i", Cget_personality()); } int Cset_personality(unsigned long persona) { return personality(persona); } static PyObject* set_personality(PyObject* self, PyObject *args) { unsigned long persona = READ_IMPLIES_EXEC; //Py_Args_ParseTuple(args, "i", &persona); return Py_BuildValue("i", Cset_personality(persona)); } static PyMethodDef personality_methods[] = { {"get_personality", (PyCFunction)get_personality, METH_NOARGS, "Returns the personality value"}, {"set_personality", (PyCFunction)set_personality, METH_NOARGS, "Sets the personality value"}, /* {"version", (PyCFunction)version, METH_NOARGS, "Returns the version number"}, */ {NULL, NULL, 0, NULL} }; static struct PyModuleDef pypersonality = { PyModuleDef_HEAD_INIT, "personality", "Module to manipulate process execution domain", -1, personality_methods }; PyMODINIT_FUNC PyInit_pypersonality(void) { return PyModule_Create(&pypersonality); }
<commit_msg>Update request type in `angular` <commit_before>/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { AuthenticationResult, AuthError, CommonEndSessionRequest } from "@azure/msal-common"; import { EventType } from "./EventType"; import { InteractionType } from "../utils/BrowserConstants"; import { PopupRequest, RedirectRequest, SilentRequest, SsoSilentRequest } from ".."; export type EventMessage = { eventType: EventType; interactionType: InteractionType | null; payload: EventPayload; error: EventError; timestamp: number; }; export type EventPayload = PopupRequest | RedirectRequest | SilentRequest | SsoSilentRequest | CommonEndSessionRequest | AuthenticationResult | null; export type EventError = AuthError | Error | null; export type EventCallbackFunction = (message: EventMessage) => void; <commit_after>/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { AuthenticationResult, AuthError } from "@azure/msal-common"; import { EventType } from "./EventType"; import { InteractionType } from "../utils/BrowserConstants"; import { PopupRequest, RedirectRequest, SilentRequest, SsoSilentRequest, EndSessionRequest } from ".."; export type EventMessage = { eventType: EventType; interactionType: InteractionType | null; payload: EventPayload; error: EventError; timestamp: number; }; export type EventPayload = PopupRequest | RedirectRequest | SilentRequest | SsoSilentRequest | EndSessionRequest | AuthenticationResult | null; export type EventError = AuthError | Error | null; export type EventCallbackFunction = (message: EventMessage) => void;
<commit_msg>Remove locking logic from sync watchdog <commit_before>from tapiriik.database import db, close_connections from tapiriik.sync import SyncStep import os import signal import socket from datetime import timedelta, datetime print("Sync watchdog run at %s" % datetime.now()) host = socket.gethostname() for worker in db.sync_workers.find({"Host": host}): # Does the process still exist? alive = True try: os.kill(worker["Process"], 0) except os.error: print("%s is no longer alive" % worker) alive = False # Has it been stalled for too long? if worker["State"] == SyncStep.List: timeout = timedelta(minutes=45) # This can take a loooooooong time else: timeout = timedelta(minutes=10) # But everything else shouldn't if alive and worker["Heartbeat"] < datetime.utcnow() - timeout: print("%s timed out" % worker) os.kill(worker["Process"], signal.SIGKILL) alive = False # Clear it from the database if it's not alive. if not alive: db.sync_workers.remove({"_id": worker["_id"]}) # Unlock users attached to it. for user in db.users.find({"SynchronizationWorker": worker["Process"], "SynchronizationHost": host}): print("\t Unlocking %s" % user["_id"]) db.users.update({"SynchronizationWorker": worker["Process"], "SynchronizationHost": host}, {"$unset":{"SynchronizationWorker": True}}, multi=True) close_connections() <commit_after>from tapiriik.database import db, close_connections from tapiriik.sync import SyncStep import os import signal import socket from datetime import timedelta, datetime print("Sync watchdog run at %s" % datetime.now()) host = socket.gethostname() for worker in db.sync_workers.find({"Host": host}): # Does the process still exist? alive = True try: os.kill(worker["Process"], 0) except os.error: print("%s is no longer alive" % worker) alive = False # Has it been stalled for too long? if worker["State"] == SyncStep.List: timeout = timedelta(minutes=45) # This can take a loooooooong time else: timeout = timedelta(minutes=10) # But everything else shouldn't if alive and worker["Heartbeat"] < datetime.utcnow() - timeout: print("%s timed out" % worker) os.kill(worker["Process"], signal.SIGKILL) alive = False # Clear it from the database if it's not alive. if not alive: db.sync_workers.remove({"_id": worker["_id"]}) close_connections()
<commit_msg>Add first code for NeuralNetwork class. <commit_before>import numpy as np import theano import theano.tensor as T<commit_after>import numpy as np import theano import theano.tensor as T class NeuralNetwork(object): def __init__(self, layers, miniBatchSize): self.miniBatchSize = miniBatchSize #Initialize layers. self.layers = layers self.numLayers = len(self.layers) self.firstLayer = self.layers[0] self.lastLayer = self.layers[-1] #Populate self.learningParams with a complete list of weights and biases from all layers. self.learningParams = [] for layer in self.layers: for param in layer.learningParams: self.learningParams.append(param) #Connect each layer's input to the previous layer's output. for i in xrange(1, self.numLayers): nextLayer = layers[i] previousLayer = layers[i-1] nextLayer.input = previousLayer.output
<commit_msg>Make script run and fix all typos <commit_before>import requests url = "https://ua.api.yle.fi/graphql?app_id=8d7303fe&app_key=105875199ef3a1f7e0fbf7e2834b2dc&query={uutisetMostRecentNews:articleList(publisher:YLE_UUTISET,limit:100,offset:0,coverage:NATIONAL){meta{count,total,remaining},items{fullUrl,properties}}}" i = 0 while True: url = "https://ua.api.yle.fi/graphql?app_id=8d7303fe&app_key=105875199ef3a1f7e0fbf7e2834b2dc&query={uutisetMostRecentNews:articleList(publisher:YLE_UUTISET,limit:100,offset:" + str( i * 100 ) + ",coverage:NATIONAL){meta{count,total,remaining},items{fullUrl,properties}}}" r = requests.get( url ) r = r.json() d = r['data'] items = d['uutisetMostRecentNews']['items'] for item in items: print item['fullUrl'] if d['meta']['remaining'] < 100: return i += 1 <commit_after> import requests url = "https://ua.api.yle.fi/graphql?app_id=8d7303fe&app_key=105875199ef3a1f7e0fbf7e2834b2dc&query={uutisetMostRecentNews:articleList(publisher:YLE_UUTISET,limit:100,offset:0,coverage:NATIONAL){meta{count,total,remaining},items{fullUrl,properties}}}" i = 0 while True: url = "https://ua.api.yle.fi/graphql?app_id=8d7303fe&app_key=105875199ef3a1f7e0fbf7e2834b2dc&query={uutisetMostRecentNews:articleList(publisher:YLE_UUTISET,limit:100,offset:" + str( i * 100 ) + ",coverage:NATIONAL){meta{count,total,remaining},items{fullUrl,properties}}}" r = requests.get( url ) r = r.json() d = r['data']['uutisetMostRecentNews'] items = d['items'] for item in items: print item['fullUrl'] if d['meta']['remaining'] < 100: break i += 1
<commit_msg>Create class for a concert set <commit_before>import { bootstrap, Component } from 'angular2/angular2'; @Component({ selector: 'deadbase-app', template: '<h1>{{title}}</h1><h2>{{venue}} Details!</h2>' }) class DeadBaseAppComponent { public title = "Deadbase - Grateful Dead Concert Archive"; public venue = "Filmore West"; } bootstrap(DeadBaseAppComponent); <commit_after>import { bootstrap, Component } from 'angular2/angular2'; class ConcertSet { date: Date; venue: string; set: number; } @Component({ selector: 'deadbase-app', template: '<h1>{{title}}</h1><h2>{{concert.date}} -- {{concert.venue}} Details!</h2>' }) class DeadBaseAppComponent { public title = "Deadbase - Grateful Dead Concert Archive"; public concert: ConcertSet = { date: new Date(1971, 7, 2), venue: "Filmore West", set: 2 } } bootstrap(DeadBaseAppComponent);
<commit_msg>Adjust minor animated tiles transgression <commit_before>\ #include "animatedtilesplugin.h" #include "animatedtilesitem.h" AnimatedTilesPlugin::AnimatedTilesPlugin() { this->mName = "AnimatedTiles"; //This should not be an advertized plugin until it is implemented //this->mRole = "animatedTiles"; } Q_EXPORT_PLUGIN2(animatedTiles, AnimatedTilesPlugin) void AnimatedTilesPlugin::registerPlugin(QDeclarativeContext *context) { qmlRegisterType<AnimatedTilesItem>("AnimatedTiles", 1, 0, "AnimatedTiles"); } <commit_after>\ #include "animatedtilesplugin.h" #include "animatedtilesitem.h" AnimatedTilesPlugin::AnimatedTilesPlugin() { setName("AnimatedTiles"); //This should not be an advertized plugin until it is implemented //setRole("animatedTiles"); } Q_EXPORT_PLUGIN2(animatedTiles, AnimatedTilesPlugin) void AnimatedTilesPlugin::registerPlugin(QDeclarativeContext *context) { qmlRegisterType<AnimatedTilesItem>("AnimatedTiles", 1, 0, "AnimatedTiles"); }
<commit_msg>Add more test coverage for the server. <commit_before>from mock import patch import sure # noqa from moto.server import main def test_wrong_arguments(): try: main(["name", "test1", "test2", "test3"]) assert False, ("main() when called with the incorrect number of args" " should raise a system exit") except SystemExit: pass @patch('moto.server.run_simple') def test_right_arguments(run_simple): main(["s3"]) func_call = run_simple.call_args[0] func_call[0].should.equal("0.0.0.0") func_call[1].should.equal(5000) @patch('moto.server.run_simple') def test_port_argument(run_simple): main(["s3", "--port", "8080"]) func_call = run_simple.call_args[0] func_call[0].should.equal("0.0.0.0") func_call[1].should.equal(8080) <commit_after>from mock import patch import sure # noqa from moto.server import main, create_backend_app, DomainDispatcherApplication def test_wrong_arguments(): try: main(["name", "test1", "test2", "test3"]) assert False, ("main() when called with the incorrect number of args" " should raise a system exit") except SystemExit: pass @patch('moto.server.run_simple') def test_right_arguments(run_simple): main(["s3"]) func_call = run_simple.call_args[0] func_call[0].should.equal("0.0.0.0") func_call[1].should.equal(5000) @patch('moto.server.run_simple') def test_port_argument(run_simple): main(["s3", "--port", "8080"]) func_call = run_simple.call_args[0] func_call[0].should.equal("0.0.0.0") func_call[1].should.equal(8080) def test_domain_dispatched(): dispatcher = DomainDispatcherApplication(create_backend_app) backend_app = dispatcher.get_application("email.us-east1.amazonaws.com") backend_app.view_functions.keys()[0].should.equal('EmailResponse.dispatch') def test_domain_without_matches(): dispatcher = DomainDispatcherApplication(create_backend_app) dispatcher.get_application.when.called_with("not-matching-anything.com").should.throw(RuntimeError) def test_domain_dispatched_with_service(): # If we pass a particular service, always return that. dispatcher = DomainDispatcherApplication(create_backend_app, service="s3") backend_app = dispatcher.get_application("s3.us-east1.amazonaws.com") backend_app.view_functions.keys()[0].should.equal('ResponseObject.key_response')
<commit_msg>Support floating point ns/op lines <commit_before>package main import "fmt" import "os" import "bufio" import "strings" import "time" import "strconv" import "flag" func main() { dur := flag.Duration("d", time.Second, "duration unit") flag.Parse() scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { line := scanner.Text() // fmt.Println(line) // Println will add back the final '\n' if strings.HasPrefix(line, "Benchmark") { fields := strings.Fields(line) if len(fields) < 4 || fields[3] != "ns/op" { fmt.Println(line) continue } nsPerOp, err := strconv.ParseInt(fields[2], 10, 64) if err != nil { fmt.Println(line) continue } opsPerDur := dur.Nanoseconds() / nsPerOp fmt.Printf("%s\t%d ops/%v\n", line, opsPerDur, dur) continue } fmt.Println(line) } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) } } <commit_after>package main import "fmt" import "os" import "bufio" import "strings" import "time" import "strconv" import "flag" func main() { dur := flag.Duration("d", time.Second, "duration unit") flag.Parse() scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { line := scanner.Text() // fmt.Println(line) // Println will add back the final '\n' if strings.HasPrefix(line, "Benchmark") { fields := strings.Fields(line) if len(fields) < 4 || fields[3] != "ns/op" { fmt.Println(line) continue } nsPerOp, err := strconv.ParseFloat(fields[2], 64) if err != nil { fmt.Println(line) continue } opsPerDur := int64(float64(dur.Nanoseconds()) / nsPerOp) fmt.Printf("%s\t%d ops/%v\n", line, opsPerDur, dur) continue } fmt.Println(line) } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) } }
<commit_msg>Enforce name conventions for test-created activities<commit_before>/** * */ package test.issues.strava; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import java.util.Arrays; import java.util.List; import javastrava.api.v3.model.StravaComment; import javastrava.api.v3.rest.API; import javastrava.api.v3.rest.ActivityAPI; import org.junit.Test; import test.api.service.impl.util.ActivityServiceUtils; import test.utils.RateLimitedTestRunner; import test.utils.TestUtils; /** * <p> * Issue test for issue javastrava-api #67 - tests will PASS if the issue is still a problem * </p> * * @author Dan Shannon * @see <a href="https://github.com/danshannon/javastravav3api/issues/67>https://github.com/danshannon/javastravav3api/issues/67</a> */ public class Issue67 { @Test public void testIssue() throws Exception { RateLimitedTestRunner.run(() -> { final ActivityAPI api = API.instance(ActivityAPI.class, TestUtils.getValidToken()); final StravaComment comment = ActivityServiceUtils.createPrivateActivityWithComment(); final List<StravaComment> comments = Arrays.asList(api.listActivityComments(comment.getActivityId(), null, null, null)); assertNotNull(comments); assertFalse(comments.isEmpty()); }); } } <commit_after>/** * */ package test.issues.strava; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import java.util.Arrays; import java.util.List; import javastrava.api.v3.model.StravaComment; import javastrava.api.v3.rest.API; import javastrava.api.v3.rest.ActivityAPI; import org.junit.Test; import test.api.service.impl.util.ActivityServiceUtils; import test.utils.RateLimitedTestRunner; import test.utils.TestUtils; /** * <p> * Issue test for issue javastrava-api #67 - tests will PASS if the issue is still a problem * </p> * * @author Dan Shannon * @see <a href="https://github.com/danshannon/javastravav3api/issues/67>https://github.com/danshannon/javastravav3api/issues/67</a> */ public class Issue67 { @Test public void testIssue() throws Exception { RateLimitedTestRunner.run(() -> { final ActivityAPI api = API.instance(ActivityAPI.class, TestUtils.getValidToken()); final StravaComment comment = ActivityServiceUtils.createPrivateActivityWithComment("Issue67.testIssue()"); final List<StravaComment> comments = Arrays.asList(api.listActivityComments(comment.getActivityId(), null, null, null)); assertNotNull(comments); assertFalse(comments.isEmpty()); }); } }
<commit_msg>Refactor shallow copy instead of deep clone <commit_before>import { MarkedPackagesAction, MarkedPackagesActions, setMarkedPackages } from "./markedPackages.actions" import { MarkedPackage } from "../../../../codeCharta.model" import { addItemToArray, removeItemFromArray } from "../../../../util/reduxHelper" const clone = require("rfdc")() export function markedPackages(state: MarkedPackage[] = setMarkedPackages().payload, action: MarkedPackagesAction): MarkedPackage[] { switch (action.type) { case MarkedPackagesActions.SET_MARKED_PACKAGES: return clone(action.payload) case MarkedPackagesActions.MARK_PACKAGE: return addItemToArray(state, action.payload) case MarkedPackagesActions.UNMARK_PACKAGE: return removeItemFromArray(state, action.payload) default: return state } } <commit_after>import { MarkedPackagesAction, MarkedPackagesActions, setMarkedPackages } from "./markedPackages.actions" import { MarkedPackage } from "../../../../codeCharta.model" import { addItemToArray, removeItemFromArray } from "../../../../util/reduxHelper" export function markedPackages(state: MarkedPackage[] = setMarkedPackages().payload, action: MarkedPackagesAction): MarkedPackage[] { switch (action.type) { case MarkedPackagesActions.SET_MARKED_PACKAGES: return [...action.payload] case MarkedPackagesActions.MARK_PACKAGE: return addItemToArray(state, action.payload) case MarkedPackagesActions.UNMARK_PACKAGE: return removeItemFromArray(state, action.payload) default: return state } }
<commit_msg>Remove a double call to requestLayout in applyTransformation <commit_before>package com.desmond.squarecamera; import android.support.annotation.NonNull; import android.view.View; import android.view.animation.Animation; import android.view.animation.Transformation; /** * Created by desmond on 4/8/15. */ public class ResizeAnimation extends Animation { final int mStartLength; final int mFinalLength; final boolean mIsPortrait; final View mView; public ResizeAnimation(@NonNull View view, final ImageParameters imageParameters) { mStartLength = view.getContext().getResources().getDimensionPixelSize(R.dimen.cover_start_width); mFinalLength = imageParameters.getAnimationParameter(); mIsPortrait = imageParameters.isPortrait(); mView = view; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { int newLength = (int) (mStartLength + (mFinalLength - mStartLength) * interpolatedTime); if (mIsPortrait) { mView.getLayoutParams().height = newLength; } else { mView.getLayoutParams().width = newLength; } mView.requestLayout(); } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); } @Override public boolean willChangeBounds() { return true; } } <commit_after>package com.desmond.squarecamera; import android.support.annotation.NonNull; import android.view.View; import android.view.animation.Animation; import android.view.animation.Transformation; /** * Created by desmond on 4/8/15. */ public class ResizeAnimation extends Animation { final int mStartLength; final int mFinalLength; final boolean mIsPortrait; final View mView; public ResizeAnimation(@NonNull View view, final ImageParameters imageParameters) { mStartLength = view.getContext().getResources().getDimensionPixelSize(R.dimen.cover_start_width); mFinalLength = imageParameters.getAnimationParameter(); mIsPortrait = imageParameters.isPortrait(); mView = view; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { int newLength = (int) (mStartLength + (mFinalLength - mStartLength) * interpolatedTime); if (mIsPortrait) { mView.getLayoutParams().height = newLength; } else { mView.getLayoutParams().width = newLength; } } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); } @Override public boolean willChangeBounds() { return true; } }
<commit_msg>Fix for compile error on Linux when using clang with GNU std c++ lib (__STRICT_ANSI__ is required) <commit_before>//------------------------------------------------------------------------------ /** @file core/posix/precompiled.h Standard includes for POSIX platforms. NOTE: keep as many headers out of here as possible, at least on compilers which don't have pre-compiled-headers turned on. */ #ifdef __STRICT_ANSI__ #undef __STRICT_ANSI__ #endif #include <cstddef> <commit_after>//------------------------------------------------------------------------------ /** @file core/posix/precompiled.h Standard includes for POSIX platforms. NOTE: keep as many headers out of here as possible, at least on compilers which don't have pre-compiled-headers turned on. */ // this is a workaround when using clang with the GNU std lib, // this fails without __STRICT_ANSI__ because clang doesn't // know the __float128 type #if __clang__ && ORYOL_LINUX && !defined __STRICT_ANSI__ #define __STRICT_ANSI__ #endif #include <cstddef>
<commit_msg>Add doctest, just for example sake, it does not work <commit_before>// This definition works for current file. // Everywhere. #![allow(dead_code)] <commit_after>// This definition works for current file. // Everywhere. #![allow(dead_code)] // Doc tests. Looks fine. use std::ops::Range; /// Return true if two ranges overlap. /// /// assert_eq!(ranges::overlap(0..7, 3..10), true); /// assert_eq!(ranges::overlap(1..5, 101..105), false); /// /// If either range is empty, they don't count as overlapping. /// /// assert_eq!(ranges::overlap(0..0, 0..10), false); /// pub fn overlap(r1: Range<usize>, r2: Range<usize>) -> bool { r1.start < r1.end && r2.start < r2.end && r1.start < r2.end && r2.start < r1.end }
<commit_msg>Add pytest hook to register online marker <commit_before>"""Module grouping session scoped PyTest fixtures.""" import pytest from _pytest.monkeypatch import MonkeyPatch import pydov def pytest_runtest_setup(): pydov.hooks = [] @pytest.fixture(scope='module') def monkeymodule(): mpatch = MonkeyPatch() yield mpatch mpatch.undo() <commit_after>"""Module grouping session scoped PyTest fixtures.""" import pytest from _pytest.monkeypatch import MonkeyPatch import pydov def pytest_runtest_setup(): pydov.hooks = [] def pytest_configure(config): config.addinivalue_line("markers", "online: mark test that requires internet access") @pytest.fixture(scope='module') def monkeymodule(): mpatch = MonkeyPatch() yield mpatch mpatch.undo()
<commit_msg>Use `isinstance()` at the cost of an extra import <commit_before>import os import shutil from django.core.files.storage import get_storage_class def delete_user_storage(username): storage = get_storage_class()() def _recursive_delete(path): directories, files = storage.listdir(path) for file_ in files: storage.delete(os.path.join(path, file_)) for directory in directories: _recursive_delete(os.path.join(path, directory)) if storage.__class__.__name__ == 'FileSystemStorage': if storage.exists(username): shutil.rmtree(storage.path(username)) else: _recursive_delete(username) def user_storage_exists(username): storage = get_storage_class()() return storage.exists(username) <commit_after>import os import shutil from django.core.files.storage import FileSystemStorage, get_storage_class def delete_user_storage(username): storage = get_storage_class()() def _recursive_delete(path): directories, files = storage.listdir(path) for file_ in files: storage.delete(os.path.join(path, file_)) for directory in directories: _recursive_delete(os.path.join(path, directory)) if isinstance(storage, FileSystemStorage): if storage.exists(username): shutil.rmtree(storage.path(username)) else: _recursive_delete(username) def user_storage_exists(username): storage = get_storage_class()() return storage.exists(username)
<commit_msg>[fa] Bring back the accidentally removed comment <commit_before>/* LanguageTool, a natural language style checker * Copyright (C) 2014 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.tokenizers; import org.junit.Test; import org.languagetool.TestTools; import org.languagetool.language.Persian; public class PersianSRXSentenceTokenizerTest { private final SRXSentenceTokenizer stokenizer = new SRXSentenceTokenizer(new Persian()); @Test public void test() { testSplit("این یک جمله است. ", "حملهٔ بعدی"); } private void testSplit(String... sentences) { TestTools.testSplit(sentences, stokenizer); } } <commit_after>/* LanguageTool, a natural language style checker * Copyright (C) 2014 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.tokenizers; import org.junit.Test; import org.languagetool.TestTools; import org.languagetool.language.Persian; public class PersianSRXSentenceTokenizerTest { private final SRXSentenceTokenizer stokenizer = new SRXSentenceTokenizer(new Persian()); @Test public void test() { // NOTE: sentences here need to end with a space character so they // have correct whitespace when appended: testSplit("این یک جمله است. ", "حملهٔ بعدی"); } private void testSplit(String... sentences) { TestTools.testSplit(sentences, stokenizer); } }
<commit_msg>Fix ordering of deletions on MySQL <commit_before>from __future__ import unicode_literals from django.test import SimpleTestCase class CaseExtension(SimpleTestCase): _models = tuple() @classmethod def append_model(cls, model): cls._models += (model, ) def _pre_setup(self): super(CaseExtension, self)._pre_setup() self._map_models('create_table') def _post_teardown(self): self._map_models('delete_table') super(CaseExtension, self)._post_teardown() def _map_models(self, method_name): for model in self._models: try: getattr(model, method_name)() except AttributeError: raise TypeError("{0} doesn't support table method {1}".format(model, method_name)) <commit_after>from __future__ import unicode_literals from django.test import SimpleTestCase class CaseExtension(SimpleTestCase): _models = tuple() @classmethod def append_model(cls, model): cls._models += (model, ) def _pre_setup(self): super(CaseExtension, self)._pre_setup() self._map_models('create_table') def _post_teardown(self): # If we don't remove them in reverse order, then if we created table A # after table B and it has a foreignkey to table B, then trying to # remove B first will fail on some configurations, as documented # in issue #1 self._map_models('delete_table', reverse=True) super(CaseExtension, self)._post_teardown() def _map_models(self, method_name, reverse=False): for model in (reversed(self._models) if reverse else self._models): try: getattr(model, method_name)() except AttributeError: raise TypeError("{0} doesn't support table method {1}".format(model, method_name))
<commit_msg>Django: Test improvementes. Empty Pad test class added. <commit_before> from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2) <commit_after>from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase class PadTest(TestCase): def setUp(self): user_data = { 'email': 'user@example.com', 'password': 'secure_password' } user = User.objects.create(username=user_data['email'], **user_data) user.set_password(user_data['password']) user.save() self.client.login(**user_data) def _get_pad_data(self): pass def test_create_pad_success(self): pass
<commit_msg>Set response encoding based on apparent_encoding. Headers from drweeaboo.net incorrectly tell us ISO-8859-1. <commit_before>import requests def user_guide(): r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html") return r.text, r.status_code <commit_after>import requests def user_guide(): r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html") r.encoding = r.apparent_encoding return r.text, r.status_code
<commit_msg>Disable test untestable without x server<commit_before>package org.jrebirth.af.core.command.basic.multi; import org.jrebirth.af.core.command.basic.BasicCommandTest; import org.junit.Test; //@Ignore("JavaFX can't be run in headless mode yet") public class MultiCommandTest extends BasicCommandTest { @Test public void sequentialTest1() { System.out.println("Sequential Test default"); runCommand(DefaultSequentialCommand.class); } @Test public void sequentialTest2() { System.out.println("Sequential Test annotation"); runCommand(AnnotatedSequentialCommand.class); } @Test public void sequentialTest3() { System.out.println("Sequential Test constructor"); runCommand(ConstructorSequentialCommand.class); } @Test public void parallelTest1() { System.out.println("Parallel Test default"); runCommand(DefaultParallelCommand.class); } @Test public void parallelTest2() { System.out.println("Parallel Test annotation"); runCommand(AnnotatedParallelCommand.class); } @Test public void parallelTest3() { System.out.println("Parallel Test constructor"); runCommand(ConstructorParallelCommand.class); } } <commit_after>package org.jrebirth.af.core.command.basic.multi; import org.jrebirth.af.core.command.basic.BasicCommandTest; import org.junit.Ignore; import org.junit.Test; @Ignore("JavaFX can't be run in headless mode yet") public class MultiCommandTest extends BasicCommandTest { @Test public void sequentialTest1() { System.out.println("Sequential Test default"); runCommand(DefaultSequentialCommand.class); } @Test public void sequentialTest2() { System.out.println("Sequential Test annotation"); runCommand(AnnotatedSequentialCommand.class); } @Test public void sequentialTest3() { System.out.println("Sequential Test constructor"); runCommand(ConstructorSequentialCommand.class); } @Test public void parallelTest1() { System.out.println("Parallel Test default"); runCommand(DefaultParallelCommand.class); } @Test public void parallelTest2() { System.out.println("Parallel Test annotation"); runCommand(AnnotatedParallelCommand.class); } @Test public void parallelTest3() { System.out.println("Parallel Test constructor"); runCommand(ConstructorParallelCommand.class); } }
<commit_msg>Include display metadata in mime bundle <commit_before>from IPython.display import display, JSON import json # Running `npm run build` will create static resources in the static # directory of this Python package (and create that directory if necessary). def _jupyter_labextension_paths(): return [{ 'name': '{{cookiecutter.extension_name}}', 'src': 'static', }] def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'static', 'dest': '{{cookiecutter.extension_name}}', 'require': '{{cookiecutter.extension_name}}/extension' }] # A display class that can be used within a notebook. E.g.: # from {{cookiecutter.extension_name}} import {{cookiecutter.mime_short_name}} # {{cookiecutter.mime_short_name}}(data) class {{cookiecutter.mime_short_name}}(JSON): @property def data(self): return self._data @data.setter def data(self, data): if isinstance(data, str): data = json.loads(data) self._data = data def _ipython_display_(self): bundle = { '{{cookiecutter.mime_type}}': self.data, 'text/plain': '<{{cookiecutter.extension_name}}.{{cookiecutter.mime_short_name}} object>' } display(bundle, raw=True) <commit_after>from IPython.display import display, JSON import json # Running `npm run build` will create static resources in the static # directory of this Python package (and create that directory if necessary). def _jupyter_labextension_paths(): return [{ 'name': '{{cookiecutter.extension_name}}', 'src': 'static', }] def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'static', 'dest': '{{cookiecutter.extension_name}}', 'require': '{{cookiecutter.extension_name}}/extension' }] # A display class that can be used within a notebook. E.g.: # from {{cookiecutter.extension_name}} import {{cookiecutter.mime_short_name}} # {{cookiecutter.mime_short_name}}(data) class {{cookiecutter.mime_short_name}}(JSON): """A display class for displaying {{cookiecutter.mime_short_name}} visualizations in the Jupyter Notebook and IPython kernel. {{cookiecutter.mime_short_name}} expects a JSON-able dict, not serialized JSON strings. Scalar types (None, number, string) are not allowed, only dict containers. """ def _data_and_metadata(self): return self.data, self.metadata def _ipython_display_(self): bundle = { '{{cookiecutter.mime_type}}': self.data, 'text/plain': '<{{cookiecutter.extension_name}}.{{cookiecutter.mime_short_name}} object>' } metadata = { '{{cookiecutter.mime_type}}': self.metadata } display(bundle, metadata=metadata, raw=True)
<commit_msg>Update mock method to match changed return value for libhxl <commit_before>"""Unit test suite for HXL proxy.""" import os import re import hxl import unittest.mock TEST_DATA_FILE = os.path.join(os.path.dirname(__file__), 'test-data.sql') # # Mock URL access for local testing # def mock_open_url(url, allow_local=False, timeout=None, verify=True): """ Open local files instead of URLs. If it's a local file path, leave it alone; otherwise, open as a file under ./files/ This is meant as a side effect for unittest.mock.Mock """ if re.match(r'https?:', url): # Looks like a URL filename = re.sub(r'^.*/([^/]+)$', '\\1', url) path = resolve_path('files/' + filename) else: # Assume it's a file path = url return open(path, 'rb') def resolve_path(filename): """Resolve a relative path against this module's directory.""" return os.path.join(os.path.dirname(__file__), filename) # Target function to replace for mocking URL access. URL_MOCK_TARGET = 'hxl.io.open_url_or_file' # Mock object to replace hxl.io.make_stream URL_MOCK_OBJECT = unittest.mock.Mock() URL_MOCK_OBJECT.side_effect = mock_open_url # end <commit_after>"""Unit test suite for HXL proxy.""" import os import re import hxl import unittest.mock TEST_DATA_FILE = os.path.join(os.path.dirname(__file__), 'test-data.sql') # # Mock URL access for local testing # def mock_open_url(url, allow_local=False, timeout=None, verify=True): """ Open local files instead of URLs. If it's a local file path, leave it alone; otherwise, open as a file under ./files/ This is meant as a side effect for unittest.mock.Mock """ if re.match(r'https?:', url): # Looks like a URL filename = re.sub(r'^.*/([^/]+)$', '\\1', url) path = resolve_path('files/' + filename) else: # Assume it's a file path = url return (open(path, 'rb'), None, None, None) def resolve_path(filename): """Resolve a relative path against this module's directory.""" return os.path.join(os.path.dirname(__file__), filename) # Target function to replace for mocking URL access. URL_MOCK_TARGET = 'hxl.io.open_url_or_file' # Mock object to replace hxl.io.make_stream URL_MOCK_OBJECT = unittest.mock.Mock() URL_MOCK_OBJECT.side_effect = mock_open_url # end
<commit_msg>Remove non-MVP Graph API calls <commit_before>package edu.deanza.calendar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.facebook.AccessToken; import com.facebook.FacebookSdk; import com.facebook.GraphRequest; import com.facebook.GraphResponse; import com.facebook.HttpMethod; import com.facebook.appevents.AppEventsLogger; import edu.deanza.R; public class SearchActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); //track analytics using FB--can remove feature later FacebookSdk.sdkInitialize(getApplicationContext()); AppEventsLogger.activateApp(this); } private void FacebookStalking() { long [] facebookGroups = {885940821502890L, //De Anza DECA Club 219645201389350L, //VIDA: Vasconcellos Institute for Democracy In Action 2236277819L, //De Anza College }; long [] facebookPages = {265047173570399L, //ICC 192472534143760L //DASB }; } private void grabFacebookPage(int id) { /* make the API call */ new GraphRequest( AccessToken.getCurrentAccessToken(), "/" + id + "/events", null, HttpMethod.GET, new GraphRequest.Callback() { public void onCompleted(GraphResponse response) { /* handle the result */ } } ).executeAsync(); } }<commit_after>package edu.deanza.calendar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import edu.deanza.R; public class SearchActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); } }
<commit_msg>Add snat ip or net validator. <commit_before> from flask_wtf import Form from wtforms import TextField from wtforms.validators import Required, IPAddress class SnatForm(Form): source = TextField(u'SNAT源IP(段)', validators=[Required(message=u'这是一个必选项!')]) gateway = TextField(u'SNAT转发IP', validators=[Required(message=u'这是一个必选项!'), IPAddress(message=u'无效的ip 地址!')]) <commit_after> from flask_wtf import Form from wtforms import TextField, ValidationError from wtforms.validators import Required, IPAddress def IPorNet(message=u"无效的IP 或网段!"): def _ipornet(form, field): value = field.data ip = value.split('/')[0] if '/' in value: try: mask = int(value.split('/')[1]) except: raise ValidationError(message) if mask < 0 or mask > 32: raise ValidationError(message) parts = ip.split('.') if len(parts) == 4 and all(x.isdigit() for x in parts): numbers = list(int(x) for x in parts) if not all(num >= 0 and num < 256 for num in numbers): raise ValidationError(message) return True raise ValidationError(message) return _ipornet class SnatForm(Form): source = TextField(u'SNAT源IP(段)', validators=[Required(message=u'这是一个必选项!'), IPorNet(message=u"无效的IP 或网段!")]) gateway = TextField(u'SNAT转发IP', validators=[Required(message=u'这是一个必选项!'), IPAddress(message=u'无效的IP 地址!')])
<commit_msg>Set docstring for "path" function <commit_before>import os def path(*p): import __main__ project_root = os.path.dirname(os.path.realpath(__main__.__file__)) return os.path.join(project_root, *p) <commit_after>import os def path(*p): """Return full path of a directory inside project's root""" import __main__ project_root = os.path.dirname(os.path.realpath(__main__.__file__)) return os.path.join(project_root, *p)
<commit_msg>Add ssh thin_dir integration test <commit_before>''' salt-ssh testing ''' # Import Python libs from __future__ import absolute_import # Import salt testing libs from tests.support.case import SSHCase class SSHTest(SSHCase): ''' Test general salt-ssh functionality ''' def test_ping(self): ''' Test a simple ping ''' ret = self.run_function('test.ping') self.assertTrue(ret, 'Ping did not return true') <commit_after>''' salt-ssh testing ''' # Import Python libs from __future__ import absolute_import import os import shutil # Import salt testing libs from tests.support.case import SSHCase class SSHTest(SSHCase): ''' Test general salt-ssh functionality ''' def test_ping(self): ''' Test a simple ping ''' ret = self.run_function('test.ping') self.assertTrue(ret, 'Ping did not return true') def test_thin_dir(self): ''' test to make sure thin_dir is created and salt-call file is included ''' thin_dir = self.run_function('config.get', ['thin_dir'], wipe=False) os.path.isdir(thin_dir) os.path.exists(os.path.join(thin_dir, 'salt-call')) os.path.exists(os.path.join(thin_dir, 'running_data')) def tearDown(self): ''' make sure to clean up any old ssh directories ''' salt_dir = self.run_function('config.get', ['thin_dir'], wipe=False) if os.path.exists(salt_dir): shutil.rmtree(salt_dir)
<commit_msg>Raise error on undefined type <commit_before>from noopy import lambda_functions from noopy.endpoint import Endpoint from noopy.endpoint import methods def dispatch(event, context): print event if event['type'] == 'APIGateway': path = event['path'] method = getattr(methods, event['method']) endpoint = Endpoint.endpoints[Endpoint(path, method)] return endpoint(event.get('params', {}), context) if event['type'] == 'Lambda': funcs = [f for f in lambda_functions if f.func_name == event['function_name']] if len(funcs) != 1: raise ValueError('One and only one function "{}" needed.'.format(event['function_name'])) funcs[0](event.get('params', {}), context) <commit_after>from noopy import lambda_functions from noopy.endpoint import Endpoint from noopy.endpoint import methods def dispatch(event, context): print event if event['type'] == 'APIGateway': path = event['path'] method = getattr(methods, event['method']) endpoint = Endpoint.endpoints[Endpoint(path, method)] return endpoint(event.get('params', {}), context) if event['type'] == 'Lambda': funcs = [f for f in lambda_functions if f.func_name == event['function_name']] if len(funcs) != 1: raise ValueError('One and only one function "{}" needed.'.format(event['function_name'])) return funcs[0](event.get('params', {}), context) raise ValueError('Undefined type: "%s"' % event['type'])
<commit_msg>Cover this exception with a test <commit_before>import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('') <commit_after>import pytest import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('') def test_transaction_raises_error_for_bad_commit(self): store = self.open_storage() transaction = store.transaction(read_only=True) transaction_map = transaction.__enter__() transaction_map['new_key'] = 'new_value' with pytest.raises(RuntimeError): transaction.__exit__(None, None, None) assert 'new_key' not in store.data
<commit_msg>Use tuple to represent version <commit_before>from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app # noqa __version__ = "1.0.0" <commit_after>from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app # noqa VERSION = (1, 0, 0, "dev") def get_version(version): assert len(version) == 4, "Version must be formatted as (major, minor, micro, state)" major, minor, micro, state = version assert isinstance(major, int), "Major version must be an integer." assert isinstance(minor, int), "Minor version must be an integer." assert isinstance(micro, int), "Micro version must be an integer." assert state in ('final', 'dev'), "State must be either final or dev." if state == 'final': return "{}.{}.{}".format(major, minor, micro) else: return "{}.{}.{}.{}".format(major, minor, micro, state) __version__ = get_version(VERSION)
<commit_msg>Fix ratio followers/following only displayed for "humans" <commit_before>import os from libraries.models import Tweet, User from config import app_config as cfg from libraries.graphs.graph import Graph # Twitter API configuration consumer_key = cfg.twitter["consumer_key"] consumer_secret = cfg.twitter["consumer_secret"] access_token = cfg.twitter["access_token"] access_token_secret = cfg.twitter["access_token_secret"] # Start current_path = os.path.dirname(os.path.abspath(__file__)) # Average mentions per user path ="{}/images/avg_mentions.png".format(current_path) graph = Graph(path) avg_mentions_per_user = Tweet.avg_mentions_per_user().values() avg_mentions_per_bot = Tweet.avg_mentions_per_user(True).values() graph.avg_tweets(avg_mentions_per_user, avg_mentions_per_bot, path) path ="{}/images/vocabulary.png".format(current_path) graph.vocabulary(Tweet.vocabulary_size().values(), Tweet.vocabulary_size(True).values(), path) path ="{}/images/followers_following.png".format(current_path) graph.ratio_followers_following( User.ratio_followers_following_per_users(), User.ratio_followers_following_per_users(), path ) <commit_after>import os from libraries.models import Tweet, User from config import app_config as cfg from libraries.graphs.graph import Graph # Twitter API configuration consumer_key = cfg.twitter["consumer_key"] consumer_secret = cfg.twitter["consumer_secret"] access_token = cfg.twitter["access_token"] access_token_secret = cfg.twitter["access_token_secret"] # Start current_path = os.path.dirname(os.path.abspath(__file__)) # Average mentions per user path ="{}/images/avg_mentions.png".format(current_path) graph = Graph(path) avg_mentions_per_user = Tweet.avg_mentions_per_user().values() avg_mentions_per_bot = Tweet.avg_mentions_per_user(True).values() graph.avg_tweets(avg_mentions_per_user, avg_mentions_per_bot, path) path ="{}/images/vocabulary.png".format(current_path) graph.vocabulary(Tweet.vocabulary_size().values(), Tweet.vocabulary_size(True).values(), path) path ="{}/images/followers_following.png".format(current_path) graph.ratio_followers_following( User.ratio_followers_following_per_users(), User.ratio_followers_following_per_users(is_bot=True), path )
<commit_msg>Change type of testText's pos <commit_before>module Protonic.Render where import Control.Exception (bracket) import Control.Monad.Managed (managed, runManaged) import Control.Monad.Reader import Data.Word (Word8) import Linear.Affine (Point (..)) import Linear.V2 import Linear.V4 import qualified Graphics.UI.SDL.TTF as TTF import SDL (($=)) import qualified SDL import SDL.Raw (Color (..)) import Protonic.Core clearBy :: V4 Int -> ProtoT () clearBy color = do r <- asks renderer SDL.rendererDrawColor r $= fromIntegral <$> color SDL.clear r testText :: Integral a => V2 a -> V4 Word8 -> String -> ProtoT () testText pos (V4 r g b a) str = do font <- asks systemFont rndr <- asks renderer liftIO $ do (w,h) <- TTF.sizeText font str runManaged $ do surface <- managed $ bracket (mkSurface <$> TTF.renderTextBlended font str (Color r g b a)) SDL.freeSurface texture <- managed $ bracket (SDL.createTextureFromSurface rndr surface) SDL.destroyTexture let rect = Just $ SDL.Rectangle (P pos') (fromIntegral <$> V2 w h) SDL.copy rndr texture Nothing rect where mkSurface p = SDL.Surface p Nothing pos' = fromIntegral <$> pos <commit_after>module Protonic.Render where import Control.Exception (bracket) import Control.Monad.Managed (managed, runManaged) import Control.Monad.Reader import Data.Word (Word8) import Linear.Affine (Point (..)) import Linear.V2 import Linear.V4 import qualified Graphics.UI.SDL.TTF as TTF import SDL (($=)) import qualified SDL import SDL.Raw (Color (..)) import Protonic.Core clearBy :: V4 Int -> ProtoT () clearBy color = do r <- asks renderer SDL.rendererDrawColor r $= fromIntegral <$> color SDL.clear r testText :: V2 Int -> V4 Word8 -> String -> ProtoT () testText pos (V4 r g b a) str = do font <- asks systemFont rndr <- asks renderer liftIO $ do (w,h) <- TTF.sizeText font str runManaged $ do surface <- managed $ bracket (mkSurface <$> TTF.renderTextBlended font str (Color r g b a)) SDL.freeSurface texture <- managed $ bracket (SDL.createTextureFromSurface rndr surface) SDL.destroyTexture let rect = Just $ SDL.Rectangle (P pos') (fromIntegral <$> V2 w h) SDL.copy rndr texture Nothing rect where mkSurface p = SDL.Surface p Nothing pos' = fromIntegral <$> pos
<commit_msg>Add is_silent & is_dry_run arguments to module API This way all the features of the command line commands is also in the module API <commit_before> import sys assert sys.version_info >= (3, 3), "Requires Python 3.3 or Greater" import dploy.main as main def stow(sources, dest): """ sub command stow """ main.Stow(sources, dest) # pylint: disable=protected-access def unstow(sources, dest): """ sub command unstow """ main.UnStow(sources, dest) # pylint: disable=protected-access def link(source, dest): """ sub command link """ main.Link(source, dest) # pylint: disable=protected-access <commit_after> import sys assert sys.version_info >= (3, 3), "Requires Python 3.3 or Greater" import dploy.main as main def stow(sources, dest, is_silent=True, is_dry_run=False): """ sub command stow """ main.Stow(sources, dest, is_silent, is_dry_run) def unstow(sources, dest, is_silent=True, is_dry_run=False): """ sub command unstow """ main.UnStow(sources, dest, is_silent, is_dry_run) def link(source, dest, is_silent=True, is_dry_run=False): """ sub command link """ main.Link(source, dest, is_silent, is_dry_run)
<commit_msg>Add negative test for StreamUtils.getStreamContents <commit_before>package org.scribe.utils; import java.io.ByteArrayInputStream; import java.io.InputStream; import org.junit.Test; import static org.junit.Assert.*; public class StreamUtilsTest { @Test public void shouldCorrectlyDecodeAStream() { String value = "expected"; InputStream is = new ByteArrayInputStream(value.getBytes()); String decoded = StreamUtils.getStreamContents(is); assertEquals("expected", decoded); } @Test(expected = IllegalArgumentException.class) public void shouldFailForNullParameter() { InputStream is = null; StreamUtils.getStreamContents(is); fail("Must throw exception before getting here"); } } <commit_after>package org.scribe.utils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import org.junit.Test; import static org.junit.Assert.*; public class StreamUtilsTest { @Test public void shouldCorrectlyDecodeAStream() { String value = "expected"; InputStream is = new ByteArrayInputStream(value.getBytes()); String decoded = StreamUtils.getStreamContents(is); assertEquals("expected", decoded); } @Test(expected = IllegalArgumentException.class) public void shouldFailForNullParameter() { InputStream is = null; StreamUtils.getStreamContents(is); fail("Must throw exception before getting here"); } @Test(expected = IllegalStateException.class) public void shouldFailWithBrokenStream() { // This object simulates problems with input stream. final InputStream is = new InputStream() { @Override public int read() throws IOException { throw new IOException(); } }; StreamUtils.getStreamContents(is); fail("Must throw exception before getting here"); } }
<commit_msg>Add slightly more spacing in output. Monotone-Parent: 6b99470e62e578d124e0fbbf7a434da82aeb3a5b Monotone-Revision: 605fe263cd8d7dada4205b576819b218d4ddb8df <commit_before> int main(int argc, char** argv) { const std::vector<FNVParam> fnvParams = FNVParam::getAll(); const std::vector<FNVAlgo> fnvAlgos = FNVAlgo::getAll(); const std::vector<Constraint> constraints = Constraint::getAll(); BOOST_FOREACH(const FNVParam& fnvParam, fnvParams) { std::cout << "Problem size: " << fnvParam.getWidth() << std::endl; BOOST_FOREACH(const FNVAlgo& fnvAlgo, fnvAlgos) { std::cout << "Algorithm: FNV-" << fnvAlgo.getName() << std::endl; const Constraint nullConstraint = Constraint::getNull(); std::cout << "Constraint: " << nullConstraint.getName() << std::endl; FNVSolver solver(fnvParam, fnvAlgo, nullConstraint); solver.solve(); const int solutionLength = solver.getSolutionLength(); BOOST_FOREACH(const Constraint& constraint, constraints) { std::cout << "Constraint: " << constraint.getName() << std::endl; FNVSolver solver(fnvParam, fnvAlgo, constraint, solutionLength); solver.solve(); } } } } <commit_after> int main(int argc, char** argv) { const std::vector<FNVParam> fnvParams = FNVParam::getAll(); const std::vector<FNVAlgo> fnvAlgos = FNVAlgo::getAll(); const std::vector<Constraint> constraints = Constraint::getAll(); BOOST_FOREACH(const FNVParam& fnvParam, fnvParams) { std::cout << "Problem size: " << fnvParam.getWidth() << std::endl; BOOST_FOREACH(const FNVAlgo& fnvAlgo, fnvAlgos) { std::cout << "Algorithm: FNV-" << fnvAlgo.getName() << std::endl; const Constraint nullConstraint = Constraint::getNull(); std::cout << "Constraint: " << nullConstraint.getName() << std::endl; FNVSolver solver(fnvParam, fnvAlgo, nullConstraint); solver.solve(); const int solutionLength = solver.getSolutionLength(); BOOST_FOREACH(const Constraint& constraint, constraints) { std::cout << "Constraint: " << constraint.getName() << std::endl; FNVSolver solver(fnvParam, fnvAlgo, constraint, solutionLength); solver.solve(); } } std::cout << std::endl; } }
<commit_msg>Fix test after JUnit upgrade<commit_before>package patterns.document; import java.util.HashMap; import java.util.Map; import java.util.OptionalDouble; import java.util.OptionalInt; import org.junit.Test; import org.junit.Assert; public class CarTest { private static final double PRICE = 100.0; private static final String MODEL = "Audi"; private static final String COLOR = "red"; private static final int WHEELS_COUNT = 4; @Test public void testCreateCar() throws Exception { Map<String, Object> entries = new HashMap<>(); Car car = new Car(entries); car.put(ColorTrait.KEY, COLOR); car.put(ModelTrait.KEY, MODEL); car.put(PriceTrait.KEY, PRICE); car.put(WheelsTrait.KEY, WHEELS_COUNT); String color = car.getColor(); Assert.assertEquals(COLOR, color); String model = car.getModel(); Assert.assertEquals(MODEL, model); OptionalDouble price = car.getPrice(); Assert.assertEquals(PRICE, price.getAsDouble()); OptionalInt wheels = car.getWheels(); Assert.assertEquals(WHEELS_COUNT, wheels.getAsInt()); } } <commit_after>package patterns.document; import java.util.HashMap; import java.util.Map; import java.util.OptionalDouble; import java.util.OptionalInt; import org.junit.Assert; import org.junit.Test; public class CarTest { private static final double DELTA = 0.000001; private static final double PRICE = 100.0; private static final String MODEL = "Audi"; private static final String COLOR = "red"; private static final int WHEELS_COUNT = 4; @Test public void testCreateCar() throws Exception { Map<String, Object> entries = new HashMap<>(); Car car = new Car(entries); car.put(ColorTrait.KEY, COLOR); car.put(ModelTrait.KEY, MODEL); car.put(PriceTrait.KEY, PRICE); car.put(WheelsTrait.KEY, WHEELS_COUNT); String color = car.getColor(); Assert.assertEquals(COLOR, color); String model = car.getModel(); Assert.assertEquals(MODEL, model); OptionalDouble price = car.getPrice(); Assert.assertEquals(PRICE, price.getAsDouble(), DELTA); OptionalInt wheels = car.getWheels(); Assert.assertEquals(WHEELS_COUNT, wheels.getAsInt()); } }
<commit_msg>Fix Django 1.9 import error <commit_before>from django import VERSION from .views import AutocompleteView, RegistryView try: from django.conf.urls import patterns, url except ImportError: # Django < 1.5 from django.conf.urls.defaults import patterns, url urlpatterns = [ url(r'^(?P<autocomplete>[-\w]+)/$', AutocompleteView.as_view(), name='autocomplete_light_autocomplete' ), url(r'^$', RegistryView.as_view(), name='autocomplete_light_registry' ), ] if VERSION < (1, 9): urlpatterns = patterns('', *urlpatterns) <commit_after>from django import VERSION from .views import AutocompleteView, RegistryView if VERSION > (1, 9): from django.conf.urls import url else: try: from django.conf.urls import patterns, url except ImportError: # Django < 1.5 from django.conf.urls.defaults import patterns, url urlpatterns = [ url(r'^(?P<autocomplete>[-\w]+)/$', AutocompleteView.as_view(), name='autocomplete_light_autocomplete' ), url(r'^$', RegistryView.as_view(), name='autocomplete_light_registry' ), ] if VERSION < (1, 9): urlpatterns = patterns('', *urlpatterns)
<commit_msg>Add support for apicalls in Bash package <commit_before> from lib.core.packages import Package class Bash(Package): """ Bash shell script analysys package. """ def start(self): # Some scripts are not executable, so we have to use /bin/bash to # invoke them self.args = [self.target] + self.args self.target = "/bin/bash" if "method" in self.options: method = self.options["method"] else: # fallback to dtruss method = "dtruss" if "dtruss" in method: for x in self._start_dtruss(): yield x else: yield "Invalid analysis method \"%S\" for package \"Bash\"" % method <commit_after> from lib.core.packages import Package class Bash(Package): """ Bash shell script analysys package. """ def start(self): # Some scripts are not executable, so we have to use /bin/bash to # invoke them self.args = [self.target] + self.args self.target = "/bin/bash" if "method" in self.options: method = self.options["method"] else: # fallback to dtruss method = "dtruss" if "dtruss" in method: for x in self._start_dtruss(): yield x elif "apicalls" in method: for x in self._start_apicalls(): yield x else: yield "Invalid analysis method \"%S\" for package \"Bash\"" % method
<commit_msg>Add default implementation of <$ <commit_before>{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} -- | A linear version of a Functor module Data.Functor.LFunctor where import Data.Linear (flip) class LFunctor f where fmap :: (a ⊸ b) ⊸ f a ⊸ f b (<$) :: a -> f () ⊸ f a (<$>) :: LFunctor f => (a ⊸ b) ⊸ f a ⊸ f b (<$>) = fmap ($>) :: LFunctor f => f () ⊸ a -> f a ($>) = flip (<$) infixl 4 $> infixl 4 <$ infixl 4 <$> <commit_after>{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} -- | A linear version of a Functor module Data.Functor.LFunctor where import Data.Linear (flip, liftUnit) import Prelude ((.)) class LFunctor f where fmap :: (a ⊸ b) ⊸ f a ⊸ f b (<$) :: a -> f () ⊸ f a (<$) = fmap . liftUnit (<$>) :: LFunctor f => (a ⊸ b) ⊸ f a ⊸ f b (<$>) = fmap ($>) :: LFunctor f => f () ⊸ a -> f a ($>) = flip (<$) infixl 4 $> infixl 4 <$ infixl 4 <$>
<commit_msg>Use full path to find mods <commit_before>from imp import find_module, load_module import os class SourceExtension(object): def __init__(self, mod): self.initialized = False self.mod = mod self.renew = mod.renew self.Source = mod.Source def __call__(self, _ses, **kwargs): if not self.initialized or self.renew: self.fetcher = self.Source(_ses, **kwargs) self.initialized = True return self.fetcher.getseries(_ses, **kwargs) sources = {} curdir = os.path.dirname(os.path.realpath(__file__)) extension_names = os.listdir(os.path.join(curdir,'source')) for name in extension_names: ext = find_module(name, ['source']) mod = load_module(name, *ext) sources[mod.stype] = SourceExtension(mod)<commit_after>from imp import find_module, load_module import os class SourceExtension(object): def __init__(self, mod): self.initialized = False self.mod = mod self.renew = mod.renew self.Source = mod.Source def __call__(self, _ses, **kwargs): if not self.initialized or self.renew: self.fetcher = self.Source(_ses, **kwargs) self.initialized = True return self.fetcher.getseries(_ses, **kwargs) sources = {} curdir = os.path.dirname(os.path.realpath(__file__)) sourcedir = os.path.join(curdir,'source') extension_names = os.listdir(sourcedir) for name in extension_names: ext = find_module(name, [sourcedir]) mod = load_module(name, *ext) sources[mod.stype] = SourceExtension(mod)
<commit_msg>Update sys.path to import heatmap <commit_before>"""Test coordinate classes.""" import sys try: import unittest2 as unittest # Python 2.6 except ImportError: import unittest import heatmap as hm class Tests(unittest.TestCase): # To remove Python 3's # "DeprecationWarning: Please use assertRaisesRegex instead" if sys.version_info[0] == 2: assertRaisesRegex = unittest.TestCase.assertRaisesRegexp def test_basic(self): '''Test Configuration class.''' # Act config = hm.Configuration(use_defaults=True) # Assert self.assertEqual(config.margin, 0) self.assertEqual(config.frequency, 1) def test_fill_missing_no_input(self): '''Test Configuration class.''' # Arrange config = hm.Configuration(use_defaults=True) # Act / Assert with self.assertRaisesRegex(ValueError, "no input specified"): config.fill_missing() if __name__ == '__main__': unittest.main() <commit_after>"""Test coordinate classes.""" import sys try: import unittest2 as unittest # Python 2.6 except ImportError: import unittest ROOT_DIR = os.path.split(os.path.abspath(os.path.dirname(__file__)))[0] sys.path.append(ROOT_DIR) import heatmap as hm class Tests(unittest.TestCase): # To remove Python 3's # "DeprecationWarning: Please use assertRaisesRegex instead" if sys.version_info[0] == 2: assertRaisesRegex = unittest.TestCase.assertRaisesRegexp def test_basic(self): '''Test Configuration class.''' # Act config = hm.Configuration(use_defaults=True) # Assert self.assertEqual(config.margin, 0) self.assertEqual(config.frequency, 1) def test_fill_missing_no_input(self): '''Test Configuration class.''' # Arrange config = hm.Configuration(use_defaults=True) # Act / Assert with self.assertRaisesRegex(ValueError, "no input specified"): config.fill_missing() if __name__ == '__main__': unittest.main()
<commit_msg>Make talk status editale from the talk list overview <commit_before>from django.contrib import admin from wafer.talks.models import Talk class TalkAdmin(admin.ModelAdmin): list_display = ('corresponding_author', 'title', 'status') admin.site.register(Talk, TalkAdmin) <commit_after>from django.contrib import admin from wafer.talks.models import Talk class TalkAdmin(admin.ModelAdmin): list_display = ('corresponding_author', 'title', 'status') list_editable = ('status',) admin.site.register(Talk, TalkAdmin)
<commit_msg>Fix not existing .apks failing <commit_before>package de.philipphager.disclosure.feature.analyser.app; import dalvik.system.DexFile; import de.philipphager.disclosure.database.app.model.App; import java.io.IOException; import java.util.Collections; import java.util.List; import rx.Observable; import timber.log.Timber; public class Apk { private static final int MIN_INDEX = 0; private final App app; private List<String> sortedClassNames; public Apk(App app) throws IOException { this.app = app; load(); } private void load() throws IOException { DexFile dexFile = new DexFile(app.sourceDir()); List<String> classNames = Collections.list(dexFile.entries()); sortedClassNames = Observable.from(classNames) .distinct() .toSortedList() .toBlocking() .first(); } public boolean containsPackage(String packageName) { String currentThread = Thread.currentThread().getName(); Timber.d("%s : Searching for package %s in app %s", currentThread, packageName, app.label()); int index = Collections.binarySearch(sortedClassNames, packageName, (currentItem, key) -> { if(currentItem.startsWith(key)) { return 0; } return currentItem.compareTo(key); }); return index >= MIN_INDEX; } } <commit_after>package de.philipphager.disclosure.feature.analyser.app; import dalvik.system.DexFile; import de.philipphager.disclosure.database.app.model.App; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import rx.Observable; import timber.log.Timber; public class Apk { private static final int MIN_INDEX = 0; private final App app; private List<String> sortedClassNames; public Apk(App app) throws IOException { this.app = app; load(); } private void load() throws IOException { File file = new File(app.sourceDir()); List<String> classNames = new ArrayList<>(); if (file.exists()) { DexFile dexFile = new DexFile(app.sourceDir()); classNames.addAll(Collections.list(dexFile.entries())); } sortedClassNames = Observable.from(classNames) .distinct() .toSortedList() .toBlocking() .first(); } public boolean containsPackage(String packageName) { String currentThread = Thread.currentThread().getName(); Timber.d("%s : Searching for package %s in app %s", currentThread, packageName, app.label()); int index = Collections.binarySearch(sortedClassNames, packageName, (currentItem, key) -> { if (currentItem.startsWith(key)) { return 0; } return currentItem.compareTo(key); }); return index >= MIN_INDEX; } }
<commit_msg>Fix updateEnvironment mutation not setting "updated" date <commit_before>const { knex } = require('../../util/db'); export const Sql = { updateEnvironment: ({ id, patch }: { id: number, patch: { [key: string]: any } }) => knex('environment') .where('id', '=', id) .update(patch) .toString(), selectEnvironmentById: (id: number) => knex('environment') .where('id', '=', id) .toString(), selectEnvironmentByNameAndProject: (name: string, projectId: number) => knex('environment') .where('name', '=', name) .andWhere('project', '=', projectId) .toString(), truncateEnvironment: () => knex('environment') .truncate() .toString(), insertService: ( environment: number, name: string, ) => knex('environment_service') .insert({ environment, name, }) .toString(), selectServicesByEnvironmentId: (id: number) => knex('environment_service') .where('environment', '=', id) .toString(), deleteServices: (id: number) => knex('environment_service') .where('environment', '=', id) .delete() .toString(), }; <commit_after>const { knex } = require('../../util/db'); export const Sql = { updateEnvironment: ({ id, patch }: { id: number, patch: { [key: string]: any } }) => { const updatePatch = { ...patch, updated: knex.fn.now(), }; return knex('environment') .where('id', '=', id) .update(updatePatch) .toString(); }, selectEnvironmentById: (id: number) => knex('environment') .where('id', '=', id) .toString(), selectEnvironmentByNameAndProject: (name: string, projectId: number) => knex('environment') .where('name', '=', name) .andWhere('project', '=', projectId) .toString(), truncateEnvironment: () => knex('environment') .truncate() .toString(), insertService: ( environment: number, name: string, ) => knex('environment_service') .insert({ environment, name, }) .toString(), selectServicesByEnvironmentId: (id: number) => knex('environment_service') .where('environment', '=', id) .toString(), deleteServices: (id: number) => knex('environment_service') .where('environment', '=', id) .delete() .toString(), };